-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
90 lines (73 loc) · 1.84 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
const express = require('express'),
bodyParser = require('body-parser'),
logger = require('morgan'),
{ mongoose } = require('./server/db/mongoose'),
{ Todo } = require('./server/models/todo'),
{ User } = require('./server/models/user'),
_ = require('lodash'),
bcrypt = require('bcryptjs')
const app = express()
const port = 3000
app.use(logger('dev'))
app.use(bodyParser.json())
/* HEROKU GET */
app.get('/times', function(request, response) {
var result = ''
var times = process.env.TIMES || 5
for (i=0; i < times; i++)
result += i + ' ';
response.send(result);
});
/* POST /users */
app.post('/users', (req, res) => {
const body = _.pick(req.body, ['email', 'password'])
const user = new User(body)
user.save()
.then(() => {
return user.generateAuthToken()
})
.then(token => {
res.header('x-auth', token).send(user)
})
.catch(e => {
res.status(400).send(e)
})
})
/* GET /users/me */
app.get('/users/me', (req, res) => {
const token = req.header('x-auth')
User.findByToken(token)
.then(user => {
res.send(user)
})
.catch(e => {
res.status(401).send(e)
})
})
/* TODO ROUTES */
app.post('/todos', (req, res) => {
const todo = new Todo({
text: req.body.text
})
todo.save().then((doc) => {
res.send(doc)
}, e => {
res.status(400).send(e)
})
})
app.post('/users/login', (req, res) => {
const body = _.pick(req.body, ['email', 'password'])
User.findByCredentials(body.email, body.password)
.then(user => {
return user.generateAuthToken()
})
.then(token => {
res.header('x-auth', token).send(user)
})
.catch(e => {
res.status(400).send(e)
})
})
app.listen(port, () => {
console.log(`Listening on port ${port}`)
})