initOptions.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const ms = require('humanize-ms');
  2. const urlutil = require('url');
  3. const { checkBucketName: _checkBucketName } = require('../utils/checkBucketName');
  4. const { setRegion } = require('../utils/setRegion');
  5. const { checkConfigValid } = require('../utils/checkConfigValid');
  6. function setEndpoint(endpoint, secure) {
  7. checkConfigValid(endpoint, 'endpoint');
  8. let url = urlutil.parse(endpoint);
  9. if (!url.protocol) {
  10. url = urlutil.parse(`http${secure ? 's' : ''}://${endpoint}`);
  11. }
  12. if (url.protocol !== 'http:' && url.protocol !== 'https:') {
  13. throw new Error('Endpoint protocol must be http or https.');
  14. }
  15. return url;
  16. }
  17. module.exports = function (options) {
  18. if (!options
  19. || !options.accessKeyId
  20. || !options.accessKeySecret) {
  21. throw new Error('require accessKeyId, accessKeySecret');
  22. }
  23. if (options.bucket) {
  24. _checkBucketName(options.bucket);
  25. }
  26. const opts = Object.assign({
  27. region: 'oss-cn-hangzhou',
  28. internal: false,
  29. secure: false,
  30. timeout: 60000,
  31. bucket: null,
  32. endpoint: null,
  33. cname: false,
  34. isRequestPay: false,
  35. sldEnable: false,
  36. headerEncoding: 'utf-8',
  37. refreshSTSToken: null
  38. }, options);
  39. opts.accessKeyId = opts.accessKeyId.trim();
  40. opts.accessKeySecret = opts.accessKeySecret.trim();
  41. if (opts.timeout) {
  42. opts.timeout = ms(opts.timeout);
  43. }
  44. if (opts.endpoint) {
  45. opts.endpoint = setEndpoint(opts.endpoint, opts.secure);
  46. } else if (opts.region) {
  47. opts.endpoint = setRegion(opts.region, opts.internal, opts.secure);
  48. } else {
  49. throw new Error('require options.endpoint or options.region');
  50. }
  51. opts.inited = true;
  52. return opts;
  53. };