forked from typicode/fetchival
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
112 lines (93 loc) · 2.89 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
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
103
104
105
106
107
108
109
110
111
112
;(function (window) {
function defaults (target, obj) {
for (var prop in obj) target[prop] = target[prop] || obj[prop]
}
function getQuery (queryParams) {
return '?' + serialize(queryParams);
}
function serialize(obj, prefix) {
var str = [], p;
for(p in obj) {
if (obj.hasOwnProperty(p)) {
if (Array.isArray(obj[p])) {
var values = obj[p];
values.forEach(v => {
str.push(encodeURIComponent(p) + "[]=" + encodeURIComponent(v));
});
} else {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
}
return str.join("&");
}
function _fetch (method, url, opts, data, queryParams) {
opts.method = method
opts.headers = opts.headers || {}
opts.responseAs = (opts.responseAs && ['json', 'text', 'response'].indexOf(opts.responseAs) >= 0) ? opts.responseAs : 'json'
defaults(opts.headers, {
'Accept': 'application/json',
'Content-Type': 'application/json'
})
if (queryParams) {
url += getQuery(queryParams)
}
if (data) {
opts.body = JSON.stringify(data);
} else {
delete opts.body;
}
return fetchival.fetch(url, opts)
.then(function (response) {
if (response.status >= 200 && response.status < 300) {
if(opts.responseAs=="response")
return response
if (response.status == 204)
return null;
return response[opts.responseAs]();
}
var err = new Error(response.statusText)
err.response = response
throw err
})
}
function fetchival (url, opts) {
opts = opts || {}
var _ = function (u, o) {
// Extend parameters with previous ones
u = url + '/' + u
o = o || {}
defaults(o, opts)
return fetchival(u, o)
}
_.get = function (queryParams) {
return _fetch('GET', url, opts, null, queryParams)
}
_.post = function (data) {
return _fetch('POST', url, opts, data)
}
_.put = function (data) {
return _fetch('PUT', url, opts, data)
}
_.patch = function (data) {
return _fetch('PATCH', url, opts, data)
}
_.delete = function () {
return _fetch('DELETE', url, opts)
}
return _
}
// Expose fetch so that other polyfills can be used
// Bind fetch to window to avoid TypeError: Illegal invocation
fetchival.fetch = typeof fetch !== 'undefined' ? fetch.bind(window) : null
// Support CommonJS, AMD & browser
if (typeof exports === 'object')
module.exports = fetchival
else if (typeof define === 'function' && define.amd)
define(function() { return fetchival })
else
window.fetchival = fetchival
})(typeof window != 'undefined' ? window : undefined);