/
api.js
82 lines (72 loc) · 1.73 KB
/
api.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
localStorage.token = localStorage.token || (Date.now()*Math.random())
//const API = 'http://addressbook-api.herokuapp.com'
const API = 'http://localhost:3000'
function setToken(req) {
req.setRequestHeader('authorization', localStorage.token)
}
function getJSON(url, cb) {
const req = new XMLHttpRequest()
req.onload = function () {
if (req.status === 404) {
cb(new Error('not found'))
} else {
// fake spotty server
const time = Math.random() * 1000
setTimeout(() => {
cb(null, JSON.parse(req.response))
}, time)
}
}
req.open('GET', url)
setToken(req)
req.send()
}
function postJSON(url, obj, cb) {
var req = new XMLHttpRequest()
req.onload = function () {
cb(null, JSON.parse(req.response))
}
req.open('POST', url)
req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
setToken(req)
req.send(JSON.stringify(obj))
}
function deleteJSON(url, cb) {
var req = new XMLHttpRequest()
req.onload = function () {
if (req.status === 500)
cb(new Error(req.responseText))
else
cb(null, req.responseText)
}
req.open('DELETE', url)
setToken(req)
req.send()
}
export function fetchContact(id, cb) {
getJSON(`${API}/contacts/${id}`, (err, res) => {
if (err)
cb(err)
else
cb(null, res.contact)
})
}
export function fetchContacts(cb) {
getJSON(`${API}/contacts`, (err, res) => {
if (err)
cb(err)
else
cb(null, res.contacts)
})
}
export function deleteContact(contactId, cb) {
deleteJSON(`${API}/contacts/${contactId}`, cb)
}
export function postContact(contact, cb) {
postJSON(`${API}/contacts`, { contact }, (err, res) => {
if (err)
cb(err)
else
cb(null, res.contact)
})
}