wrapper.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. var co = require('co');
  3. var OssClient = require('..');
  4. module.exports = Client;
  5. function isGenerator(obj) {
  6. return obj && 'function' == typeof obj.next && 'function' == typeof obj.throw;
  7. }
  8. function isGeneratorFunction(obj) {
  9. if (!obj) return false;
  10. var constructor = obj.constructor;
  11. if (!constructor) return false;
  12. if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
  13. return isGenerator(constructor.prototype) || isGenerator(obj.prototype);
  14. }
  15. function wrap(ObjectClass, options) {
  16. var client = new ObjectClass(options);
  17. var props = Object.keys(client);
  18. var protoProps = Object.keys(Object.getPrototypeOf(client));
  19. props.concat(protoProps).forEach(function(key) {
  20. if (isGeneratorFunction(client[key])) {
  21. this[key] = co.wrap(client[key]).bind(client);
  22. } else {
  23. this[key] = client[key];
  24. }
  25. }, this);
  26. }
  27. function Client(options) {
  28. if (!(this instanceof Client)) {
  29. return new Client(options);
  30. }
  31. wrap.call(this, OssClient, options);
  32. }
  33. Client.STS = function STSClient(options) {
  34. if (!(this instanceof STSClient)) {
  35. return new STSClient(options);
  36. }
  37. wrap.call(this, OssClient.STS, options);
  38. }