Ohm-Management - Projektarbeit B-ME
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

castArrayFilters.js 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. const castFilterPath = require('../query/castFilterPath');
  3. const modifiedPaths = require('./modifiedPaths');
  4. module.exports = function castArrayFilters(query) {
  5. const arrayFilters = query.options.arrayFilters;
  6. if (!Array.isArray(arrayFilters)) {
  7. return;
  8. }
  9. const update = query.getUpdate();
  10. const schema = query.schema;
  11. const updatedPaths = modifiedPaths(update);
  12. const updatedPathsByFilter = Object.keys(updatedPaths).reduce((cur, path) => {
  13. const matches = path.match(/\$\[[^\]]+\]/g);
  14. if (matches == null) {
  15. return cur;
  16. }
  17. for (const match of matches) {
  18. const firstMatch = path.indexOf(match);
  19. if (firstMatch !== path.lastIndexOf(match)) {
  20. throw new Error(`Path '${path}' contains the same array filter multiple times`);
  21. }
  22. cur[match.substring(2, match.length - 1)] = path.substr(0, firstMatch - 1);
  23. }
  24. return cur;
  25. }, {});
  26. for (const filter of arrayFilters) {
  27. if (filter == null) {
  28. throw new Error(`Got null array filter in ${arrayFilters}`);
  29. }
  30. const firstKey = Object.keys(filter)[0];
  31. if (filter[firstKey] == null) {
  32. continue;
  33. }
  34. const dot = firstKey.indexOf('.');
  35. let filterPath = dot === -1 ?
  36. updatedPathsByFilter[firstKey] + '.0' :
  37. updatedPathsByFilter[firstKey.substr(0, dot)] + '.0' + firstKey.substr(dot);
  38. if (filterPath == null) {
  39. throw new Error(`Filter path not found for ${firstKey}`);
  40. }
  41. // If there are multiple array filters in the path being updated, make sure
  42. // to replace them so we can get the schema path.
  43. filterPath = filterPath.replace(/\$\[[^\]]+\]/g, '0');
  44. const schematype = schema.path(filterPath);
  45. if (typeof filter[firstKey] === 'object') {
  46. filter[firstKey] = castFilterPath(query, schematype, filter[firstKey]);
  47. } else {
  48. filter[firstKey] = schematype.castForQuery(filter[firstKey]);
  49. }
  50. }
  51. };