index.js
1.71 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
/**
* Service for sending network requests.
*/
const COMMON_HEADERS = {'Accept': 'application/json, text/plain, */*'};
const JSON_CONTENT_TYPE = {'Content-Type': 'application/json;charset=utf-8'};
import cors from './interceptor/cors';
import body from './interceptor/body';
import jsonp from './interceptor/jsonp';
import before from './interceptor/before';
import method from './interceptor/method';
import header from './interceptor/header';
import Client from './client/index';
import Request from './request';
import Promise from '../promise';
import { assign, defaults, error } from '../util';
export default function Http(options) {
var self = this || {}, client = Client(self.$vm);
defaults(options || {}, self.$options, Http.options);
Http.interceptors.forEach((handler) => {
client.use(handler);
});
return client(new Request(options)).then((response) => {
return response.ok ? response : Promise.reject(response);
}, (response) => {
if (response instanceof Error) {
error(response);
}
return Promise.reject(response);
});
}
Http.options = {};
Http.headers = {
put: JSON_CONTENT_TYPE,
post: JSON_CONTENT_TYPE,
patch: JSON_CONTENT_TYPE,
delete: JSON_CONTENT_TYPE,
common: COMMON_HEADERS,
custom: {}
};
Http.interceptors = [before, method, body, jsonp, header, cors];
['get', 'delete', 'head', 'jsonp'].forEach((method) => {
Http[method] = function (url, options) {
return this(assign(options || {}, {url, method}));
};
});
['post', 'put', 'patch'].forEach((method) => {
Http[method] = function (url, body, options) {
return this(assign(options || {}, {url, method, body}));
};
});