Skip to content

Commit

Permalink
Refactor/init option (ali-sdk#671)
Browse files Browse the repository at this point in the history
* refactor: common initOptions

* doc: remove usefetch
  • Loading branch information
PeterRao authored and luozhang002 committed Oct 23, 2019
1 parent 1f49ff3 commit a35c8b6
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 146 deletions.
14 changes: 4 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,7 @@ Node.js >= 8.0.0 required. You can use 4.x in Node.js < 8.

`Note`:
- For Lower browsers you can refer to [PostObject](https://help.aliyun.com/document_detail/31988.html), if you want to see more practices ,please refer to [Web Post](https://help.aliyun.com/document_detail/31923.html)
- QQ Browser ,we suggest config useFetch option false, it will upload with `XMLhttpRequest`, eg

```javascript
let client = new OSS({
...,
useFetch: false
})
```
## License

[MIT](LICENSE)
Expand All @@ -63,7 +56,7 @@ All operation use es7 async/await to implement. All api is async function.
- [Data Regions](#data-regions)
- [Create Account](#create-acount)
- [Create A Bucket Instance](#create-a-bucket-instance)
- [#oss(options)](#ossoptions)
- [oss(options)](#ossoptions)
- [Bucket Operations](#bucket-operations)
- Base
- [.listBuckets(query[, options])](#listbucketsquery-options)
Expand Down Expand Up @@ -133,7 +126,7 @@ All operation use es7 async/await to implement. All api is async function.
- [.createVod(id, name, time[, options])](#createvodid-name-time-options)
- [.getRtmpUrl(channelId[, options])](#getrtmpurlchannelid-options)
- [Create A Image Service Instance](#create-a-image-service-instance)
- [#oss.ImageClient(options)](#ossimageclientoptions)
- [oss.ImageClient(options)](#ossimageclientoptions)
- [Image Operations](#image-operations)
- [imgClient.get(name, file[, options])](#imgclientgetname-file-options)
- [imgClient.getStream(name[, options])](#imgclientgetstreamname-options)
Expand Down Expand Up @@ -295,7 +288,8 @@ options:
- [cname] {Boolean}, default false, access oss with custom domain name. if true, you can fill `endpoint` field with your custom domain name,
- [isRequestPay] {Boolean}, default false, whether request payer function of the bucket is open, if true, will send headers `'x-oss-request-payer': 'requester'` to oss server.
the details you can see [requestPay](https://help.aliyun.com/document_detail/91337.htm)
- [useFetch] {Boolean}, default true, it just work in Browser, if true,it means upload object with `fetch` mode ,else `XMLHttpRequest`
- [useFetch] {Boolean}, default false, it just work in Browser, if true,it means upload object with
`fetch` mode ,else `XMLHttpRequest`

example:

Expand Down
78 changes: 9 additions & 69 deletions lib/browser/client.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@

const debug = require('debug')('ali-oss');
const crypto = require('crypto');
const path = require('path');
const copy = require('copy-to');
const mime = require('mime');
const xml = require('xml2js');
const ms = require('humanize-ms');
const AgentKeepalive = require('agentkeepalive');
const merge = require('merge-descriptors');
const urlutil = require('url');
Expand All @@ -18,42 +16,18 @@ const dateFormat = require('dateformat');
const bowser = require('bowser');
const signUtils = require('../common/signUtils');
const utils = require('../common/utils');
const _initOptions = require('../common/client/initOptions');

const globalHttpAgent = new AgentKeepalive();

function getHeader(headers, name) {
return headers[name] || headers[name.toLowerCase()];
}

function setEndpoint(endpoint, secure) {
let url = urlutil.parse(endpoint);

if (!url.protocol) {
const protocol = secure ? 'https://' : 'http://';
url = urlutil.parse(protocol + endpoint);
}

if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error('Endpoint protocol must be http or https.');
}

return url;
}

function setRegion(region, internal, secure) {
const protocol = secure ? 'https://' : 'http://';
let suffix = internal ? '-internal.aliyuncs.com' : '.aliyuncs.com';
const prefix = 'vpc100-oss-cn-';
// aliyun VPC region: https://help.aliyun.com/knowledge_detail/38740.html
if (region.substr(0, prefix.length) === prefix) {
suffix = '.aliyuncs.com';
}

return urlutil.parse(protocol + region + suffix);
}

// check local web protocol,if https secure default set true , if http secure default set false
function isHttpsWebProtocol() {
// for web worker not use window.location.
// eslint-disable-next-line no-restricted-globals
return location && location.protocol === 'https:';
}

Expand Down Expand Up @@ -93,47 +67,13 @@ Client.initOptions = function initOptions(options) {
if (!options.stsToken) {
console.warn('Please use STS Token for safety, see more details at https://help.aliyun.com/document_detail/32077.html');
}
const opts = Object.assign({
secure: isHttpsWebProtocol(),
// for browser compatibility disable fetch.
useFetch: false
}, options);

if (!options
|| !options.accessKeyId
|| !options.accessKeySecret) {
throw new Error('require accessKeyId, accessKeySecret');
}

const isHttpsProtocol = isHttpsWebProtocol();
const opts = {
region: 'oss-cn-hangzhou',
internal: false,
secure: isHttpsProtocol,
bucket: null,
endpoint: null,
cname: false,
isRequestPay: false,
useFetch: true
};

Object.keys(options).forEach((key) => {
if (options[key] !== undefined) {
opts[key] = options[key];
}
});
opts.accessKeyId = opts.accessKeyId.trim();
opts.accessKeySecret = opts.accessKeySecret.trim();

if (opts.timeout) {
opts.timeout = ms(opts.timeout);
}

if (opts.endpoint) {
opts.endpoint = setEndpoint(opts.endpoint, opts.secure);
} else if (opts.region) {
opts.endpoint = setRegion(opts.region, opts.internal, opts.secure);
} else {
throw new Error('require options.endpoint or options.region');
}

opts.inited = true;
return opts;
return _initOptions(opts);
};


Expand Down
4 changes: 2 additions & 2 deletions lib/bucket.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@


const assert = require('assert');
const utils = require('./common/utils/checkBucketname');
const utils = require('./common/utils/checkBucketName');

const proto = exports;

Expand All @@ -18,7 +18,7 @@ function toArray(obj) {
}

/**
* check Bucket name
* check Bucket Name
*/

proto._checkBucketName = function _checkBucketName(name) {
Expand Down
65 changes: 2 additions & 63 deletions lib/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ const path = require('path');
const copy = require('copy-to');
const mime = require('mime');
const xml = require('xml2js');
const ms = require('humanize-ms');
const AgentKeepalive = require('agentkeepalive');
const HttpsAgentKeepalive = require('agentkeepalive').HttpsAgent;
const merge = require('merge-descriptors');
Expand All @@ -20,6 +19,7 @@ const dateFormat = require('dateformat');
const bowser = require('bowser');
const signUtils = require('./common/signUtils');
const utils = require('./common/utils');
const _initOptions = require('./common/client/initOptions');

const globalHttpAgent = new AgentKeepalive();
const globalHttpsAgent = new HttpsAgentKeepalive();
Expand All @@ -28,31 +28,6 @@ function getHeader(headers, name) {
return headers[name] || headers[name.toLowerCase()];
}

function setEndpoint(endpoint) {
let url = urlutil.parse(endpoint);

if (!url.protocol) {
url = urlutil.parse(`http://${endpoint}`);
}

if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error('Endpoint protocol must be http or https.');
}

return url;
}

function setRegion(region, internal, secure) {
const protocol = secure ? 'https://' : 'http://';
let suffix = internal ? '-internal.aliyuncs.com' : '.aliyuncs.com';
const prefix = 'vpc100-oss-cn-';
// aliyun VPC region: https://help.aliyun.com/knowledge_detail/38740.html
if (region.substr(0, prefix.length) === prefix) {
suffix = '.aliyuncs.com';
}

return urlutil.parse(protocol + region + suffix);
}

function Client(options, ctx) {
if (!(this instanceof Client)) {
Expand Down Expand Up @@ -84,43 +59,7 @@ function Client(options, ctx) {
module.exports = Client;

Client.initOptions = function initOptions(options) {
if (!options
|| !options.accessKeyId
|| !options.accessKeySecret) {
throw new Error('require accessKeyId, accessKeySecret');
}

const opts = {
region: 'oss-cn-hangzhou',
internal: false,
secure: false,
timeout: 60000, // 60s
bucket: null,
endpoint: null,
cname: false,
isRequestPay: false
};

Object.keys(options).forEach((key) => {
if (options[key] !== undefined) {
opts[key] = options[key];
}
});
opts.accessKeyId = opts.accessKeyId.trim();
opts.accessKeySecret = opts.accessKeySecret.trim();

opts.timeout = ms(opts.timeout);

if (opts.endpoint) {
opts.endpoint = setEndpoint(opts.endpoint);
} else if (opts.region) {
opts.endpoint = setRegion(opts.region, opts.internal, opts.secure);
} else {
throw new Error('require options.endpoint or options.region');
}

opts.inited = true;
return opts;
return _initOptions(options);
};

/**
Expand Down
65 changes: 65 additions & 0 deletions lib/common/client/initOptions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const ms = require('humanize-ms');
const urlutil = require('url');

function setEndpoint(endpoint) {
let url = urlutil.parse(endpoint);

if (!url.protocol) {
url = urlutil.parse(`http://${endpoint}`);
}

if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw new Error('Endpoint protocol must be http or https.');
}

return url;
}

function setRegion(region, internal, secure) {
const protocol = secure ? 'https://' : 'http://';
let suffix = internal ? '-internal.aliyuncs.com' : '.aliyuncs.com';
const prefix = 'vpc100-oss-cn-';
// aliyun VPC region: https://help.aliyun.com/knowledge_detail/38740.html
if (region.substr(0, prefix.length) === prefix) {
suffix = '.aliyuncs.com';
}

return urlutil.parse(protocol + region + suffix);
}


module.exports = function (options) {
if (!options
|| !options.accessKeyId
|| !options.accessKeySecret) {
throw new Error('require accessKeyId, accessKeySecret');
}
const opts = Object.assign({
region: 'oss-cn-hangzhou',
internal: false,
secure: false,
timeout: 60000,
bucket: null,
endpoint: null,
cname: false,
isRequestPay: false
}, options);

opts.accessKeyId = opts.accessKeyId.trim();
opts.accessKeySecret = opts.accessKeySecret.trim();

if (opts.timeout) {
opts.timeout = ms(opts.timeout);
}

if (opts.endpoint) {
opts.endpoint = setEndpoint(opts.endpoint, opts.secure);
} else if (opts.region) {
opts.endpoint = setRegion(opts.region, opts.internal, opts.secure);
} else {
throw new Error('require options.endpoint or options.region');
}

opts.inited = true;
return opts;
};
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
/**
* check Bucket name
* check Bucket Name
*/

exports._checkBucketName = function (name) {
const bucketRegex = /^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$/;
const checkBucket = bucketRegex.test(name);
return checkBucket;
};
};

0 comments on commit a35c8b6

Please sign in to comment.