utils.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict';
  2. const co = require('co');
  3. const is = require('is-type-of');
  4. const stringify = require('json-stringify-safe');
  5. const MAX_REQUEST_ID = Math.pow(2, 30); // avoid write big integer
  6. const empty = () => {};
  7. let id = 0;
  8. function nextId() {
  9. id += 1;
  10. if (id >= MAX_REQUEST_ID) {
  11. id = 1;
  12. }
  13. return id;
  14. }
  15. /**
  16. * generate requestId
  17. *
  18. * @return {Number} requestId
  19. */
  20. exports.nextId = nextId;
  21. // for unittest
  22. exports.setId = val => {
  23. id = val;
  24. };
  25. /**
  26. * event delegate
  27. *
  28. * @param {EventEmitter} from - from object
  29. * @param {EventEmitter} to - to object
  30. * @return {void}
  31. */
  32. exports.delegateEvents = (from, to) => {
  33. // ignore the sdk-base defaultErrorHandler
  34. // https://github.com/node-modules/sdk-base/blob/master/index.js#L131
  35. if (from.listeners('error').length <= 1) {
  36. from.on('error', empty);
  37. }
  38. from.emit = new Proxy(from.emit, {
  39. apply(target, thisArg, args) {
  40. target.apply(from, args);
  41. to.emit.apply(to, args);
  42. return thisArg;
  43. },
  44. });
  45. };
  46. function formatKey(reg) {
  47. return stringify(reg);
  48. }
  49. /**
  50. * normalize object to string
  51. *
  52. * @param {Object} reg - reg object
  53. * @return {String} key
  54. */
  55. exports.formatKey = formatKey;
  56. /**
  57. * call a function, support common function, generator function, or a function returning promise
  58. *
  59. * @param {Function} fn - common function, generator function, or a function returning promise
  60. * @param {Array} args - args as fn() paramaters
  61. * @return {*} data returned by fn
  62. */
  63. exports.callFn = async function(fn, args) {
  64. args = args || [];
  65. if (!is.function(fn)) return;
  66. if (is.generatorFunction(fn)) {
  67. return await co(function* () {
  68. return yield fn(...args);
  69. });
  70. }
  71. const r = fn(...args);
  72. if (is.promise(r)) {
  73. return await r;
  74. }
  75. return r;
  76. };
  77. exports.findMethodName = (descriptors, type) => {
  78. for (const method of descriptors.keys()) {
  79. const descriptor = descriptors.get(method);
  80. if (descriptor.type === 'delegate' && descriptor.to === type) {
  81. return method;
  82. }
  83. }
  84. return null;
  85. };