-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
62 lines (53 loc) · 2.04 KB
/
index.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
(function(factory) {
// Establish the root object (`self` instead of `window` in case retch is used in a WebWorker).
const root = typeof self == 'object' && self.self === self && self ||
typeof global == 'object' && global.global === global && global;
// Node/CommonJS module
if (typeof exports !== 'undefined') {
factory(root, exports);
}
// or `retch` global in the browser
else {
root.retch = factory(root, {});
}
})(function(root, retch) {
return {
get: (url, options) => {
options = options || {};
options.method = 'GET';
return makeRequest(url, options);
},
save: (url, options) => {
options = options || {};
options.id = options.body[options.altId || 'id'];
options.method = options.id ? 'PUT' : 'POST';
return makeRequest(url, options);
},
delete: (url, options) => {
options = options || {};
options.method = 'DELETE';
if (!options.id) return Promise.reject('options.id is missing.');
return makeRequest(url, options);
}
};
function makeRequest(url, options) {
// Some url work
url = new URL(url);
if (options.id) url.pathname += (url.pathname.endsWith('/') ? '' : '/') + options.id;
if (options.query) Object.keys(options.query).forEach(key => url.searchParams.append(key, options.query[key]));
// Stringify body
if (options.body) options.body = JSON.stringify(options.body);
// Set init defaults, override if provided
options.credentials = options.credentials || 'include';
options.headers = {'Content-type': 'application/json; charset=UTF-8'};
// All ready, send the request
return fetch(url.toString(), options).then(res => {
if (res.ok) {
return res.json();
}
else {
throw new Error('Network response was not ok, i.e. non-200.');
}
})
}
});