-
Notifications
You must be signed in to change notification settings - Fork 2
/
fetch-rails.ts
190 lines (182 loc) · 5.19 KB
/
fetch-rails.ts
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
interface IDefaultOptions {
headers: any;
credentials: any;
}
interface IJSONOptions {
headers: any;
credentials: any;
method: string;
body: string;
}
const Fetch = {
getCSRF: function() {
const element = document.querySelector('meta[name="csrf-token"]');
if (element) {
return element.getAttribute('content');
} else {
return '';
}
},
defaultHeadersJSON: function(options) {
return (
options.headers || {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': this.getCSRF(),
Accept: 'application/json',
'Content-Type': 'application/json',
}
);
},
defaultHeaders: function(options = { headers: null }) {
return (
options.headers || {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': this.getCSRF(),
}
);
},
defaultCredentials: (options = { credentials: null }) =>
options.credentials || 'same-origin',
checkStatus: (response): Promise<object> => {
return new Promise((resolve, reject) => {
if (response.status >= 200 && response.status < 300) {
resolve(response);
} else {
response.json().then(responseJson => {
reject(responseJson);
});
}
});
},
json: function(url: string, params: object, options: IDefaultOptions) {
url = mergeParameters(url, params);
const optionsDefault = {
headers: this.defaultHeadersJSON(options),
credentials: this.defaultCredentials(options),
};
return fetch(url, optionsDefault)
.then(this.checkStatus)
.then(parseJSON);
},
requestDataJSON: function(
method: string,
url: string,
body: object,
options: IJSONOptions,
) {
const optionsDefault = {
headers: this.defaultHeadersJSON(options),
credentials: this.defaultCredentials(options),
method: method,
body: JSON.stringify(body),
};
return fetch(url, optionsDefault)
.then(this.checkStatus)
.then(parseJSON);
},
postJSON: function(url: string, body: object, options: IJSONOptions) {
return this.requestDataJSON('post', url, body, options);
},
putJSON: function(url: string, body: object, options: IJSONOptions) {
return this.requestDataJSON('put', url, body, options);
},
deleteJSON: function(url: string, body: object, options: IJSONOptions) {
return this.requestDataJSON('delete', url, body, options);
},
html: function(url: string, params: object, options: IDefaultOptions) {
url = mergeParameters(url, params);
const optionsDefault = {
headers: this.defaultHeaders(options),
credentials: this.defaultCredentials(options),
};
return fetch(url, optionsDefault).then(this.checkStatus);
},
text: function(url: string, options: IDefaultOptions) {
url = mergeParameters(url, options);
const optionsDefault = {
headers: this.defaultHeaders(options),
credentials: this.defaultCredentials(options),
};
return fetch(url, optionsDefault)
.then(this.checkStatus)
.then(parseText);
},
postForm: function(
url: string,
form,
options: { headers: any; credentials: any; body: FormData; method: any },
) {
const optionsDefault = {
headers: this.defaultHeadersHTML(options),
credentials: this.defaultCredentials(options),
body: new FormData(document.querySelector(form)),
method: options.method || 'post',
};
return fetch(url, optionsDefault).then(this.checkStatus);
},
};
// helpers
const mergeParameters = (url = '', params = {}) => {
if (!params || Object.keys(params).length === 0) {
return url;
}
const query = encodeParams(params);
return `${url}?${query}`;
};
const parseJSON = response => response.json();
const parseText = response => response.text();
/* tslint:disable */
export const encodeParams = function(a): any {
var s = [],
rbracket = /\[\]$/,
isArray = function(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
},
add = function(k, v) {
v =
typeof v === 'function'
? v()
: v === null
? ''
: v === undefined
? ''
: v;
s[s.length] = encodeURIComponent(k) + '=' + encodeURIComponent(v);
},
buildParams = function(prefix, obj) {
var i, len, key;
if (prefix) {
if (isArray(obj)) {
for (i = 0, len = obj.length; i < len; i++) {
if (rbracket.test(prefix)) {
add(prefix, obj[i]);
} else {
buildParams(
prefix + '[' + (typeof obj[i] === 'object' ? i : '') + ']',
obj[i],
);
}
}
} else if (obj && String(obj) === '[object Object]') {
for (key in obj) {
buildParams(prefix + '[' + key + ']', obj[key]);
}
} else {
add(prefix, obj);
}
} else if (isArray(obj)) {
for (i = 0, len = obj.length; i < len; i++) {
add(obj[i].name, obj[i].value);
}
} else {
for (key in obj) {
buildParams(key, obj[key]);
}
}
return s;
};
return buildParams('', a)
.join('&')
.replace(/%20/g, '+');
};
export default Fetch;