-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
65 lines (54 loc) · 1.54 KB
/
server.js
File metadata and controls
65 lines (54 loc) · 1.54 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
var express = require('express');
var path = require("path");
var app = express();
app.use(express.urlencoded());
app.use(express.json());
var memoryDb = {
products: [
{
title: 'My product',
pictureUri: 'http://thecatapi.com/api/images/get?format=src&type=gif',
description: 'My product description',
price: 50,
id: 0,
remaining: 50
},
{
title: 'My product',
pictureUri: 'http://thecatapi.com/api/images/get?format=src&type=gif',
description: 'My product description',
price: 50,
id: 1,
remaining: 50
}
]
};
app.get('/products/:pid', function (req, res, next) {
var products = memoryDb.products,
pid = parseInt(req.params.pid),
seekedProduct = null;
if (isNaN(pid) || pid < 0) {
res.status = 500;
return res.json({ error: 'invalid params' });
}
products.forEach(function (product) {
if (pid === product.id) {
seekedProduct = product;
}
});
if (seekedProduct) {
return res.json(seekedProduct);
}
else {
res.status = 404;
return res.json({ error: 'product not found' });
}
});
app.get('/products', function (req, res, next) {
var products = memoryDb.products;
return res.json(products);
});
app.use(express.static(path.join(__dirname, "bin")));
var port = process.env.PORT || 8000;
app.listen(port);
console.log('server listening on port ' + port);