applyStaticHooks.js 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. 'use strict';
  2. const { queryMiddlewareFunctions, aggregateMiddlewareFunctions, modelMiddlewareFunctions, documentMiddlewareFunctions } = require('../../constants');
  3. const middlewareFunctions = Array.from(
  4. new Set([
  5. ...queryMiddlewareFunctions,
  6. ...aggregateMiddlewareFunctions,
  7. ...modelMiddlewareFunctions,
  8. ...documentMiddlewareFunctions
  9. ])
  10. );
  11. module.exports = function applyStaticHooks(model, hooks, statics) {
  12. hooks = hooks.filter(hook => {
  13. // If the custom static overwrites an existing middleware, don't apply
  14. // middleware to it by default. This avoids a potential backwards breaking
  15. // change with plugins like `mongoose-delete` that use statics to overwrite
  16. // built-in Mongoose functions.
  17. if (middlewareFunctions.indexOf(hook.name) !== -1) {
  18. return !!hook.model;
  19. }
  20. return hook.model !== false;
  21. });
  22. for (const key of Object.keys(statics)) {
  23. if (hooks.hasHooks(key)) {
  24. const original = model[key];
  25. model[key] = hooks.createWrapper(key, original);
  26. }
  27. }
  28. };