forked from amplitude/redux-query
-
Notifications
You must be signed in to change notification settings - Fork 0
/
superagent.js
54 lines (44 loc) · 1.47 KB
/
superagent.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
import superagent from 'superagent';
import * as httpMethods from '../constants/http-methods';
export const createRequest = (url, method) => {
switch (method) {
case httpMethods.GET:
return superagent.get(url);
case httpMethods.POST:
return superagent.post(url);
case httpMethods.PUT:
return superagent.put(url);
case httpMethods.PATCH:
return superagent.patch(url);
case httpMethods.DELETE:
return superagent.del(url);
default:
throw new Error(`Unsupported HTTP method: ${method}`);
}
};
const superagentNetworkAdapter = (url, method, { body, headers, credentials } = {}) => {
const request = createRequest(url, method);
if (body) {
request.send(body);
}
if (headers) {
request.set(headers);
}
if (credentials === 'include') {
request.withCredentials();
}
const execute = (cb) => request.end((err, response) => {
const resStatus = (response && response.status) || 0;
const resBody = (response && response.body) || undefined;
const resText = (response && response.text) || undefined;
const resHeaders = (response && response.header) || undefined;
cb(err, resStatus, resBody, resText, resHeaders);
});
const abort = () => request.abort();
return {
abort,
execute,
instance: request,
};
};
export default superagentNetworkAdapter;