applyQueryMiddleware.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. 'use strict';
  2. /*!
  3. * ignore
  4. */
  5. module.exports = applyQueryMiddleware;
  6. /*!
  7. * ignore
  8. */
  9. applyQueryMiddleware.middlewareFunctions = [
  10. 'count',
  11. 'countDocuments',
  12. 'deleteMany',
  13. 'deleteOne',
  14. 'distinct',
  15. 'estimatedDocumentCount',
  16. 'find',
  17. 'findOne',
  18. 'findOneAndDelete',
  19. 'findOneAndRemove',
  20. 'findOneAndReplace',
  21. 'findOneAndUpdate',
  22. 'remove',
  23. 'replaceOne',
  24. 'update',
  25. 'updateMany',
  26. 'updateOne',
  27. 'validate'
  28. ];
  29. /*!
  30. * Apply query middleware
  31. *
  32. * @param {Query} query constructor
  33. * @param {Model} model
  34. */
  35. function applyQueryMiddleware(Query, model) {
  36. const kareemOptions = {
  37. useErrorHandlers: true,
  38. numCallbackParams: 1,
  39. nullResultByDefault: true
  40. };
  41. const middleware = model.hooks.filter(hook => {
  42. const contexts = _getContexts(hook);
  43. if (hook.name === 'updateOne') {
  44. return contexts.query == null || !!contexts.query;
  45. }
  46. if (hook.name === 'deleteOne') {
  47. return !!contexts.query || Object.keys(contexts).length === 0;
  48. }
  49. if (hook.name === 'validate' || hook.name === 'remove') {
  50. return !!contexts.query;
  51. }
  52. if (hook.query != null || hook.document != null) {
  53. return !!hook.query;
  54. }
  55. return true;
  56. });
  57. // `update()` thunk has a different name because `_update` was already taken
  58. Query.prototype._execUpdate = middleware.createWrapper('update',
  59. Query.prototype._execUpdate, null, kareemOptions);
  60. // `distinct()` thunk has a different name because `_distinct` was already taken
  61. Query.prototype.__distinct = middleware.createWrapper('distinct',
  62. Query.prototype.__distinct, null, kareemOptions);
  63. // `validate()` doesn't have a thunk because it doesn't execute a query.
  64. Query.prototype.validate = middleware.createWrapper('validate',
  65. Query.prototype.validate, null, kareemOptions);
  66. applyQueryMiddleware.middlewareFunctions.
  67. filter(v => v !== 'update' && v !== 'distinct' && v !== 'validate').
  68. forEach(fn => {
  69. Query.prototype[`_${fn}`] = middleware.createWrapper(fn,
  70. Query.prototype[`_${fn}`], null, kareemOptions);
  71. });
  72. }
  73. function _getContexts(hook) {
  74. const ret = {};
  75. if (hook.hasOwnProperty('query')) {
  76. ret.query = hook.query;
  77. }
  78. if (hook.hasOwnProperty('document')) {
  79. ret.document = hook.document;
  80. }
  81. return ret;
  82. }