This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
forked from FullstackAcademy/acme-groceries
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
95 lines (82 loc) · 1.92 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
const express = require('express');
const { static } = express;
const path = require('path');
const app = express();
app.use(express.json());
app.use('/dist', static(path.join(__dirname, 'dist')));
app.use(express.json());
app.get('/', (req, res, next)=> res.sendFile(path.join(__dirname, 'index.html')));
app.get('/api/groceries', async(req, res, next)=> {
try {
res.send(await Grocery.findAll());
}
catch(ex){
next(ex);
}
});
app.put('/api/groceries/:id', async(req, res, next)=> {
try {
const grocery = await Grocery.findByPk(req.params.id);
await grocery.update(req.body);
res.send(grocery);
}
catch(ex){
next(ex);
}
});
app.post('/api/groceries', async(req, res, next)=> {
try {
res.send(await Grocery.create(req.body));
}
catch(ex){
next(ex);
}
});
app.post('/api/groceries/random', async(req, res, next)=> {
try {
res.send(await Grocery.createRandom());
}
catch(ex){
next(ex);
}
});
const init = async()=> {
try {
await syncAndSeed();
const port = process.env.PORT || 3000;
app.listen(port, ()=> console.log(`listening on port ${port}`));
}
catch(ex){
console.log(ex);
}
};
const Sequelize = require('sequelize');
const { STRING, BOOLEAN } = Sequelize;
const conn = new Sequelize(process.env.DATABASE_URL || 'postgres://localhost/acme_grocery_db');
const faker = require('faker');
const Grocery = conn.define('grocery', {
name: {
type: STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
purchased: {
type: BOOLEAN,
allowNull: false,
defaultValue: false
},
});
Grocery.createRandom = function(){
return Grocery.create({ name: faker.commerce.productName()});
}
const syncAndSeed = async()=> {
await conn.sync({ force: true });
await Promise.all([
Grocery.create({ name: 'milk' }),
Grocery.create({ name: 'eggs' }),
Grocery.create({ name: 'cheeze', purchased: true })
]);
};
init();