applyQueryMiddleware.js 2.0 KB

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