selectPopulatedFields.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const isExclusive = require('../projection/isExclusive');
  3. const isInclusive = require('../projection/isInclusive');
  4. /*!
  5. * ignore
  6. */
  7. module.exports = function selectPopulatedFields(fields, userProvidedFields, populateOptions) {
  8. if (populateOptions == null) {
  9. return;
  10. }
  11. const paths = Object.keys(populateOptions);
  12. userProvidedFields = userProvidedFields || {};
  13. if (isInclusive(fields)) {
  14. for (const path of paths) {
  15. if (!isPathInFields(userProvidedFields, path)) {
  16. fields[path] = 1;
  17. } else if (userProvidedFields[path] === 0) {
  18. delete fields[path];
  19. }
  20. const refPath = populateOptions[path]?.refPath;
  21. if (typeof refPath === 'string') {
  22. if (!isPathInFields(userProvidedFields, refPath)) {
  23. fields[refPath] = 1;
  24. } else if (userProvidedFields[refPath] === 0) {
  25. delete fields[refPath];
  26. }
  27. }
  28. }
  29. } else if (isExclusive(fields)) {
  30. for (const path of paths) {
  31. if (userProvidedFields[path] == null) {
  32. delete fields[path];
  33. }
  34. const refPath = populateOptions[path]?.refPath;
  35. if (typeof refPath === 'string' && userProvidedFields[refPath] == null) {
  36. delete fields[refPath];
  37. }
  38. }
  39. }
  40. };
  41. /*!
  42. * ignore
  43. */
  44. function isPathInFields(userProvidedFields, path) {
  45. const pieces = path.split('.');
  46. const len = pieces.length;
  47. let cur = pieces[0];
  48. for (let i = 1; i < len; ++i) {
  49. if (userProvidedFields[cur] != null || userProvidedFields[cur + '.$'] != null) {
  50. return true;
  51. }
  52. cur += '.' + pieces[i];
  53. }
  54. return userProvidedFields[cur] != null || userProvidedFields[cur + '.$'] != null;
  55. }