-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
70 lines (59 loc) · 1.64 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
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var ingredients = [
{
"id":"232kAk",
"text":"Eggs"
},
{
"id":"dkP345",
"text":"Milk"
},
{
"id":"dkcuu7",
"text":"Bacon"
},
{
"id":"73hdy",
"text":"Frogs Legs"
}
];
app.get('/ingredients', function(request, response) {
response.send(ingredients);
});
app.post('/ingredients', function(request, response) {
var ingredient = request.body;
if (!ingredient || ingredient.text === "") {
response.status(500).send({error: "Your ingredient must have text"});
} else {
ingredients.push(ingredient);
response.status(200).send(ingredients);
}
});
app.put('/ingredients/:ingredientId', function(request, response) {
var newText = request.body.text;
if (!newText || newText === "") {
response.status(500).send({error:"You must provide ingredient text"})
} else {
var objectFound = false;
for (var x = 0; x < ingredients.length; x++) {
var ing = ingredients[x];
if (ing.id === request.params.ingredientId) {
ingredients[x].text = newText;
objectFound = true;
break;
}
}
if (!objectFound) {
response.status(500).send({error:"Ingredient id not found"});
} else {
response.send(ingredients);
}
}
});
app.listen(3000, function() {
console.log("First API running on port 3000!");
});