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