-
Notifications
You must be signed in to change notification settings - Fork 24
/
server.js
118 lines (100 loc) · 2.23 KB
/
server.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
const { conn, User, Thing } = require('./db');
const express = require('express');
const app = express();
const path = require('path');
app.use(express.json());
app.use('/dist', express.static('dist'));
app.get('/', (req, res)=> res.sendFile(path.join(__dirname, 'index.html')));
app.post('/api/users', async(req, res, next)=> {
try {
res.status(201).send(await User.create(req.body));
}
catch(ex){
next(ex);
}
});
app.post('/api/things', async(req, res, next)=> {
try {
res.status(201).send(await Thing.create(req.body));
}
catch(ex){
next(ex);
}
});
app.put('/api/things/:id', async(req, res, next)=> {
try {
const thing = await Thing.findByPk(req.params.id);
await thing.update(req.body);
res.send(thing);
}
catch(ex){
next(ex);
}
});
app.delete('/api/users/:id', async(req, res, next)=> {
try {
const user = await User.findByPk(req.params.id);
await user.destroy();
res.sendStatus(204);
}
catch(ex){
next(ex);
}
});
app.delete('/api/things/:id', async(req, res, next)=> {
try {
const thing = await Thing.findByPk(req.params.id);
await thing.destroy();
res.sendStatus(204);
}
catch(ex){
next(ex);
}
});
app.get('/api/things', async(req, res, next)=> {
try {
res.send(await Thing.findAll({
order: [['name']]
}));
}
catch(ex){
next(ex);
}
});
app.get('/api/users', async(req, res, next)=> {
try {
res.send(await User.findAll());
}
catch(ex){
next(ex);
}
});
app.use((err, req, res, next)=> {
console.log(err);
res.status(500).send(err);
});
const port = process.env.PORT || 3000;
app.listen(port, ()=> console.log(`listening on port ${port}`));
const init = async()=> {
try {
await conn.sync({ force: true });
const [moe, larry, lucy, ethyl] = await Promise.all(
['moe', 'larry', 'lucy', 'ethyl'].map( name => User.create({ name }))
);
const [foo, bar, bazz, quq, fizz] = await Promise.all(
['foo', 'bar', 'bazz', 'quq', 'fizz'].map( name => Thing.create({ name }))
);
foo.userId = moe.id;
bar.userId = lucy.id
bazz.userId = lucy.id
await Promise.all([
foo.save(),
bar.save(),
bazz.save()
]);
}
catch(ex){
console.log(ex);
}
};
init();