-
Notifications
You must be signed in to change notification settings - Fork 77
/
server.js
70 lines (53 loc) · 1.33 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');
var products = [
{
id: 1,
name: 'laptop'
},
{
id: 2,
name: 'microwave'
}
];
var currentId = 2;
var PORT = process.env.PORT || 3000;
app.use(express.static(__dirname));
app.use(bodyParser.json());
app.get('/products', function(req, res) {
res.send({ products: products });
});
app.post('/products', function(req, res) {
var productName = req.body.name;
currentId++;
products.push({
id: currentId,
name: productName
});
res.send('Successfully created product!');
});
app.put('/products/:id', function(req, res) {
var id = req.params.id;
var newName = req.body.newName;
var found = false;
products.forEach(function(product, index) {
if (!found && product.id === Number(id)) {
product.name = newName;
}
});
res.send('Succesfully updated product!');
});
app.delete('/products/:id', function(req, res) {
var id = req.params.id;
var found = false;
products.forEach(function(product, index) {
if (!found && product.id === Number(id)) {
products.splice(index, 1);
}
});
res.send('Successfully deleted product!');
});
app.listen(PORT, function() {
console.log('Server listening on ' + PORT);
});