Skip to content

Commit 5388a91

Browse files
committed
Put forward setRegionServer() to request.js
1 parent eac51df commit 5388a91

File tree

3 files changed

+92
-94
lines changed

3 files changed

+92
-94
lines changed

src/cache.js

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1-
'use strict';
1+
/**
2+
* 每位工程师都有保持代码优雅的义务
3+
* Each engineer has a duty to keep the code elegant
4+
**/
5+
26
const storage = require('./localstorage');
37
const AV = require('./av');
48

59
const remove = exports.remove = storage.removeItemAsync.bind(storage);
610

7-
exports.get = (key) => {
8-
return storage.getItemAsync(`${AV.applicationId}/${key}`)
11+
exports.get = (key) =>
12+
storage.getItemAsync(`${AV.applicationId}/${key}`)
913
.then(cache => {
1014
try {
1115
cache = JSON.parse(cache);
@@ -21,12 +25,9 @@ exports.get = (key) => {
2125
}
2226
return null;
2327
});
24-
};
2528

2629
exports.set = (key, value, ttl) => {
27-
const cache = {
28-
value
29-
};
30+
const cache = { value };
3031
if (typeof ttl === 'number') {
3132
cache.expiredAt = Date.now() + ttl;
3233
}

src/request.js

Lines changed: 77 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const request = require('superagent');
77
const debug = require('debug')('request');
88
const md5 = require('md5');
99
const Promise = require('./promise');
10+
const Cache = require('./cache');
1011

1112
// 计算 X-LC-Sign 的签名方法
1213
const sign = (key, isMasterKey) => {
@@ -87,7 +88,6 @@ const ajax = (method, resourceUrl, data, headers = {}, onprogress) => {
8788
};
8889

8990
const setHeaders = (AV, sessionToken) => {
90-
9191
const headers = {
9292
'X-LC-Id': AV.applicationId,
9393
'Content-Type': 'application/json;charset=UTF-8',
@@ -137,7 +137,7 @@ const createApiUrl = (AV, route, className, objectId, method, dataObject) => {
137137
let apiURL = AV._config.APIServerURL;
138138

139139
// Test Data
140-
// apiURL = 'https://e1-api.leancloud.cn';
140+
apiURL = 'https://e1-api.leancloud.cn';
141141

142142
if (apiURL.charAt(apiURL.length - 1) !== '/') {
143143
apiURL += '/';
@@ -176,14 +176,78 @@ const createApiUrl = (AV, route, className, objectId, method, dataObject) => {
176176
return apiURL;
177177
};
178178

179-
/**
180-
When API request need to redirect to the right location,
181-
can't use browser redirect by http status 307, as the reason of CORS,
182-
so API server response http status 410 and the param "location" for this case.
183-
*/
184-
// const retryRequest = () => {
179+
const cacheServerURL = (serverURL, ttl) => {
180+
if (typeof ttl !== 'number') {
181+
ttl = 3600;
182+
}
183+
Cache.set('APIServerURL', serverURL, ttl * 1000);
184+
};
185+
186+
// handle AV._request Error
187+
const handleError = (AV, res) => {
188+
const promise = new Promise();
189+
/**
190+
When API request need to redirect to the right location,
191+
can't use browser redirect by http status 307, as the reason of CORS,
192+
so API server response http status 410 and the param "location" for this case.
193+
*/
194+
if (res.statusCode === 410) {
195+
196+
} else {
197+
let errorJSON = { code: -1, error: res.responseText };
198+
if (res.response && res.response.code) {
199+
errorJSON = res.response;
200+
} else if (res.responseText) {
201+
try {
202+
errorJSON = JSON.parse(res.responseText);
203+
} catch (e) {
204+
// If we fail to parse the error text, that's okay.
205+
}
206+
}
207+
208+
// Transform the error into an instance of AV.Error by trying to parse
209+
// the error string as JSON.
210+
const error = AV.Error(errorJSON.code, errorJSON.error);
211+
promise.reject(error);
212+
}
213+
return promise;
214+
};
185215

186-
// };
216+
const setRegionServer = (AV, region = 'cn') => {
217+
// 服务器请求的节点 host
218+
const API_HOST = {
219+
cn: 'https://api.leancloud.cn',
220+
us: 'https://us-api.leancloud.cn',
221+
};
222+
223+
const AVConfig = AV._config;
224+
AVConfig.region = region;
225+
// 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router
226+
if (AVConfig.APIServerURL) {
227+
return;
228+
}
229+
AVConfig.APIServerURL = API_HOST[region];
230+
if (region === 'cn') {
231+
Cache.get('APIServerURL').then(cachedServerURL => {
232+
if (cachedServerURL) {
233+
return cachedServerURL;
234+
} else {
235+
return ajax('get', `https://app-router.leancloud.cn/1/route?appId=${AV.applicationId}`)
236+
.then(servers => {
237+
if (servers.api_server) {
238+
cacheServerURL(servers.api_server, servers.ttl);
239+
return servers.api_server;
240+
}
241+
});
242+
}
243+
}).then(serverURL => {
244+
// 如果用户在 init 之后设置了 APIServerURL,保持用户设置
245+
if (AVConfig.APIServerURL === API_HOST[region]) {
246+
AVConfig.APIServerURL = `https://${serverURL}`;
247+
}
248+
});
249+
}
250+
};
187251

188252
const init = (AV) => {
189253
/**
@@ -207,35 +271,15 @@ const init = (AV) => {
207271

208272
return setHeaders(AV, sessionToken).then(
209273
headers => ajax(method, apiURL, dataObject, headers)
210-
.then(null, (response) => {
211-
// Transform the error into an instance of AV.Error by trying to parse
212-
// the error string as JSON.
213-
let error;
214-
if (response) {
215-
if (response.response) {
216-
error = new AV.Error(response.response.code, response.response.error);
217-
} else if (response.responseText) {
218-
try {
219-
const errorJSON = JSON.parse(response.responseText);
220-
if (errorJSON) {
221-
error = new AV.Error(errorJSON.code, errorJSON.error);
222-
}
223-
} catch (e) {
224-
// If we fail to parse the error text, that's okay.
225-
}
226-
}
227-
}
228-
error = error || new AV.Error(-1, response.responseText);
229-
230-
// By explicitly returning a rejected Promise, this will work with
231-
// either jQuery or Promises/A semantics.
232-
return Promise.error(error);
233-
})
274+
.then(null, (res) =>
275+
handleError(AV, res)
276+
)
234277
);
235278
};
236279
};
237280

238281
module.exports = {
239282
init,
240283
ajax,
284+
setRegionServer,
241285
};

src/utils.js

Lines changed: 7 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,11 @@
44
**/
55

66
const _ = require('underscore');
7-
const Cache = require('./cache');
8-
const ajax = require('./request').ajax;
7+
const request = require('./request');
98

109
const init = (AV) => {
11-
1210
// 挂载一些配置
13-
let AVConfig = AV._config;
14-
15-
// 服务器请求的节点 host
16-
const API_HOST = {
17-
cn: 'https://api.leancloud.cn',
18-
us: 'https://us-api.leancloud.cn',
19-
};
11+
const AVConfig = AV._config;
2012

2113
_.extend(AVConfig, {
2214

@@ -117,44 +109,6 @@ const init = (AV) => {
117109
AV._useMasterKey = false;
118110
};
119111

120-
const setRegionServer = (region = 'cn') => {
121-
AVConfig.region = region;
122-
// 如果用户在 init 之前设置了 APIServerURL,则跳过请求 router
123-
if (AVConfig.APIServerURL) {
124-
return;
125-
}
126-
AVConfig.APIServerURL = API_HOST[region];
127-
if (region === 'cn') {
128-
// TODO: remove appId match hack
129-
if (AV.applicationId.indexOf('-9Nh9j0Va') !== -1) {
130-
AVConfig.APIServerURL = 'https://e1-api.leancloud.cn';
131-
}
132-
133-
Cache.get('APIServerURL').then(cachedServerURL => {
134-
if (cachedServerURL) {
135-
return cachedServerURL;
136-
} else {
137-
return ajax('get', `https://app-router.leancloud.cn/1/route?appId=${AV.applicationId}`)
138-
.then(servers => {
139-
if (servers.api_server) {
140-
let ttl = 3600;
141-
if (typeof servers.ttl === 'number') {
142-
ttl = servers.ttl;
143-
}
144-
Cache.set('APIServerURL', servers.api_server, ttl * 1000);
145-
return servers.api_server;
146-
}
147-
});
148-
}
149-
}).then(serverURL => {
150-
// 如果用户在 init 之后设置了 APIServerURL,保持用户设置
151-
if (AVConfig.APIServerURL === API_HOST[region]) {
152-
AVConfig.APIServerURL = `https://${serverURL}`;
153-
}
154-
});
155-
}
156-
};
157-
158112
/**
159113
* Call this method first to set up your authentication tokens for AV.
160114
* You can get your app keys from the LeanCloud dashboard on http://leancloud.cn .
@@ -166,7 +120,6 @@ const init = (AV) => {
166120
*/
167121

168122
AV.init = (...args) => {
169-
170123
const masterKeyWarn = () => {
171124
console.warn('MasterKey should not be used in the browser. ' +
172125
'The permissions of MasterKey can be across all the server permissions,' +
@@ -181,7 +134,7 @@ const init = (AV) => {
181134
masterKeyWarn();
182135
}
183136
initialize(options.appId, options.appKey, options.masterKey);
184-
setRegionServer(options.region);
137+
request.setRegionServer(AV, options.region);
185138
AVConfig.disableCurrentUser = options.disableCurrentUser;
186139
} else {
187140
throw new Error('AV.init(): Parameter is not correct.');
@@ -195,7 +148,7 @@ const init = (AV) => {
195148
masterKeyWarn();
196149
}
197150
initialize(...args);
198-
setRegionServer('cn');
151+
request.setRegionServer(AV, 'cn');
199152
break;
200153
}
201154
};
@@ -238,7 +191,7 @@ const init = (AV) => {
238191
**/
239192
// TODO: 后续不再暴露此接口
240193
AV.useAVCloudCN = function(){
241-
setRegionServer('cn');
194+
request.setRegionServer(AV, 'cn');
242195
console.warn('Do not use AV.useAVCloudCN. Please use AV.init(), you can set the region of server.');
243196
};
244197

@@ -247,7 +200,7 @@ const init = (AV) => {
247200
**/
248201
// TODO: 后续不再暴露此接口
249202
AV.useAVCloudUS = function(){
250-
setRegionServer('us');
203+
request.setRegionServer(AV, 'us');
251204
console.warn('Do not use AV.useAVCloudUS. Please use AV.init(), you can set the region of server.');
252205
};
253206

@@ -331,7 +284,7 @@ const init = (AV) => {
331284
// TODO: Next version remove
332285
AV._ajax = (...args) => {
333286
console.warn('AV._ajax is deprecated, and will be removed in next release.');
334-
ajax(...args);
287+
request.ajax(...args);
335288
};
336289

337290
// A self-propagating extend function.

0 commit comments

Comments
 (0)