-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapi.js
More file actions
71 lines (53 loc) · 1.51 KB
/
api.js
File metadata and controls
71 lines (53 loc) · 1.51 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
const express = require('express')
const bodyParser = require('body-parser')
const actions = require('./actions')
const api = express()
api.use(bodyParser.urlencoded({ extended: false }))
api.use(bodyParser.json())
api.get('/contacts', (req, res) => {
actions.getAllContactsAndTheirGroups()
.then((contacts) => {
res.json(contacts)
})
.catch(res.json)
})
api.get('/contacts/:id', (req, res) => {
const contactID = req.params.id
actions.getContactAndTheirGroups(contactID)
.then((contact) => {
res.json(contact)
})
.catch(res.json)
})
api.post('/contacts', (req, res) => {
const { contact, groups } = req.body
actions.createContactWithGroups(contact, groups)
.then((contactID) => {
res.status(201)
res.json({ id: contactID, message: 'Contact created' })
})
.catch(res.json)
})
api.delete('/contacts/:id', (req, res) => {
const contactID = req.params.id
actions.deleteContactAndTheirMemberships(contactID)
.then((contact) => {
res.json({ id: contact.id, message: 'Contact deleted' })
})
.catch(res.json)
})
api.delete('/groups/:id', (req, res) => {
const groupID = req.params.id
actions.deleteGroupAndTheirMemberships(groupID)
.then((group) => {
res.json({ id: group.id, message: 'Group deleted' })
})
.catch(res.json)
})
if (!module.parent) {
const port = process.env.PORT || 3000
api.listen(port, function () {
console.log(`Address book API listening on port ${port}!`)
})
}
module.exports = { api }