index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. 'use strict';
  2. function Kareem() {
  3. this._pres = new Map();
  4. this._posts = new Map();
  5. }
  6. Kareem.prototype.execPre = function(name, context, args, callback) {
  7. if (arguments.length === 3) {
  8. callback = args;
  9. args = [];
  10. }
  11. var pres = get(this._pres, name, []);
  12. var numPres = pres.length;
  13. var numAsyncPres = pres.numAsync || 0;
  14. var currentPre = 0;
  15. var asyncPresLeft = numAsyncPres;
  16. var done = false;
  17. var $args = args;
  18. if (!numPres) {
  19. return process.nextTick(function() {
  20. callback(null);
  21. });
  22. }
  23. var next = function() {
  24. if (currentPre >= numPres) {
  25. return;
  26. }
  27. var pre = pres[currentPre];
  28. if (pre.isAsync) {
  29. var args = [
  30. decorateNextFn(_next),
  31. decorateNextFn(function(error) {
  32. if (error) {
  33. if (done) {
  34. return;
  35. }
  36. done = true;
  37. return callback(error);
  38. }
  39. if (--asyncPresLeft === 0 && currentPre >= numPres) {
  40. return callback(null);
  41. }
  42. })
  43. ];
  44. callMiddlewareFunction(pre.fn, context, args, args[0]);
  45. } else if (pre.fn.length > 0) {
  46. var args = [decorateNextFn(_next)];
  47. var _args = arguments.length >= 2 ? arguments : [null].concat($args);
  48. for (var i = 1; i < _args.length; ++i) {
  49. args.push(_args[i]);
  50. }
  51. callMiddlewareFunction(pre.fn, context, args, args[0]);
  52. } else {
  53. let maybePromise = null;
  54. try {
  55. maybePromise = pre.fn.call(context);
  56. } catch (err) {
  57. if (err != null) {
  58. return callback(err);
  59. }
  60. }
  61. if (isPromise(maybePromise)) {
  62. maybePromise.then(() => _next(), err => _next(err));
  63. } else {
  64. if (++currentPre >= numPres) {
  65. if (asyncPresLeft > 0) {
  66. // Leave parallel hooks to run
  67. return;
  68. } else {
  69. return process.nextTick(function() {
  70. callback(null);
  71. });
  72. }
  73. }
  74. next();
  75. }
  76. }
  77. };
  78. next.apply(null, [null].concat(args));
  79. function _next(error) {
  80. if (error) {
  81. if (done) {
  82. return;
  83. }
  84. done = true;
  85. return callback(error);
  86. }
  87. if (++currentPre >= numPres) {
  88. if (asyncPresLeft > 0) {
  89. // Leave parallel hooks to run
  90. return;
  91. } else {
  92. return callback(null);
  93. }
  94. }
  95. next.apply(context, arguments);
  96. }
  97. };
  98. Kareem.prototype.execPreSync = function(name, context, args) {
  99. var pres = get(this._pres, name, []);
  100. var numPres = pres.length;
  101. for (var i = 0; i < numPres; ++i) {
  102. pres[i].fn.apply(context, args || []);
  103. }
  104. };
  105. Kareem.prototype.execPost = function(name, context, args, options, callback) {
  106. if (arguments.length < 5) {
  107. callback = options;
  108. options = null;
  109. }
  110. var posts = get(this._posts, name, []);
  111. var numPosts = posts.length;
  112. var currentPost = 0;
  113. var firstError = null;
  114. if (options && options.error) {
  115. firstError = options.error;
  116. }
  117. if (!numPosts) {
  118. return process.nextTick(function() {
  119. callback.apply(null, [firstError].concat(args));
  120. });
  121. }
  122. var next = function() {
  123. var post = posts[currentPost].fn;
  124. var numArgs = 0;
  125. var argLength = args.length;
  126. var newArgs = [];
  127. for (var i = 0; i < argLength; ++i) {
  128. numArgs += args[i] && args[i]._kareemIgnore ? 0 : 1;
  129. if (!args[i] || !args[i]._kareemIgnore) {
  130. newArgs.push(args[i]);
  131. }
  132. }
  133. if (firstError) {
  134. if (post.length === numArgs + 2) {
  135. var _cb = decorateNextFn(function(error) {
  136. if (error) {
  137. firstError = error;
  138. }
  139. if (++currentPost >= numPosts) {
  140. return callback.call(null, firstError);
  141. }
  142. next();
  143. });
  144. callMiddlewareFunction(post, context,
  145. [firstError].concat(newArgs).concat([_cb]), _cb);
  146. } else {
  147. if (++currentPost >= numPosts) {
  148. return callback.call(null, firstError);
  149. }
  150. next();
  151. }
  152. } else {
  153. const _cb = decorateNextFn(function(error) {
  154. if (error) {
  155. firstError = error;
  156. return next();
  157. }
  158. if (++currentPost >= numPosts) {
  159. return callback.apply(null, [null].concat(args));
  160. }
  161. next();
  162. });
  163. if (post.length === numArgs + 2) {
  164. // Skip error handlers if no error
  165. if (++currentPost >= numPosts) {
  166. return callback.apply(null, [null].concat(args));
  167. }
  168. return next();
  169. }
  170. if (post.length === numArgs + 1) {
  171. callMiddlewareFunction(post, context, newArgs.concat([_cb]), _cb);
  172. } else {
  173. let error;
  174. let maybePromise;
  175. try {
  176. maybePromise = post.apply(context, newArgs);
  177. } catch (err) {
  178. error = err;
  179. firstError = err;
  180. }
  181. if (isPromise(maybePromise)) {
  182. return maybePromise.then(() => _cb(), err => _cb(err));
  183. }
  184. if (++currentPost >= numPosts) {
  185. return callback.apply(null, [error].concat(args));
  186. }
  187. next(error);
  188. }
  189. }
  190. };
  191. next();
  192. };
  193. Kareem.prototype.execPostSync = function(name, context, args) {
  194. const posts = get(this._posts, name, []);
  195. const numPosts = posts.length;
  196. for (let i = 0; i < numPosts; ++i) {
  197. posts[i].fn.apply(context, args || []);
  198. }
  199. };
  200. Kareem.prototype.createWrapperSync = function(name, fn) {
  201. var kareem = this;
  202. return function syncWrapper() {
  203. kareem.execPreSync(name, this, arguments);
  204. var toReturn = fn.apply(this, arguments);
  205. kareem.execPostSync(name, this, [toReturn]);
  206. return toReturn;
  207. };
  208. }
  209. function _handleWrapError(instance, error, name, context, args, options, callback) {
  210. if (options.useErrorHandlers) {
  211. var _options = { error: error };
  212. return instance.execPost(name, context, args, _options, function(error) {
  213. return typeof callback === 'function' && callback(error);
  214. });
  215. } else {
  216. return typeof callback === 'function' ?
  217. callback(error) :
  218. undefined;
  219. }
  220. }
  221. Kareem.prototype.wrap = function(name, fn, context, args, options) {
  222. const lastArg = (args.length > 0 ? args[args.length - 1] : null);
  223. const argsWithoutCb = typeof lastArg === 'function' ?
  224. args.slice(0, args.length - 1) :
  225. args;
  226. const _this = this;
  227. options = options || {};
  228. const checkForPromise = options.checkForPromise;
  229. this.execPre(name, context, args, function(error) {
  230. if (error) {
  231. const numCallbackParams = options.numCallbackParams || 0;
  232. const errorArgs = options.contextParameter ? [context] : [];
  233. for (var i = errorArgs.length; i < numCallbackParams; ++i) {
  234. errorArgs.push(null);
  235. }
  236. return _handleWrapError(_this, error, name, context, errorArgs,
  237. options, lastArg);
  238. }
  239. const end = (typeof lastArg === 'function' ? args.length - 1 : args.length);
  240. const numParameters = fn.length;
  241. const ret = fn.apply(context, args.slice(0, end).concat(_cb));
  242. if (checkForPromise) {
  243. if (ret != null && typeof ret.then === 'function') {
  244. // Thenable, use it
  245. return ret.then(
  246. res => _cb(null, res),
  247. err => _cb(err)
  248. );
  249. }
  250. // If `fn()` doesn't have a callback argument and doesn't return a
  251. // promise, assume it is sync
  252. if (numParameters < end + 1) {
  253. return _cb(null, ret);
  254. }
  255. }
  256. function _cb() {
  257. const args = arguments;
  258. const argsWithoutError = Array.prototype.slice.call(arguments, 1);
  259. if (options.nullResultByDefault && argsWithoutError.length === 0) {
  260. argsWithoutError.push(null);
  261. }
  262. if (arguments[0]) {
  263. // Assume error
  264. return _handleWrapError(_this, arguments[0], name, context,
  265. argsWithoutError, options, lastArg);
  266. } else {
  267. _this.execPost(name, context, argsWithoutError, function() {
  268. if (arguments[0]) {
  269. return typeof lastArg === 'function' ?
  270. lastArg(arguments[0]) :
  271. undefined;
  272. }
  273. return typeof lastArg === 'function' ?
  274. lastArg.apply(context, arguments) :
  275. undefined;
  276. });
  277. }
  278. }
  279. });
  280. };
  281. Kareem.prototype.filter = function(fn) {
  282. const clone = this.clone();
  283. const pres = Array.from(clone._pres.keys());
  284. for (const name of pres) {
  285. const hooks = this._pres.get(name).
  286. map(h => Object.assign({}, h, { name: name })).
  287. filter(fn);
  288. if (hooks.length === 0) {
  289. clone._pres.delete(name);
  290. continue;
  291. }
  292. hooks.numAsync = hooks.filter(h => h.isAsync).length;
  293. clone._pres.set(name, hooks);
  294. }
  295. const posts = Array.from(clone._posts.keys());
  296. for (const name of posts) {
  297. const hooks = this._posts.get(name).
  298. map(h => Object.assign({}, h, { name: name })).
  299. filter(fn);
  300. if (hooks.length === 0) {
  301. clone._posts.delete(name);
  302. continue;
  303. }
  304. clone._posts.set(name, hooks);
  305. }
  306. return clone;
  307. };
  308. Kareem.prototype.hasHooks = function(name) {
  309. return this._pres.has(name) || this._posts.has(name);
  310. };
  311. Kareem.prototype.createWrapper = function(name, fn, context, options) {
  312. var _this = this;
  313. if (!this.hasHooks(name)) {
  314. // Fast path: if there's no hooks for this function, just return the
  315. // function wrapped in a nextTick()
  316. return function() {
  317. process.nextTick(() => fn.apply(this, arguments));
  318. };
  319. }
  320. return function() {
  321. var _context = context || this;
  322. var args = Array.prototype.slice.call(arguments);
  323. _this.wrap(name, fn, _context, args, options);
  324. };
  325. };
  326. Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) {
  327. let options = {};
  328. if (typeof isAsync === 'object' && isAsync != null) {
  329. options = isAsync;
  330. isAsync = options.isAsync;
  331. } else if (typeof arguments[1] !== 'boolean') {
  332. error = fn;
  333. fn = isAsync;
  334. isAsync = false;
  335. }
  336. const pres = get(this._pres, name, []);
  337. this._pres.set(name, pres);
  338. if (isAsync) {
  339. pres.numAsync = pres.numAsync || 0;
  340. ++pres.numAsync;
  341. }
  342. if (typeof fn !== 'function') {
  343. throw new Error('pre() requires a function, got "' + typeof fn + '"');
  344. }
  345. if (unshift) {
  346. pres.unshift(Object.assign({}, options, { fn: fn, isAsync: isAsync }));
  347. } else {
  348. pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync }));
  349. }
  350. return this;
  351. };
  352. Kareem.prototype.post = function(name, options, fn, unshift) {
  353. const hooks = get(this._posts, name, []);
  354. if (typeof options === 'function') {
  355. unshift = !!fn;
  356. fn = options;
  357. options = {};
  358. }
  359. if (typeof fn !== 'function') {
  360. throw new Error('post() requires a function, got "' + typeof fn + '"');
  361. }
  362. if (unshift) {
  363. hooks.unshift(Object.assign({}, options, { fn: fn }));
  364. } else {
  365. hooks.push(Object.assign({}, options, { fn: fn }));
  366. }
  367. this._posts.set(name, hooks);
  368. return this;
  369. };
  370. Kareem.prototype.clone = function() {
  371. const n = new Kareem();
  372. for (let key of this._pres.keys()) {
  373. const clone = this._pres.get(key).slice();
  374. clone.numAsync = this._pres.get(key).numAsync;
  375. n._pres.set(key, clone);
  376. }
  377. for (let key of this._posts.keys()) {
  378. n._posts.set(key, this._posts.get(key).slice());
  379. }
  380. return n;
  381. };
  382. Kareem.prototype.merge = function(other, clone) {
  383. clone = arguments.length === 1 ? true : clone;
  384. var ret = clone ? this.clone() : this;
  385. for (let key of other._pres.keys()) {
  386. const sourcePres = get(ret._pres, key, []);
  387. const deduplicated = other._pres.get(key).
  388. // Deduplicate based on `fn`
  389. filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1);
  390. const combined = sourcePres.concat(deduplicated);
  391. combined.numAsync = sourcePres.numAsync || 0;
  392. combined.numAsync += deduplicated.filter(p => p.isAsync).length;
  393. ret._pres.set(key, combined);
  394. }
  395. for (let key of other._posts.keys()) {
  396. const sourcePosts = get(ret._posts, key, []);
  397. const deduplicated = other._posts.get(key).
  398. filter(p => sourcePosts.indexOf(p) === -1);
  399. ret._posts.set(key, sourcePosts.concat(deduplicated));
  400. }
  401. return ret;
  402. };
  403. function get(map, key, def) {
  404. if (map.has(key)) {
  405. return map.get(key);
  406. }
  407. return def;
  408. }
  409. function callMiddlewareFunction(fn, context, args, next) {
  410. let maybePromise;
  411. try {
  412. maybePromise = fn.apply(context, args);
  413. } catch (error) {
  414. return next(error);
  415. }
  416. if (isPromise(maybePromise)) {
  417. maybePromise.then(() => next(), err => next(err));
  418. }
  419. }
  420. function isPromise(v) {
  421. return v != null && typeof v.then === 'function';
  422. }
  423. function decorateNextFn(fn) {
  424. var called = false;
  425. var _this = this;
  426. return function() {
  427. // Ensure this function can only be called once
  428. if (called) {
  429. return;
  430. }
  431. called = true;
  432. // Make sure to clear the stack so try/catch doesn't catch errors
  433. // in subsequent middleware
  434. return process.nextTick(() => fn.apply(_this, arguments));
  435. };
  436. }
  437. module.exports = Kareem;