-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (50 loc) · 1.85 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const port = 3000;
let customers = [
{id: '1588323375416', firstName: 'John', lastName: 'Johnson', email: '[email protected]', phone: '8233243'},
{id: '1588323375417', firstName: 'Mary', lastName: 'Smith', email: '[email protected]', phone: '6654113'},
{id: '1588323375418', firstName: 'Peter', lastName: 'North', email: '[email protected]', phone: '901176'},
];
// fetch all customers
app.get("/api/customers", (req, res) => {
res.json(customers);
})
// fetch customer by id
app.get("/api/customers/:id", (req, res) => {
const customerId = req.params.id;
const customer = customers.filter(customer => customer.id === customerId);
if (customer.length > 0)
res.json(customer);
else
res.status(404).end();
})
// add new customer
app.post("/api/customers", (req, res) => {
// Extract customer from the request body and generate id
const newCustomer = {'id': Date.now(), ...req.body};
// Add new customer at the end of the customers array
customers = [...customers, newCustomer];
res.json(newCustomer);
});
// delete customer
app.delete("/api/customers/:id", (req, res) => {
const id = req.params.id;
customers = customers.filter(customer => customer.id !== id);
res.status(204).end();
})
// update customer
app.put("/api/customers/:id", (req, res) => {
const id = req.params.id;
const updatedCustomer = {'id': id, ...req.body};
// Get the index of updated customer
const index = customers.findIndex(customer => customer.id === id);
// Replace updated customer in the array
customers.splice(index, 1, updatedCustomer);
res.json(updatedCustomer);
})
app.listen(port, () => {
console.log(`Server is running on port ${port}.`);
});