forked from turingschool-examples/whats-cookin-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
95 lines (75 loc) · 2.39 KB
/
server.js
File metadata and controls
95 lines (75 loc) · 2.39 KB
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
const express = require('express');
const cors = require('cors');
const port = process.env.PORT || 3001;
const app = express();
const users = require('./data/users');
const recipes = require('./data/recipes');
const ingredients = require('./data/ingredients');
app.locals = {
title: 'What\'s Cookin API',
users,
recipes,
ingredients
}
app.use(cors());
app.use(express.json());
app.get('/api/v1/users', (req, res) => {
res.status(200).json({ users: app.locals.users });
});
app.get('/api/v1/recipes', (req, res) => {
res.status(200).json({ recipes: app.locals.recipes });
});
app.get('/api/v1/ingredients', (req, res) => {
res.status(200).json({ ingredients: app.locals.ingredients });
});
app.post('/api/v1/usersRecipes', (req, res) => {
const { userID, recipeID } = req.body;
for (let requiredParameter of ['userID', 'recipeID']) {
if (req.body[requiredParameter] === undefined) {
return res.status(422).json({
message: `You are missing a required parameter of ${requiredParameter}`
});
}
}
const foundUser = users.find(user => user.id === userID);
if (!foundUser) {
return res.status(422).json({
message: `No user found with ID ${userID}`
});
}
if (foundUser.recipesToCook.includes(recipeID)) {
return res.status(422).json({
message: `Recipe #${recipeID} is already a recipeToCook for User #${userID}`
});
}
foundUser.recipesToCook.push(recipeID);
return res.status(201).json({
message: `Recipe #${recipeID} was added for User #${userID}`
});
});
app.delete('/api/v1/usersRecipes', (req, res) => {
const { userID, recipeID } = req.body;
for (let requiredParameter of ['userID', 'recipeID']) {
if (req.body[requiredParameter] === undefined) {
return res.status(422).json({
message: `You are missing a required parameter of ${requiredParameter}`
});
}
}
const foundUser = users.find(user => user.id === userID);
if (!foundUser) {
return res.status(422).json({
message: `No user found with ID ${userID}`
});
}
foundUser.recipesToCook = foundUser.recipesToCook.filter(usersRecipeID => {
return usersRecipeID !== recipeID;
});
return res.status(200).json({
message: `Recipe #${recipeID} was removed for User #${userID}`
});
});
app.listen(port, () => {
console.log(`${app.locals.title} is now running on http://localhost:${port} !`)
});
module.exports = app;