-
Notifications
You must be signed in to change notification settings - Fork 268
/
server.js
82 lines (67 loc) · 2.47 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
const express = require('express');
const router = express.Router();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const {ShoppingList, Recipes} = require('./models');
const jsonParser = bodyParser.json();
const app = express();
// log the http layer
app.use(morgan('common'));
// we're going to add some items to ShoppingList
// so there's some data to look at
ShoppingList.create('beans', 2);
ShoppingList.create('tomatoes', 3);
ShoppingList.create('peppers', 4);
// adding some recipes to `Recipes` so there's something
// to retrieve.
Recipes.create(
'boiled white rice', ['1 cup white rice', '2 cups water', 'pinch of salt']);
Recipes.create(
'milkshake', ['2 tbsp cocoa', '2 cups vanilla ice cream', '1 cup milk']);
// when the root of this router is called with GET, return
// all current ShoppingList items
app.get('/shopping-list', (req, res) => {
res.json(ShoppingList.get());
});
app.post('/shopping-list', jsonParser, (req, res) => {
// ensure `name` and `budget` are in request body
const requiredFields = ['name', 'budget'];
for (let i=0; i<requiredFields.length; i++) {
const field = requiredFields[i];
if (!(field in req.body)) {
const message = `Missing \`${field}\` in request body`
console.error(message);
return res.status(400).send(message);
}
}
const item = ShoppingList.create(req.body.name, req.body.budget);
res.status(201).json(item);
});
app.delete('/shopping-list/:id', (req, res) => {
ShoppingList.delete(req.params.id);
console.log(`Deleted shopping list item \`${req.params.id}\``);
res.status(204).end();
});
// when new recipe added, ensure has required fields. if not,
// log error and return 400 status code with hepful message.
// if okay, add new item, and return it with a status 201.
app.post('/recipes', jsonParser, (req, res) => {
// ensure `name` and `budget` are in request body
const requiredFields = ['name', 'ingredients'];
for (let i=0; i<requiredFields.length; i++) {
const field = requiredFields[i];
if (!(field in req.body)) {
const message = `Missing \`${field}\` in request body`
console.error(message);
return res.status(400).send(message);
}
}
const item = Recipes.create(req.body.name, req.body.ingredients);
res.status(201).json(item);
});
app.get('/recipes', (req, res) => {
res.json(Recipes.get());
})
app.listen(process.env.PORT || 8080, () => {
console.log(`Your app is listening on port ${process.env.PORT || 8080}`);
});