autoInject.js 6.0 KB

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