-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (44 loc) · 1.36 KB
/
index.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
const app = require('express')();
const bodyParser = require('body-parser')
const { products, bins } = require('./db.json');
const PAGE_LENGTH = 10;
const isEmail = email => !!email.match(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/);
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
app.use(bodyParser.json());
app.get('/products', (req, res) => {
let found = products.find(p => p.name === req.query.name);
if (found) {
found = Object.assign({}, found, {
bin: bins.find(b => b.id === found.bin),
});
} else {
found = { name: req.query.name, bin: null };
}
const rest = products
.filter(p => (
p.name.includes(req.query.name || '') && p.name !== req.query.name
))
.slice(0, PAGE_LENGTH - 1)
.map(p => Object.assign({}, p, {
bin: bins.find(b => b.id === p.bin),
}));
res.json({
data: [found, ...rest],
});
});
app.post('/products', (req, res) => {
if (
(req.body.email && isEmail(req.body.email)) &&
(typeof req.body.name === 'string' && req.body.name.trim() !== '')
) {
res.sendStatus(200);
} else {
res.sendStatus(422);
}
});
app.listen(process.env.PORT || 3000);