Skip to content

Commit 3fcb24a

Browse files
committed
refactor(ajax): 精简 ajax 为请求封装,将业务相关逻辑移到 _request 中,移除了 node agent keepAlive 选项。
1 parent 9371d38 commit 3fcb24a

File tree

5 files changed

+58
-111
lines changed

5 files changed

+58
-111
lines changed

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
language: node_js
22

33
node_js:
4-
- "4.2"
4+
- "4"
55
- "0.12"
66

77
sudo: false

src/av.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ AV._ = require('underscore');
1919
AV.version = require('./version');
2020
AV.Promise = require('./promise');
2121
AV.localStorage = require('./localstorage');
22-
AV.Cache = require('./Cache');
22+
AV.Cache = require('./cache');
2323

2424
// 挂载所有内部配置项
2525
AV._config = AV._config || {};

src/browserify-wrapper/ajax-browser.js

Lines changed: 6 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -6,31 +6,12 @@
66
'use strict';
77

88
const AVPromise = require('../promise');
9-
const md5 = require('md5');
9+
const debug = require('debug')('ajax');
1010

11-
// 计算 X-LC-Sign 的签名方法
12-
const sign = (key, isMasterKey) => {
13-
const now = new Date().getTime();
14-
const signature = md5(now + key);
15-
if (isMasterKey) {
16-
return signature + ',' + now + ',master';
17-
} else {
18-
return signature + ',' + now;
19-
}
20-
};
21-
22-
const ajax = (method, url, data, success, error) => {
23-
const AV = global.AV;
11+
const ajax = (method, url, data, headers = {}) => {
12+
debug(method, url, data, headers);
2413

2514
const promise = new AVPromise();
26-
const options = {
27-
success: success,
28-
error: error
29-
};
30-
31-
const appId = AV.applicationId;
32-
const appKey = AV.applicationKey;
33-
const masterKey = AV.masterKey;
3415

3516
let handled = false;
3617
const xhr = new global.XMLHttpRequest();
@@ -41,6 +22,8 @@ const ajax = (method, url, data, success, error) => {
4122
}
4223
handled = true;
4324

25+
debug(xhr.status, xhr.responseText);
26+
4427
if (xhr.status >= 200 && xhr.status < 300) {
4528
let response;
4629
try {
@@ -59,59 +42,14 @@ const ajax = (method, url, data, success, error) => {
5942
}
6043
};
6144

62-
let headers = {
63-
'X-LC-Id': appId,
64-
'X-LC-UA': 'LC-Web-' + AV.version,
65-
'Content-Type': 'application/json;charset=UTF-8'
66-
};
67-
68-
// 清理原来多余的数据(如果不清理,会污染数据表)
69-
if (data) {
70-
delete data._ApplicationId;
71-
delete data._ApplicationKey;
72-
delete data._ApplicationProduction;
73-
delete data._MasterKey;
74-
delete data._ClientVersion;
75-
delete data._InstallationId;
76-
77-
if (data._SessionToken) {
78-
headers['X-LC-Session'] = data._SessionToken;
79-
delete data._SessionToken;
80-
}
81-
}
82-
83-
if (method.toLowerCase() === 'get') {
84-
let i = 0;
85-
for (let k in data) {
86-
if (i === 0) {
87-
url = url + '?';
88-
} else {
89-
url = url + '&';
90-
}
91-
92-
if (typeof data[k] === 'object') {
93-
data[k] = JSON.stringify(data[k]);
94-
}
95-
96-
url = url + k + '=' + encodeURIComponent(data[k]);
97-
i ++;
98-
}
99-
}
100-
101-
if (masterKey && AV._useMasterKey) {
102-
headers['X-LC-Sign'] = sign(masterKey, true);
103-
} else {
104-
headers['X-LC-Sign'] = sign(appKey);
105-
}
106-
10745
xhr.open(method, url, true);
10846

10947
for (let name in headers) {
11048
xhr.setRequestHeader(name, headers[name]);
11149
}
11250

11351
xhr.send(JSON.stringify(data));
114-
return promise._thenRunCallbacks(options);
52+
return promise;
11553
};
11654

11755
module.exports = ajax;

src/browserify-wrapper/ajax.js

Lines changed: 11 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,44 +8,33 @@
88
const http = require('http');
99
const https = require('https');
1010
const url = require('url');
11+
const debug = require('debug')('ajax');
1112

1213
const Promise = require('../promise');
1314
const VERSION = require('../version');
1415

15-
// `keepAlive` option only work on Node.js 0.12+
16-
var httpAgent = new http.Agent({keepAlive: true});
17-
var httpsAgent = new https.Agent({keepAlive: true});
18-
19-
module.exports = function _ajax(method, resourceUrl, data, success, error) {
20-
if (method.toLowerCase() !== 'post') {
21-
data = data || {};
22-
data._method = method;
23-
method = 'post';
24-
}
25-
data = JSON.stringify(data);
16+
module.exports = function _ajax(method, resourceUrl, data, headers = {}) {
17+
debug(method, resourceUrl, data, headers);
2618

2719
var parsedUrl = url.parse(resourceUrl);
20+
2821
var promise = new Promise();
2922

3023
var transportModule = http;
31-
var transportAgent = httpAgent;
3224

3325
if (parsedUrl.protocol === 'https:') {
3426
transportModule = https;
35-
transportAgent = httpsAgent;
3627
}
3728

29+
delete headers['X-LC-UA'];
30+
headers['User-Agent'] = _ajax.userAgent || 'AV/' + VERSION + '; Node.js/' + process.version;
3831
var req = transportModule.request({
3932
method: method,
4033
protocol: parsedUrl.protocol,
4134
hostname: parsedUrl.hostname,
4235
port: parsedUrl.port,
4336
path: parsedUrl.path,
44-
agent: transportAgent,
45-
headers: {
46-
'Content-Type': 'text/plain',
47-
'User-Agent': _ajax.userAgent || 'AV/' + VERSION + '; Node.js/' + process.version
48-
}
37+
headers,
4938
});
5039

5140
req.on('response', function(res) {
@@ -56,6 +45,7 @@ module.exports = function _ajax(method, resourceUrl, data, success, error) {
5645
});
5746

5847
res.on('end', function() {
48+
debug(res.statusCode, responseText);
5949
if (res.statusCode >= 200 && res.statusCode < 300) {
6050
try {
6151
promise.resolve(JSON.parse(responseText), res.statusCode, res);
@@ -74,9 +64,7 @@ module.exports = function _ajax(method, resourceUrl, data, success, error) {
7464
promise.reject(err);
7565
});
7666

77-
req.end(data);
78-
return promise._thenRunCallbacks({
79-
success: success,
80-
error: error
81-
});
67+
req.end(JSON.stringify(data));
68+
debug(req);
69+
return promise;
8270
};

src/utils.js

Lines changed: 39 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,19 @@
88
const _ = require('underscore');
99
const ajax = require('./browserify-wrapper/ajax');
1010
const Cache = require('./cache');
11+
const md5 = require('md5');
12+
const debug = require('debug')('utils');
13+
14+
// 计算 X-LC-Sign 的签名方法
15+
const sign = (key, isMasterKey) => {
16+
const now = new Date().getTime();
17+
const signature = md5(now + key);
18+
if (isMasterKey) {
19+
return signature + ',' + now + ',master';
20+
} else {
21+
return signature + ',' + now;
22+
}
23+
};
1124

1225
const init = (AV) => {
1326

@@ -413,36 +426,44 @@ const init = (AV) => {
413426
}
414427
}
415428

416-
dataObject = _.clone(dataObject || {});
417-
dataObject._ApplicationId = AV.applicationId;
418-
dataObject._ApplicationKey = AV.applicationKey;
419-
if (!AV._isNullOrUndefined(AV.applicationProduction)) {
420-
dataObject._ApplicationProduction = AV.applicationProduction;
429+
if (method.toLowerCase() === 'get') {
430+
if (apiURL.indexOf('?') === -1) {
431+
apiURL += '?';
432+
}
433+
for (let k in dataObject) {
434+
if (typeof dataObject[k] === 'object') {
435+
dataObject[k] = JSON.stringify(dataObject[k]);
436+
}
437+
apiURL += '&' + k + '=' + encodeURIComponent(dataObject[k]);
438+
}
439+
}
440+
441+
var headers = {
442+
'X-LC-Id': AV.applicationId,
443+
'X-LC-UA': 'LC-Web-' + AV.version,
444+
'Content-Type': 'application/json;charset=UTF-8'
445+
};
446+
if (AV.masterKey && AV._useMasterKey) {
447+
headers['X-LC-Sign'] = sign(AV.masterKey, true);
448+
} else {
449+
headers['X-LC-Sign'] = sign(AV.applicationKey);
421450
}
422-
if (AV._useMasterKey) {
423-
dataObject._MasterKey = AV.masterKey;
451+
if (!AV._isNullOrUndefined(AV.applicationProduction)) {
452+
headers['X-LC-Prod'] = AV.applicationProduction;
424453
}
425-
dataObject._ClientVersion = AV.version;
426454
return AV.Promise.as().then(function() {
427455
// Pass the session token
428456
if (sessionToken) {
429-
dataObject._SessionToken = sessionToken;
457+
headers['X-LC-Session'] = sessionToken;
430458
} else if (!AV._config.disableCurrentUser) {
431459
return AV.User.currentAsync().then(function(currentUser) {
432460
if (currentUser && currentUser._sessionToken) {
433-
dataObject._SessionToken = currentUser._sessionToken;
461+
headers['X-LC-Session'] = currentUser._sessionToken;
434462
}
435463
});
436464
}
437465
}).then(function() {
438-
// Pass the installation id
439-
if (!AV._config.disableCurrentUser) {
440-
return AV._getInstallationId().then(function(installationId) {
441-
dataObject._InstallationId = installationId;
442-
});
443-
}
444-
}).then(function() {
445-
return AV._ajax(method, apiURL, dataObject).then(null, function(response) {
466+
return AV._ajax(method, apiURL, dataObject, headers).then(null, function(response) {
446467
// Transform the error into an instance of AV.Error by trying to parse
447468
// the error string as JSON.
448469
var error;

0 commit comments

Comments
 (0)