/
baseapi.js
112 lines (104 loc) · 3.29 KB
/
baseapi.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
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
/**
* base api
*/
var $ = require('zepto');
var config = require('runtime').config;
var BaseAPI = function () {
if (window.sessionStorage) {
this.dataStorage = sessionStorage;
} else {
this.dataStorage = {};
}
this.requestQueue = {};
}
BaseAPI.prototype = {
request: function (conf) {
var url = conf.url,
method = conf.method,
_this = this,
cacheKey = _this.getCacheKey(url, conf.data),
cache,
time = conf.url.indexOf('?') > -1 ? '&time='+ new Date().getTime() : '?time='+ new Date().getTime();
if (typeof method == 'undefined' || !$.inArray(method, ['get', 'post'])) {
method = 'get';
}
if (method == 'get') {
cache = this.getCache(cacheKey);
if (cache) {
return conf.callback(cache);
}
}
if (!this.requestQueue[cacheKey]) {
this.requestQueue[cacheKey] = [];
}
var queue = this.requestQueue[cacheKey];
queue.push(conf.callback);
if (queue.length == 1) {
$.ajax({
type: method,
url: url + time,
data: conf.data,
xhrFields: conf.xhrFields,
dataType: conf.dataType || 'json',
jsonp: conf.jsonp || 'callback',
beforeSend: conf.beforeSend || function () {},
success: function (res) {
//@todo 错误码处理
if (method = 'get') {
_this.setCache(cacheKey, res, conf.expires);
}
var callbacks = _this.requestQueue[cacheKey];
_this.requestQueue[cacheKey] = null;
$.each(callbacks, function (_, fn) {
fn(res);
});
},
error: function(){
_this.requestQueue[cacheKey] = null;
},
complete: conf.complete || function () {}
});
}
},
getCacheKey: function (url, params) {
if (typeof params == 'undefined') {
return url;
}
if (typeof params == 'object') {
var tmp = params;
params = '';
$.each(tmp, function (k, v) {
params += '&' + k + '=' + v;
});
tmp = null;
}
if (typeof params == 'string') {
url += url.indexOf('?') > -1 ? '&' + params : '?' + params;
}
return decodeURIComponent(url);
},
getCache: function (key) {
try {
var cacheData = JSON.parse(this.dataStorage[key]);
if (cacheData.expires < new Date().getTime()) {
this.dataStorage[key] = null;
return null;
}
return cacheData.data;
} catch (_) {
return null;
}
},
setCache: function (key, value, expires) {
var expires = expires || config.dataCacheExpires;
if (expires <= 0) {
return;
}
var cacheData = {
data: value,
expires: new Date().getTime() + expires
}
this.dataStorage[key] = JSON.stringify(cacheData);
}
}
module.exports = BaseAPI;