forked from udacity/reactnd-contacts-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
contacts.js
64 lines (52 loc) · 1.12 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
62
63
64
const clone = require('clone')
const config = require('./config')
const db = {}
const defaultData = {
contacts: [
{
id: 'ryan',
name: 'Ryan Florence',
email: '[email protected]',
avatarURL: config.origin + '/ryan.jpg'
},
{
id: 'michael',
name: 'Michael Jackson',
email: '[email protected]',
avatarURL: config.origin + '/michael.jpg'
},
{
id: 'tyler',
name: 'Tyler McGinnis',
email: '[email protected]',
avatarURL: config.origin + '/tyler.jpg'
}
]
}
const get = (token) => {
let data = db[token]
if (data == null) {
data = db[token] = clone(defaultData)
}
return data
}
const add = (token, contact) => {
if (!contact.id) {
contact.id = Math.random().toString(36).substr(-8)
}
get(token).contacts.push(contact)
return contact
}
const remove = (token, id) => {
const data = get(token)
const contact = data.contacts.find(c => c.id === id)
if (contact) {
data.contacts = data.contacts.filter(c => c !== contact)
}
return { contact }
}
module.exports = {
get,
add,
remove
}