-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathserver.js
80 lines (69 loc) · 1.56 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
//used for printing colors in console.log
const chalk = require('chalk');
const express = require('express');
const path = require('path');
const { syncAndSeed, models: { User, Sale, Car} } = require('./db');
const app = express();
app.use(express.json());
app.get('/', (req, res)=> res.sendFile(path.join(__dirname, 'index.html')));
app.use('/dist', express.static(path.join(__dirname, 'dist')));
app.post('/api/users/:id/sales', async(req, res, next)=> {
try {
res.status(201).send(await Sale.create({ userId: req.params.id, ...req.body }));
}
catch(ex){
next(ex);
}
});
app.delete('/api/sales/:id', async(req, res, next)=> {
try {
const sale = await Sale.findByPk(req.params.id);
await sale.destroy();
res.sendStatus(204);
}
catch(ex){
next(ex);
}
});
app.get('/api/users', async(req, res, next)=> {
try {
res.send(await User.findAll());
}
catch(ex){
next(ex);
}
});
app.get('/api/cars', async(req, res, next)=> {
try {
res.send(await Car.findAll());
}
catch(ex){
next(ex);
}
});
app.get('/api/users/:id/sales', async(req, res, next)=> {
try {
res.send(await Sale.findAll({
where: {
userId: req.params.id
},
include: [ Car ]
}));
}
catch(ex){
next(ex);
}
});
const init = async()=> {
try {
//if(process.env.SEED === 'true'){
await syncAndSeed();
//}
const port = process.env.PORT || 3000;
app.listen(port, ()=> console.log(chalk.green(`listening on port ${port}`)));
}
catch(ex){
console.log(chalk.red(ex.message));
}
};
init();