-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.js
132 lines (116 loc) · 2.78 KB
/
routes.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
const app = require('express').Router();
const models = require('./db').models;
const jwt = require('jwt-simple');
const secret = process.env.SECRET || 'foo';
module.exports = app;
app.get('/products', (req, res, next)=> {
models.Product.findAll({ order: 'name'})
.then( products => res.send(products ))
.catch(next);
});
app.delete('/products/:id', (req, res, next)=> {
models.Product.destroy({ where: { id: req.params.id}})
.then( () => res.sendStatus(204))
.catch(next);
});
app.put('/users/favorite/:id', (req, res, next) => {
models.User.update(
{ favoriteProductId: req.body.id },
{ where: { id: req.params.id }})
.then( () => {
return models.User.findOne({
where: { id: req.params.id},
include: [
{
model: models.Product,
as: 'favoriteProduct'
},
{
model: models.Product,
as: 'worstProduct'
}
]})
.then( user => res.send( user))
})
.catch(next)
});
app.put('/users/worst/:id', (req, res, next) => {
models.User.update(
{ worstProductId: req.body.id },
{ where: { id: req.params.id }})
.then( () => {
return models.User.findOne({
where: { id: req.params.id},
include: [
{
model: models.Product,
as: 'favoriteProduct'
},
{
model: models.Product,
as: 'worstProduct'
}
]})
.then( user => res.send( user))
})
.catch(next)
});
app.post('/session', (req, res, next)=> {
models.User.findOne({
where: {
name: req.body.name,
password: req.body.password
}
})
.then( user => {
if(user){
const token = jwt.encode({id: user.id}, secret);
return res.send({ token });
}
return res.sendStatus(401);
})
.catch(next);
});
app.get('/session/:token', (req, res, next) => {
try{
const token = jwt.decode(req.params.token, secret);
models.User.findOne({
where: { id: token.id },
include: [
{
model: models.Product,
as: 'favoriteProduct'
},
{
model: models.Product,
as: 'worstProduct'
}]
})
.then( user => {
if(!user) {
return res.sendStatus(401)
}
console.log('user on login', user)
res.send(user)
})
}
catch(err) {
res.sendStatus(500)
}
});
app.get('/users', (req, res, next)=> {
models.User.findAll({
order: 'name',
include: [
{
model: models.Product,
as: 'favoriteProduct'
},
{
model: models.Product,
as: 'worstProduct'
}]
})
.then( users => res.send( users ))
.catch(next);
});