Skip to content

Commit ddf11da

Browse files
committed
初始化 init 方法支持传入服务器节点选项
1 parent 7f251f1 commit ddf11da

File tree

2 files changed

+64
-65
lines changed

2 files changed

+64
-65
lines changed

src/file.js

Lines changed: 25 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
11
'use strict';
22

3-
var _ = require('underscore');
4-
53
// port from browserify path module
64
// since react-native packager won't shim node modules.
75
function extname(path) {
86
return path.match(/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/)[4];
97
}
108

11-
/*jshint bitwise:false *//*global FileReader: true, File: true */
129
module.exports = function(AV) {
10+
const _ = AV._;
11+
12+
// 挂载一些配置
13+
let avConfig = AV._config;
14+
1315
var b64Digit = function(number) {
1416
if (number < 26) {
1517
return String.fromCharCode(65 + number);
@@ -59,11 +61,9 @@ module.exports = function(AV) {
5961
};
6062

6163
// 判断是否是国内节点
62-
var isCnNode = function() {
63-
var serverHost = AV.serverURL.match(/\/\/(.*)/, 'g')[1];
64-
var cnApiHost = AV._config.cnApiUrl.match(/\/\/(.*)/, 'g')[1];
65-
return serverHost === cnApiHost;
66-
}
64+
const isCnNode = function() {
65+
return avConfig.region === 'cn';
66+
};
6767

6868
// A list of file extensions to mime types as found here:
6969
// http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-
@@ -280,7 +280,7 @@ module.exports = function(AV) {
280280
-1, "Attempted to use a FileReader on an unsupported browser."));
281281
}
282282

283-
var reader = new FileReader();
283+
var reader = new global.FileReader();
284284
reader.onloadend = function() {
285285
if (reader.readyState !== 2) {
286286
promise.reject(new AV.Error(-1, "Error reading file."));
@@ -344,7 +344,7 @@ module.exports = function(AV) {
344344
console.warn('Get current user failed. It seems this runtime use an async storage system, please new AV.File in the callback of AV.User.currentAsync().');
345345
}
346346
this._metaData = {
347-
owner: (currentUser != null ? currentUser.id : 'unknown')
347+
owner: (currentUser !== null ? currentUser.id : 'unknown')
348348
};
349349

350350
// Guess the content type from the extension if we need to.
@@ -366,9 +366,9 @@ module.exports = function(AV) {
366366
this._source = AV.Promise.as(dataBase64, guessedType);
367367
} else if (data && data.blob) {
368368
this._source = AV.Promise.as(data.blob, guessedType);
369-
} else if (typeof(File) !== "undefined" && data instanceof File) {
369+
} else if (typeof(File) !== "undefined" && data instanceof global.File) {
370370
this._source = AV.Promise.as(data, guessedType);
371-
} else if(AV._config.isNode && global.Buffer.isBuffer(data)) {
371+
} else if(avConfig.isNode && global.Buffer.isBuffer(data)) {
372372
// use global.Buffer to prevent browserify pack Buffer module
373373
this._base64 = data.toString('base64');
374374
this._source = AV.Promise.as(this._base64, guessedType);
@@ -402,7 +402,7 @@ module.exports = function(AV) {
402402
}
403403
file._url = url;
404404
//Mark the file is from external source.
405-
file._metaData['__source'] = 'external';
405+
file._metaData.__source = 'external';
406406
return file;
407407
};
408408

@@ -474,12 +474,12 @@ module.exports = function(AV) {
474474
* @param {Object} value an optional metadata value.
475475
**/
476476
metaData: function(attr, value) {
477-
if(attr != null && value != null){
478-
this._metaData[attr] = value;
479-
return this;
480-
}else if(attr != null){
481-
return this._metaData[attr];
482-
}else{
477+
if (attr !== null && value !== null) {
478+
this._metaData[attr] = value;
479+
return this;
480+
} else if (attr !== null) {
481+
return this._metaData[attr];
482+
} else {
483483
return this._metaData;
484484
}
485485
},
@@ -501,14 +501,13 @@ module.exports = function(AV) {
501501
throw "Invalid width or height value.";
502502
}
503503
quality = quality || 100;
504-
scaleToFit = (scaleToFit == null) ? true: scaleToFit;
505-
if(quality<=0 || quality>100){
504+
scaleToFit = (scaleToFit === null) ? true: scaleToFit;
505+
if(quality <= 0 || quality > 100){
506506
throw "Invalid quality value.";
507507
}
508508
fmt = fmt || 'png';
509509
var mode = scaleToFit ? 2: 1;
510-
return this.url() + '?imageView/' + mode + '/w/' + width + '/h/' + height
511-
+ '/q/' + quality + '/format/' + fmt;
510+
return this.url() + '?imageView/' + mode + '/w/' + width + '/h/' + height + '/q/' + quality + '/format/' + fmt;
512511
},
513512

514513
/**
@@ -551,8 +550,7 @@ module.exports = function(AV) {
551550
var hexOctet = function() {
552551
return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);
553552
};
554-
var key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet()
555-
+ extName;
553+
var key = hexOctet() + hexOctet() + hexOctet() + hexOctet() + hexOctet() + extName;
556554

557555
var data = {
558556
key: key,
@@ -561,7 +559,7 @@ module.exports = function(AV) {
561559
mime_type: type,
562560
metaData: self._metaData
563561
};
564-
if(type && self._metaData.mime_type == null)
562+
if(type && self._metaData.mime_type === null)
565563
self._metaData.mime_type = type;
566564
self._qiniu_key = key;
567565
return AV._request("qiniu", null, null, 'POST', data);
@@ -598,7 +596,7 @@ module.exports = function(AV) {
598596
// 通过国内 CDN 服务商上传
599597
var upload = require('./browserify-wrapper/upload');
600598
upload(self, AV, saveOptions);
601-
} else if (self._url && self._metaData['__source'] == 'external') {
599+
} else if (self._url && self._metaData.__source === 'external') {
602600
//external link file.
603601
var data = {
604602
name: self._name,

src/utils.js

Lines changed: 39 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
'use strict';
2-
3-
var _ = require('underscore');
4-
5-
/*global _: false, $: false, localStorage: false, process: true,
6-
XMLHttpRequest: false, XDomainRequest: false, exports: false,
7-
require: false */
82
module.exports = function(AV) {
93

4+
const _ = AV._;
5+
106
// 挂载一些配置
11-
_.extend(AV._config, {
12-
cnApiUrl: 'https://api.leancloud.cn',
13-
usApiUrl: 'https://us-api.leancloud.cn'
7+
let avConfig = AV._config;
8+
9+
_.extend(avConfig, {
10+
// 服务器请求的节点 host
11+
apiHost : {
12+
cn: 'https://api.leancloud.cn',
13+
us: 'https://us-api.leancloud.cn'
14+
},
15+
// 服务器节点地区,默认中国大陆
16+
region: 'cn'
1417
});
1518

1619
/**
@@ -23,7 +26,7 @@ module.exports = function(AV) {
2326

2427
// Check whether we are running in Node.js.
2528
if (typeof(process) !== 'undefined' && process.versions && process.versions.node) {
26-
AV._config.isNode = true;
29+
avConfig.isNode = true;
2730
}
2831

2932
// Helpers
@@ -89,7 +92,7 @@ module.exports = function(AV) {
8992
applicationId !== AV.applicationId &&
9093
applicationKey !== AV.applicationKey &&
9194
masterKey !== AV.masterKey) {
92-
console.warn('AVOSCloud SDK is already initialized, please don\'t reinitialize it.');
95+
console.warn('LeanCloud SDK is already initialized, please don\'t reinitialize it.');
9396
}
9497
AV.applicationId = applicationId;
9598
AV.applicationKey = applicationKey;
@@ -112,18 +115,25 @@ module.exports = function(AV) {
112115
case 1:
113116
const options = args[0];
114117
if (typeof options === 'object') {
115-
if (!AV._config.isNode && options.masterKey) {
118+
if (!avConfig.isNode && options.masterKey) {
116119
throw new Error('AV.init(): Master Key is only used in Node.js.');
117120
}
118121
initialize(options.appId, options.appKey, options.masterKey);
122+
123+
// 服务器地区选项,默认为中国大陆
124+
switch (options.region) {
125+
case 'us':
126+
avConfig.region = 'us';
127+
break;
128+
}
119129
} else {
120130
throw new Error('AV.init(): Parameter is not correct.');
121131
}
122132
break;
123133
// 兼容旧版本的初始化方法
124134
case 2:
125135
case 3:
126-
if (!AV._config.isNode && args.length === 3) {
136+
if (!avConfig.isNode && args.length === 3) {
127137
throw new Error('AV.init(): Master Key is only used in Node.js.');
128138
}
129139
initialize(...args);
@@ -132,11 +142,11 @@ module.exports = function(AV) {
132142
};
133143

134144
// If we're running in node.js, allow using the master key.
135-
if (AV._config.isNode) {
145+
if (avConfig.isNode) {
136146
AV.Cloud = AV.Cloud || {};
137147
/**
138-
* Switches the AVOSCloud SDK to using the Master key. The Master key grants
139-
* priveleged access to the data in AVOSCloud and can be used to bypass ACLs and
148+
* Switches the LeanCloud SDK to using the Master key. The Master key grants
149+
* priveleged access to the data in LeanCloud and can be used to bypass ACLs and
140150
* other restrictions that are applied to the client SDKs.
141151
* <p><strong><em>Available in Cloud Code and Node.js only.</em></strong>
142152
* </p>
@@ -164,23 +174,16 @@ module.exports = function(AV) {
164174
AV.applicationProduction = AV._isNullOrUndefined(production) ? 1: production;
165175
};
166176

167-
/**
168-
*Use china avoscloud API service
169-
*/
177+
// TODO: 后续不再暴露此接口
170178
AV.useAVCloudCN = function(){
171-
AV.serverURL = AV._config.cnApiUrl;
179+
avConfig.region = 'cn';
172180
};
173181

174-
/**
175-
*Use USA avoscloud API service
176-
*/
182+
// TODO: 后续不再暴露此接口
177183
AV.useAVCloudUS = function(){
178-
AV.serverURL = AV._config.usApiUrl;
184+
avConfig.region = 'us';
179185
};
180186

181-
// 默认使用国内节点
182-
AV.useAVCloudCN();
183-
184187
/**
185188
* Returns prefix for localStorage keys used by this instance of AV.
186189
* @param {String} path The relative suffix to append to it.
@@ -317,20 +320,21 @@ module.exports = function(AV) {
317320
throw "Bad route: '" + route + "'.";
318321
}
319322

320-
var url = AV.serverURL;
321-
if (url.charAt(url.length - 1) !== "/") {
322-
url += "/";
323+
// 兼容 AV.serverURL 旧方式设置 API Host,后续去掉
324+
let apiUrl = AV.serverURL || avConfig.apiHost[avConfig.region];
325+
if (apiUrl.charAt(apiUrl.length - 1) !== "/") {
326+
apiUrl += "/";
323327
}
324-
url += "1.1/" + route;
328+
apiUrl += "1.1/" + route;
325329
if (className) {
326-
url += "/" + className;
330+
apiUrl += "/" + className;
327331
}
328332
if (objectId) {
329-
url += "/" + objectId;
333+
apiUrl += "/" + objectId;
330334
}
331335
if ((route ==='users' || route === 'classes') && dataObject && dataObject._fetchWhenSave){
332336
delete dataObject._fetchWhenSave;
333-
url += '?new=true';
337+
apiUrl += '?new=true';
334338
}
335339

336340
dataObject = AV._.clone(dataObject || {});
@@ -357,7 +361,7 @@ module.exports = function(AV) {
357361
dataObject._InstallationId = _InstallationId;
358362

359363
var data = JSON.stringify(dataObject);
360-
return AV._ajax(method, url, data).then(null, function(response) {
364+
return AV._ajax(method, apiUrl, data).then(null, function(response) {
361365
// Transform the error into an instance of AV.Error by trying to parse
362366
// the error string as JSON.
363367
var error;
@@ -398,7 +402,6 @@ module.exports = function(AV) {
398402
* is set, then none of the AV Objects that are serialized can be dirty.
399403
*/
400404
AV._encode = function(value, seenObjects, disallowObjects) {
401-
var _ = AV._;
402405
if (value instanceof AV.Object) {
403406
if (disallowObjects) {
404407
throw "AV.Objects not allowed here";
@@ -463,7 +466,6 @@ module.exports = function(AV) {
463466
* TODO: make decode not mutate value.
464467
*/
465468
AV._decode = function(key, value) {
466-
var _ = AV._;
467469
if (!_.isObject(value)) {
468470
return value;
469471
}
@@ -613,7 +615,6 @@ module.exports = function(AV) {
613615
* * it does work for dictionaries with a "length" attribute.
614616
*/
615617
AV._objectEach = AV._each = function(obj, callback) {
616-
var _ = AV._;
617618
if (_.isObject(obj)) {
618619
_.each(_.keys(obj), function(key) {
619620
callback(obj[key], key);

0 commit comments

Comments
 (0)