-
Notifications
You must be signed in to change notification settings - Fork 0
/
axios-demock.js
85 lines (69 loc) · 2.75 KB
/
axios-demock.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
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
root.axiosDemock = factory();
}
}(this, function () {
'use strict';
function mixin(target) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
for (var prop in source) {
target[prop] = source[prop];
}
}
return target;
}
return {
intercept: function (axios, demock) {
axios.interceptors.request.use(function (config) {
var demockRequest = {
url: config.url,
method: config.method.toUpperCase(),
params: mixin({}, config.params, config.data),
headers: mixin({}, config.headers)
};
demock.filterRequest(demockRequest);
config.url = demockRequest.url;
config.method = demockRequest.method.toLowerCase();
config.__demockRequest = demockRequest;
return config;
});
axios.interceptors.response.use(function (response) {
var demockRequest = response.config.__demockRequest;
var demockResponse = {
statusCode: response.status,
statusText: response.statusText,
data: response.data,
headers: response.headers
};
demock.filterResponse(demockRequest, demockResponse);
return new Promise(function (resolve, reject) {
function handleResponse() {
response.status = demockResponse.statusCode;
response.statusText = demockResponse.statusText;
response.data = demockResponse.data;
response.headers = demockResponse.headers;
if (demockResponse.timeout) {
response.statusCode = 0;
reject(response);
} else if (demockResponse.statusCode >= 400 && demockResponse.statusCode < 600) {
reject(response);
} else {
resolve(response);
}
}
if (demockResponse.delay) {
setTimeout(handleResponse, demockResponse.delay);
} else {
handleResponse();
}
});
});
}
};
}));