-
Notifications
You must be signed in to change notification settings - Fork 0
/
contacts.js
61 lines (51 loc) · 1.56 KB
/
contacts.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
const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const contactManager = require('./lib/contact_manager');
const helpers = require('./lib/helpers');
const app = express();
app.set('port', (process.env.PORT || 3000));
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/contacts', (req, res) => {
res.json(contactManager.getAll());
});
app.get('/api/contacts/:id', (req, res) => {
let contact = contactManager.get(req.params['id']);
if (contact) {
res.json(contact);
} else {
res.status(404).end();
}
});
app.post('/api/contacts', (req, res) => {
let contactAttrs = helpers.extractContactAttrs(req.body);
let contact = contactManager.add(contactAttrs);
if (contact) {
res.status(201).json(contact);
} else {
res.status(400).end();
}
});
app.put('/api/contacts/:id', (req, res) => {
let contactAttrs = helpers.extractContactAttrs(req.body);
let contact = contactManager.update(req.params['id'], contactAttrs);
if (contact) {
res.status(201).json(contact);
} else {
res.status(400).end();
}
});
app.delete('/api/contacts/:id', (req, res) => {
if (contactManager.remove(req.params['id'])) {
res.status(204).end();
} else {
res.status(400).end();
}
});
app.listen(app.get('port'), () => {
console.log(`Find the server at: http://localhost:${app.get('port')}/`); // eslint-disable-line no-console
});
module.exports = app; // for testing