index.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. let ret;
  242. try {
  243. ret = fn.apply(context, args.slice(0, end).concat(_cb));
  244. } catch (err) {
  245. return _cb(err);
  246. }
  247. if (checkForPromise) {
  248. if (ret != null && typeof ret.then === 'function') {
  249. // Thenable, use it
  250. return ret.then(
  251. res => _cb(null, res),
  252. err => _cb(err)
  253. );
  254. }
  255. // If `fn()` doesn't have a callback argument and doesn't return a
  256. // promise, assume it is sync
  257. if (numParameters < end + 1) {
  258. return _cb(null, ret);
  259. }
  260. }
  261. function _cb() {
  262. const args = arguments;
  263. const argsWithoutError = Array.prototype.slice.call(arguments, 1);
  264. if (options.nullResultByDefault && argsWithoutError.length === 0) {
  265. argsWithoutError.push(null);
  266. }
  267. if (arguments[0]) {
  268. // Assume error
  269. return _handleWrapError(_this, arguments[0], name, context,
  270. argsWithoutError, options, lastArg);
  271. } else {
  272. _this.execPost(name, context, argsWithoutError, function() {
  273. if (arguments[0]) {
  274. return typeof lastArg === 'function' ?
  275. lastArg(arguments[0]) :
  276. undefined;
  277. }
  278. return typeof lastArg === 'function' ?
  279. lastArg.apply(context, arguments) :
  280. undefined;
  281. });
  282. }
  283. }
  284. });
  285. };
  286. Kareem.prototype.filter = function(fn) {
  287. const clone = this.clone();
  288. const pres = Array.from(clone._pres.keys());
  289. for (const name of pres) {
  290. const hooks = this._pres.get(name).
  291. map(h => Object.assign({}, h, { name: name })).
  292. filter(fn);
  293. if (hooks.length === 0) {
  294. clone._pres.delete(name);
  295. continue;
  296. }
  297. hooks.numAsync = hooks.filter(h => h.isAsync).length;
  298. clone._pres.set(name, hooks);
  299. }
  300. const posts = Array.from(clone._posts.keys());
  301. for (const name of posts) {
  302. const hooks = this._posts.get(name).
  303. map(h => Object.assign({}, h, { name: name })).
  304. filter(fn);
  305. if (hooks.length === 0) {
  306. clone._posts.delete(name);
  307. continue;
  308. }
  309. clone._posts.set(name, hooks);
  310. }
  311. return clone;
  312. };
  313. Kareem.prototype.hasHooks = function(name) {
  314. return this._pres.has(name) || this._posts.has(name);
  315. };
  316. Kareem.prototype.createWrapper = function(name, fn, context, options) {
  317. var _this = this;
  318. if (!this.hasHooks(name)) {
  319. // Fast path: if there's no hooks for this function, just return the
  320. // function wrapped in a nextTick()
  321. return function() {
  322. process.nextTick(() => fn.apply(this, arguments));
  323. };
  324. }
  325. return function() {
  326. var _context = context || this;
  327. var args = Array.prototype.slice.call(arguments);
  328. _this.wrap(name, fn, _context, args, options);
  329. };
  330. };
  331. Kareem.prototype.pre = function(name, isAsync, fn, error, unshift) {
  332. let options = {};
  333. if (typeof isAsync === 'object' && isAsync != null) {
  334. options = isAsync;
  335. isAsync = options.isAsync;
  336. } else if (typeof arguments[1] !== 'boolean') {
  337. error = fn;
  338. fn = isAsync;
  339. isAsync = false;
  340. }
  341. const pres = get(this._pres, name, []);
  342. this._pres.set(name, pres);
  343. if (isAsync) {
  344. pres.numAsync = pres.numAsync || 0;
  345. ++pres.numAsync;
  346. }
  347. if (typeof fn !== 'function') {
  348. throw new Error('pre() requires a function, got "' + typeof fn + '"');
  349. }
  350. if (unshift) {
  351. pres.unshift(Object.assign({}, options, { fn: fn, isAsync: isAsync }));
  352. } else {
  353. pres.push(Object.assign({}, options, { fn: fn, isAsync: isAsync }));
  354. }
  355. return this;
  356. };
  357. Kareem.prototype.post = function(name, options, fn, unshift) {
  358. const hooks = get(this._posts, name, []);
  359. if (typeof options === 'function') {
  360. unshift = !!fn;
  361. fn = options;
  362. options = {};
  363. }
  364. if (typeof fn !== 'function') {
  365. throw new Error('post() requires a function, got "' + typeof fn + '"');
  366. }
  367. if (unshift) {
  368. hooks.unshift(Object.assign({}, options, { fn: fn }));
  369. } else {
  370. hooks.push(Object.assign({}, options, { fn: fn }));
  371. }
  372. this._posts.set(name, hooks);
  373. return this;
  374. };
  375. Kareem.prototype.clone = function() {
  376. const n = new Kareem();
  377. for (let key of this._pres.keys()) {
  378. const clone = this._pres.get(key).slice();
  379. clone.numAsync = this._pres.get(key).numAsync;
  380. n._pres.set(key, clone);
  381. }
  382. for (let key of this._posts.keys()) {
  383. n._posts.set(key, this._posts.get(key).slice());
  384. }
  385. return n;
  386. };
  387. Kareem.prototype.merge = function(other, clone) {
  388. clone = arguments.length === 1 ? true : clone;
  389. var ret = clone ? this.clone() : this;
  390. for (let key of other._pres.keys()) {
  391. const sourcePres = get(ret._pres, key, []);
  392. const deduplicated = other._pres.get(key).
  393. // Deduplicate based on `fn`
  394. filter(p => sourcePres.map(_p => _p.fn).indexOf(p.fn) === -1);
  395. const combined = sourcePres.concat(deduplicated);
  396. combined.numAsync = sourcePres.numAsync || 0;
  397. combined.numAsync += deduplicated.filter(p => p.isAsync).length;
  398. ret._pres.set(key, combined);
  399. }
  400. for (let key of other._posts.keys()) {
  401. const sourcePosts = get(ret._posts, key, []);
  402. const deduplicated = other._posts.get(key).
  403. filter(p => sourcePosts.indexOf(p) === -1);
  404. ret._posts.set(key, sourcePosts.concat(deduplicated));
  405. }
  406. return ret;
  407. };
  408. function get(map, key, def) {
  409. if (map.has(key)) {
  410. return map.get(key);
  411. }
  412. return def;
  413. }
  414. function callMiddlewareFunction(fn, context, args, next) {
  415. let maybePromise;
  416. try {
  417. maybePromise = fn.apply(context, args);
  418. } catch (error) {
  419. return next(error);
  420. }
  421. if (isPromise(maybePromise)) {
  422. maybePromise.then(() => next(), err => next(err));
  423. }
  424. }
  425. function isPromise(v) {
  426. return v != null && typeof v.then === 'function';
  427. }
  428. function decorateNextFn(fn) {
  429. var called = false;
  430. var _this = this;
  431. return function() {
  432. // Ensure this function can only be called once
  433. if (called) {
  434. return;
  435. }
  436. called = true;
  437. // Make sure to clear the stack so try/catch doesn't catch errors
  438. // in subsequent middleware
  439. return process.nextTick(() => fn.apply(_this, arguments));
  440. };
  441. }
  442. module.exports = Kareem;