-
Notifications
You must be signed in to change notification settings - Fork 0
/
demock-jquery.js
74 lines (65 loc) · 2.78 KB
/
demock-jquery.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
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([ 'demock' ], factory);
} else if (typeof exports === 'object') {
factory(require('demock'));
} else {
factory(root.demock);
}
}(this, function (demock) {
demock.init = function ($) {
$.ajax = (function (ajax) {
return function (settings) {
var request = {
method: settings.type ? settings.type.toUpperCase() : 'GET',
url: settings.url,
params: settings.data
};
demock.filterRequest(request);
settings.type = request.method;
settings.url = request.url;
settings.data = request.params;
settings.dataType = 'json';
return ajax.call(this, settings).then(function (data, textStatus, jqXHR) {
var response = {
statusCode: jqXHR.status,
statusText: jqXHR.statusText,
data: data
},
dfd = $.Deferred();
while (demock.filterResponse(request, response)) {}
function resolve() {
jqXHR.status = response.statusCode;
jqXHR.statusText = response.statusText;
jqXHR.responseText = JSON.stringify(response.data);
// @todo handle textStatus: "error", "abort", "parsererror"
if (response.timeout) {
jqXHR.status = 0;
jqXHR.statusText = ''; // @todo check actual jQuery behaviour
dfd.reject(jqXHR, 'timeout');
} else if (response.statusCode >= 400 && response.statusCode < 600) {
dfd.reject(jqXHR, 'error', response.statusText);
} else {
dfd.resolve(response.data, textStatus, jqXHR);
}
}
if (response.delay) {
var timeout = window.setTimeout(resolve, response.delay);
return dfd.promise({
abort: function () {
if (timeout) {
window.clearTimeout(timeout);
}
}
});
} else {
resolve();
return dfd.promise({
abort: $.noop
});
}
});
};
}($.ajax));
};
}));