-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
42 lines (34 loc) · 1.34 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
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const customers = require('./customers.json');
const app = express();
const jsonParser = bodyParser.json();
app.use(jsonParser);
app.use(cors());
app.post('/search', (req, res) => {
try {
const {first_name, surname, email, mobile} = req.body;
const checkFieldMatches = (customer, search, propertyName) => {
if (typeof search === 'undefined' || search === '') {
return true;
}
if (typeof customer[propertyName] === 'undefined') {
return false;
}
return customer[propertyName].toLowerCase() === search.toLowerCase();
}
const filterFields = (customer) => {
return checkFieldMatches(customer, first_name, 'first_name') &&
checkFieldMatches(customer, surname, 'surname') &&
checkFieldMatches(customer, email, 'email') &&
checkFieldMatches(customer, mobile, 'mobile');
};
res.send(customers.filter(filterFields));
} catch(error) {
console.error(error);
res.status(500).send('Server error')
}
});
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`Customer Server listening on port ${port}!`));