autoInject.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = autoInject;
  6. var _auto = require('./auto.js');
  7. var _auto2 = _interopRequireDefault(_auto);
  8. var _wrapAsync = require('./internal/wrapAsync.js');
  9. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  10. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  11. var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/;
  12. var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/;
  13. var FN_ARG_SPLIT = /,/;
  14. var FN_ARG = /(=.+)?(\s*)$/;
  15. function stripComments(string) {
  16. let stripped = '';
  17. let index = 0;
  18. let endBlockComment = string.indexOf('*/');
  19. while (index < string.length) {
  20. if (string[index] === '/' && string[index + 1] === '/') {
  21. // inline comment
  22. let endIndex = string.indexOf('\n', index);
  23. index = endIndex === -1 ? string.length : endIndex;
  24. } else if (endBlockComment !== -1 && string[index] === '/' && string[index + 1] === '*') {
  25. // block comment
  26. let endIndex = string.indexOf('*/', index);
  27. if (endIndex !== -1) {
  28. index = endIndex + 2;
  29. endBlockComment = string.indexOf('*/', index);
  30. } else {
  31. stripped += string[index];
  32. index++;
  33. }
  34. } else {
  35. stripped += string[index];
  36. index++;
  37. }
  38. }
  39. return stripped;
  40. }
  41. function parseParams(func) {
  42. const src = stripComments(func.toString());
  43. let match = src.match(FN_ARGS);
  44. if (!match) {
  45. match = src.match(ARROW_FN_ARGS);
  46. }
  47. if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src);
  48. let [, args] = match;
  49. return args.replace(/\s/g, '').split(FN_ARG_SPLIT).map(arg => arg.replace(FN_ARG, '').trim());
  50. }
  51. /**
  52. * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent
  53. * tasks are specified as parameters to the function, after the usual callback
  54. * parameter, with the parameter names matching the names of the tasks it
  55. * depends on. This can provide even more readable task graphs which can be
  56. * easier to maintain.
  57. *
  58. * If a final callback is specified, the task results are similarly injected,
  59. * specified as named parameters after the initial error parameter.
  60. *
  61. * The autoInject function is purely syntactic sugar and its semantics are
  62. * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}.
  63. *
  64. * @name autoInject
  65. * @static
  66. * @memberOf module:ControlFlow
  67. * @method
  68. * @see [async.auto]{@link module:ControlFlow.auto}
  69. * @category Control Flow
  70. * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of
  71. * the form 'func([dependencies...], callback). The object's key of a property
  72. * serves as the name of the task defined by that property, i.e. can be used
  73. * when specifying requirements for other tasks.
  74. * * The `callback` parameter is a `callback(err, result)` which must be called
  75. * when finished, passing an `error` (which can be `null`) and the result of
  76. * the function's execution. The remaining parameters name other tasks on
  77. * which the task is dependent, and the results from those tasks are the
  78. * arguments of those parameters.
  79. * @param {Function} [callback] - An optional callback which is called when all
  80. * the tasks have been completed. It receives the `err` argument if any `tasks`
  81. * pass an error to their callback, and a `results` object with any completed
  82. * task results, similar to `auto`.
  83. * @returns {Promise} a promise, if no callback is passed
  84. * @example
  85. *
  86. * // The example from `auto` can be rewritten as follows:
  87. * async.autoInject({
  88. * get_data: function(callback) {
  89. * // async code to get some data
  90. * callback(null, 'data', 'converted to array');
  91. * },
  92. * make_folder: function(callback) {
  93. * // async code to create a directory to store a file in
  94. * // this is run at the same time as getting the data
  95. * callback(null, 'folder');
  96. * },
  97. * write_file: function(get_data, make_folder, callback) {
  98. * // once there is some data and the directory exists,
  99. * // write the data to a file in the directory
  100. * callback(null, 'filename');
  101. * },
  102. * email_link: function(write_file, callback) {
  103. * // once the file is written let's email a link to it...
  104. * // write_file contains the filename returned by write_file.
  105. * callback(null, {'file':write_file, 'email':'user@example.com'});
  106. * }
  107. * }, function(err, results) {
  108. * console.log('err = ', err);
  109. * console.log('email_link = ', results.email_link);
  110. * });
  111. *
  112. * // If you are using a JS minifier that mangles parameter names, `autoInject`
  113. * // will not work with plain functions, since the parameter names will be
  114. * // collapsed to a single letter identifier. To work around this, you can
  115. * // explicitly specify the names of the parameters your task function needs
  116. * // in an array, similar to Angular.js dependency injection.
  117. *
  118. * // This still has an advantage over plain `auto`, since the results a task
  119. * // depends on are still spread into arguments.
  120. * async.autoInject({
  121. * //...
  122. * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) {
  123. * callback(null, 'filename');
  124. * }],
  125. * email_link: ['write_file', function(write_file, callback) {
  126. * callback(null, {'file':write_file, 'email':'user@example.com'});
  127. * }]
  128. * //...
  129. * }, function(err, results) {
  130. * console.log('err = ', err);
  131. * console.log('email_link = ', results.email_link);
  132. * });
  133. */
  134. function autoInject(tasks, callback) {
  135. var newTasks = {};
  136. Object.keys(tasks).forEach(key => {
  137. var taskFn = tasks[key];
  138. var params;
  139. var fnIsAsync = (0, _wrapAsync.isAsync)(taskFn);
  140. var hasNoDeps = !fnIsAsync && taskFn.length === 1 || fnIsAsync && taskFn.length === 0;
  141. if (Array.isArray(taskFn)) {
  142. params = [...taskFn];
  143. taskFn = params.pop();
  144. newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn);
  145. } else if (hasNoDeps) {
  146. // no dependencies, use the function as-is
  147. newTasks[key] = taskFn;
  148. } else {
  149. params = parseParams(taskFn);
  150. if (taskFn.length === 0 && !fnIsAsync && params.length === 0) {
  151. throw new Error("autoInject task functions require explicit parameters.");
  152. }
  153. // remove callback param
  154. if (!fnIsAsync) params.pop();
  155. newTasks[key] = params.concat(newTask);
  156. }
  157. function newTask(results, taskCb) {
  158. var newArgs = params.map(name => results[name]);
  159. newArgs.push(taskCb);
  160. (0, _wrapAsync2.default)(taskFn)(...newArgs);
  161. }
  162. });
  163. return (0, _auto2.default)(newTasks, callback);
  164. }
  165. module.exports = exports['default'];