-
Notifications
You must be signed in to change notification settings - Fork 16
/
utils.js
247 lines (234 loc) · 6.5 KB
/
utils.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
module.exports = {
/**
* Generate a cache key unique to this query
* @param {superagent} agent
* @param {object} reg
* @param {object} cProps
*/
keygen: function(agent, req, cProps){
var cleanParams = null;
var cleanOptions = null;
var params = this.getQueryParams(req);
var options = this.getHeaderOptions(req);
if(cProps.pruneQuery || cProps.pruneHeader){
cleanParams = (cProps.pruneQuery) ? this.pruneObj(this.cloneObject(params), cProps.pruneQuery) : params;
cleanOptions = (cProps.pruneHeader) ? this.pruneObj(this.cloneObject(options), cProps.pruneHeader, true) : options;
}
return JSON.stringify({
nameSpace: agent.cache.nameSpace,
method: req.method,
uri: req.url,
params: cleanParams || params || null,
options: cleanOptions || options || null
});
},
/**
* Find and extract query params
* @param {object} reg
*/
getQueryParams: function(req){
if(req && req.qs && !this.isEmpty(req.qs)){
return req.qs;
}
else if(req && req.qsRaw){
return this.arrayToObj(req.qsRaw);
}
else if(req && req.req){
return this.stringToObj(req.req.path);
}
else if(req && req._query){
return this.stringToObj(req._query.join('&'));
}
return null;
},
/**
* Find and extract headers
* @param {object} reg
*/
getHeaderOptions: function(req){
//I have to remove the User-Agent header ever since superagent 1.7.0
if(req && req._header){
return this.pruneObj(req._header, ['User-Agent', 'user-agent']);
}
else if(req && req.req && req.req._headers){
return this.pruneObj(req.req._headers, ['User-Agent', 'user-agent']);
}
else if(req && req.header){
return this.pruneObj(req.header, ['User-Agent', 'user-agent']);
}
return null;
},
/**
* Add an array of key-value pairs to an object (mutation by reference)
* @param {object} obj
* @param {array} arr
*/
addKvArrayToObj: function(obj, arr){
for(var i = 0; i < arr.length; i++){
var kvString = arr[i].split(`=`);
if (Array.isArray(obj[kvString[0]])) {
obj[kvString[0]].push(kvString[1])
} else if (obj[kvString[0]]) {
obj[kvString[0]] = [obj[kvString[0]], kvString[1]];
} else {
obj[kvString[0]] = kvString[1];
}
}
return obj;
},
/**
* Convert an array to an object
* @param {array} arr
*/
arrayToObj: function(arr){
if(arr && arr.length){
var obj = {};
for(var i = 0; i < arr.length; i++){
var str = arr[i];
var kvArray = str.split('&');
obj = this.addKvArrayToObj(obj, kvArray);
}
return obj;
}
return null;
},
/**
* Convert a string to an object
* @param {string} str
*/
stringToObj: function(str){
if(str){
if(~str.indexOf('?')){
var strs = str.split('?');
str = strs[1];
}
var kvArray = str.split('&');
return this.addKvArrayToObj({}, kvArray);
}
return null;
},
/**
* Remove properties from an object
* @param {object} obj
* @param {array} props
* @param {boolean} isOptions
*/
pruneObj: function(obj, props, isOptions){
for(var i = 0; i < props.length; i++){
var prop = props[i];
if(isOptions){
delete obj[prop.toLowerCase()];
}
delete obj[prop];
}
return obj;
},
/**
* Simplify superagent's http response object
* @param {object} r
*/
gutResponse: function(r){
var newResponse = {};
newResponse.body = r.body;
newResponse.text = r.text;
newResponse.headers = r.headers;
newResponse.statusCode = r.statusCode;
newResponse.status = r.status;
newResponse.ok = r.ok;
return newResponse;
},
/**
* Determine whether a value is considered empty
* @param {*} val
*/
isEmpty: function(val){
return (val === false || val === null || (typeof val == 'object' && Object.keys(val).length == 0));
},
/**
* Return a clone of an object
* @param {object} obj
*/
cloneObject: function(obj){
var newObj = {};
for(var attr in obj) {
if (obj.hasOwnProperty(attr)){
newObj[attr] = obj[attr];
}
}
return newObj;
},
handlePendingRequests: function(curProps, superagent, key, err, response){
if(curProps.preventDuplicateCalls){
if(superagent.pendingRequests[key] && (!this.isEmpty(response) || curProps.cacheWhenEmpty)){
var self = this;
var pendingRequests = superagent.pendingRequests[key];
pendingRequests.forEach(function (cb){
self.callbackExecutor(cb, err, response, key);
});
}
delete superagent.pendingRequests[key];
}
},
/**
* Reset superagent-cache's default query properties using the defaults object
* @param {object} d
*/
resetProps: function(d){
return {
doQuery: (typeof d.doQuery === 'boolean') ? d.doQuery : true,
cacheWhenEmpty: (typeof d.cacheWhenEmpty === 'boolean') ? d.cacheWhenEmpty : true,
prune: d.prune,
pruneQuery: d.pruneQuery,
pruneHeader: d.pruneHeader,
responseProp: d.responseProp,
expiration: d.expiration,
forceUpdate: d.forceUpdate,
preventDuplicateCalls: d.preventDuplicateCalls,
backgroundRefresh: d.backgroundRefresh
};
},
/**
* Generate a background refresh query identical to the current query
* @param {superagent} agent
* @param {object} curProps
*/
getBackgroundRefreshFunction: function(agent, curProps){
return function(key, cb){
key = JSON.parse(key);
var method = key.method.toLowerCase();
var request = agent[method](key.uri)
.doQuery(curProps.doQuery)
.pruneQuery(curProps.pruneQuery)
.pruneHeader(curProps.pruneHeader)
.prune(curProps.prune)
.responseProp(curProps.responseProp)
.expiration(curProps.expiration)
.cacheWhenEmpty(curProps.cacheWhenEmpty);
if(key.params){
request.query(key.params)
}
if(key.options){
request.set(key.options);
}
request.end(cb);
}
},
/**
* Handle the varying number of callback output params
* @param {function} cb
* @param {object} err
* @param {object} response
* @param {string} key
*/
callbackExecutor: function(cb, err, response, key){
if(cb.length === 1){
cb(response);
}
else if(cb.length > 1){
cb(err, response, key);
}
else{
throw new Error('UnsupportedCallbackException: Your .end() callback must pass at least one argument.');
}
}
}