-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
102 lines (86 loc) · 2.29 KB
/
client.js
File metadata and controls
102 lines (86 loc) · 2.29 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
const request = require('request')
const querystring = require('querystring')
module.exports = function ({ endpoint, username, password }) {
endpoint = endpoint || 'http://localhost:1337'
return {
getProduct,
listProducts,
createProduct,
editProduct,
deleteProduct,
createOrder,
listOrders
}
function getProduct (id, cb) {
const url = `${endpoint}/products/${id}`
getJSON(url, cb)
}
function listProducts (opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
const { offset = 0, limit = 25, tag } = opts
const url = `${endpoint}/products?${querystring.stringify({
offset,
limit,
tag
})}`
getJSON(url, cb)
}
function createProduct (product, cb) {
const url = `${endpoint}/products`
postJSON(url, product, cb)
}
function editProduct (id, changes, cb) {
const url = `${endpoint}/products/${id}`
putJSON(url, changes, cb)
}
function deleteProduct (id, cb) {
const url = `${endpoint}/products/${id}`
delJSON(url, cb)
}
function createOrder ({ products, username }, cb) {
const url = `${endpoint}/orders`
postJSON(url, { products, username }, cb)
}
function listOrders (opts, cb) {
if (typeof opts === 'function') {
cb = opts
opts = {}
}
const { offset = 0, limit = 25, status, productId } = opts
const url = `${endpoint}/orders?${querystring.stringify({
offset,
limit,
status,
productId
})}`
getJSON(url, cb)
}
function getJSON (url, cb) {
request.get(url, { json: true }, handleResponse(cb))
}
function postJSON (url, data, cb) {
request.post(url, { json: true, body: data }, handleResponse(cb))
}
function putJSON (url, data, cb) {
request.put(url, { json: true, body: data }, handleResponse(cb))
}
function delJSON (url, cb) {
request.delete(url, { json: true }, handleResponse(cb))
}
}
function handleResponse (cb) {
return function (err, res, body) {
if (err) return cb(err)
if (res.statusCode !== 200) {
const defaultMsg = `Request Failed.\n Status Code: ${res.statusCode}`
const serverMsg = (body || {}).error
err = new Error(serverMsg || defaultMsg)
err.statusCode = res.statusCode
return cb(err)
}
cb(null, body)
}
}