-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (56 loc) · 1.81 KB
/
Copy pathserver.js
File metadata and controls
72 lines (56 loc) · 1.81 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
const Express = require('express'),
app = Express(),
auth = require('./auth'),
port = process.env.PORT || 3000,
products = require("./data/products.json");
if (process.env.NODE_ENV !== 'development') app.use(auth);
app.get('/', (req, res) => {
res.send("Hello World!");
});
app.get('/service', (req, res) => {
res.status(200).json(require('./service'));
});
app.get('/products/search', (req, res) => {
const offset = req.query.offset || 0,
limit = req.query.limit || 10;
const results = products.filter((p) => {
let match = true;
let { price } = req.query;
// Apply price filter
if (price) {
if (price.currency) match &= p.pricing.price.currency === price.currency;
if (price.min) match &= p.pricing.price.value >= price.min;
if (price.max) match &= p.pricing.price.value <= price.max;
}
return match;
}).sort((a, b) => {
// Sort Results
const { sort } = req.query;
switch (sort) {
case 'id':
case 'name':
return a[sort] >= b[sort];
case 'price':
return a.pricing.price.value >= b.pricing.price.value;
default:
a
return a.name >= b.name;
}
}).slice(offset, limit);
res.status(200).json(results);
});
app.get('/products/:id', (req, res) => {
const { id } = req.params;
const product = products.find((p) => p.id === id);
if (product) {
res.json(product).status(200);
} else {
res.status(404).json({ error: 'Product not found'});
}
});
app.get('/products', (req, res) => {
res.status(200).json(products);
});
app.listen(port, () => {
console.log(`App listening on http://localhost:${port}`);
});