Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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