applyHooks.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. 'use strict';
  2. const symbols = require('../../schema/symbols');
  3. const utils = require('../../utils');
  4. /*!
  5. * ignore
  6. */
  7. module.exports = applyHooks;
  8. /*!
  9. * ignore
  10. */
  11. applyHooks.middlewareFunctions = [
  12. 'deleteOne',
  13. 'save',
  14. 'validate',
  15. 'remove',
  16. 'updateOne',
  17. 'init'
  18. ];
  19. /*!
  20. * Register hooks for this model
  21. *
  22. * @param {Model} model
  23. * @param {Schema} schema
  24. */
  25. function applyHooks(model, schema, options) {
  26. options = options || {};
  27. const kareemOptions = {
  28. useErrorHandlers: true,
  29. numCallbackParams: 1,
  30. nullResultByDefault: true,
  31. contextParameter: true
  32. };
  33. const objToDecorate = options.decorateDoc ? model : model.prototype;
  34. model.$appliedHooks = true;
  35. for (const key of Object.keys(schema.paths)) {
  36. const type = schema.paths[key];
  37. let childModel = null;
  38. if (type.$isSingleNested) {
  39. childModel = type.caster;
  40. } else if (type.$isMongooseDocumentArray) {
  41. childModel = type.Constructor;
  42. } else {
  43. continue;
  44. }
  45. if (childModel.$appliedHooks) {
  46. continue;
  47. }
  48. applyHooks(childModel, type.schema, options);
  49. if (childModel.discriminators != null) {
  50. const keys = Object.keys(childModel.discriminators);
  51. for (let j = 0; j < keys.length; ++j) {
  52. applyHooks(childModel.discriminators[keys[j]],
  53. childModel.discriminators[keys[j]].schema, options);
  54. }
  55. }
  56. }
  57. // Built-in hooks rely on hooking internal functions in order to support
  58. // promises and make it so that `doc.save.toString()` provides meaningful
  59. // information.
  60. const middleware = schema.s.hooks.
  61. filter(hook => {
  62. if (hook.name === 'updateOne' || hook.name === 'deleteOne') {
  63. return !!hook['document'];
  64. }
  65. if (hook.name === 'remove') {
  66. return hook['document'] == null || !!hook['document'];
  67. }
  68. return true;
  69. }).
  70. filter(hook => {
  71. // If user has overwritten the method, don't apply built-in middleware
  72. if (schema.methods[hook.name]) {
  73. return !hook.fn[symbols.builtInMiddleware];
  74. }
  75. return true;
  76. });
  77. model._middleware = middleware;
  78. objToDecorate.$__save = middleware.
  79. createWrapper('save', objToDecorate.$__save, null, kareemOptions);
  80. objToDecorate.$__validate = middleware.
  81. createWrapper('validate', objToDecorate.$__validate, null, kareemOptions);
  82. objToDecorate.$__remove = middleware.
  83. createWrapper('remove', objToDecorate.$__remove, null, kareemOptions);
  84. objToDecorate.$__deleteOne = middleware.
  85. createWrapper('deleteOne', objToDecorate.$__deleteOne, null, kareemOptions);
  86. objToDecorate.$__init = middleware.
  87. createWrapperSync('init', objToDecorate.$__init, null, kareemOptions);
  88. // Support hooks for custom methods
  89. const customMethods = Object.keys(schema.methods);
  90. const customMethodOptions = Object.assign({}, kareemOptions, {
  91. // Only use `checkForPromise` for custom methods, because mongoose
  92. // query thunks are not as consistent as I would like about returning
  93. // a nullish value rather than the query. If a query thunk returns
  94. // a query, `checkForPromise` causes infinite recursion
  95. checkForPromise: true
  96. });
  97. for (const method of customMethods) {
  98. if (!middleware.hasHooks(method)) {
  99. // Don't wrap if there are no hooks for the custom method to avoid
  100. // surprises. Also, `createWrapper()` enforces consistent async,
  101. // so wrapping a sync method would break it.
  102. continue;
  103. }
  104. const originalMethod = objToDecorate[method];
  105. objToDecorate[method] = function() {
  106. const args = Array.prototype.slice.call(arguments);
  107. const cb = utils.last(args);
  108. const argsWithoutCallback = typeof cb === 'function' ?
  109. args.slice(0, args.length - 1) : args;
  110. return utils.promiseOrCallback(cb, callback => {
  111. return this[`$__${method}`].apply(this,
  112. argsWithoutCallback.concat([callback]));
  113. }, model.events);
  114. };
  115. objToDecorate[`$__${method}`] = middleware.
  116. createWrapper(method, originalMethod, null, customMethodOptions);
  117. }
  118. }