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.

applyStaticHooks.js 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. 'use strict';
  2. const utils = require('../../utils');
  3. module.exports = function applyStaticHooks(model, hooks, statics) {
  4. const kareemOptions = {
  5. useErrorHandlers: true,
  6. numCallbackParams: 1
  7. };
  8. hooks = hooks.filter(hook => hook.model !== false);
  9. model.$__insertMany = hooks.createWrapper('insertMany',
  10. model.$__insertMany, model, kareemOptions);
  11. for (const key of Object.keys(statics)) {
  12. if (hooks.hasHooks(key)) {
  13. const original = model[key];
  14. model[key] = function() {
  15. const numArgs = arguments.length;
  16. const lastArg = numArgs > 0 ? arguments[numArgs - 1] : null;
  17. const cb = typeof lastArg === 'function' ? lastArg : null;
  18. const args = Array.prototype.slice.
  19. call(arguments, 0, cb == null ? numArgs : numArgs - 1);
  20. // Special case: can't use `Kareem#wrap()` because it doesn't currently
  21. // support wrapped functions that return a promise.
  22. return utils.promiseOrCallback(cb, callback => {
  23. hooks.execPre(key, model, args, function(err) {
  24. if (err != null) {
  25. return callback(err);
  26. }
  27. let postCalled = 0;
  28. const ret = original.apply(model, args.concat(post));
  29. if (ret != null && typeof ret.then === 'function') {
  30. ret.then(res => post(null, res), err => post(err));
  31. }
  32. function post(error, res) {
  33. if (postCalled++ > 0) {
  34. return;
  35. }
  36. if (error != null) {
  37. return callback(error);
  38. }
  39. hooks.execPost(key, model, [res], function(error) {
  40. if (error != null) {
  41. return callback(error);
  42. }
  43. callback(null, res);
  44. });
  45. }
  46. });
  47. }, model.events);
  48. };
  49. }
  50. }
  51. };