ParsedDeps.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. "use strict";
  2. /**
  3. * This class is designed to quickly extract the needed fields into a Document.
  4. * It should only be created by a call to DepsTracker.toParsedDeps.
  5. *
  6. * @class ParsedDeps
  7. * @namespace mungedb-aggregate.pipeline
  8. * @module mungedb-aggregate
  9. * @constructor
  10. * @param {Object} fields The fields needed in a Document
  11. */
  12. var ParsedDeps = module.exports = function ParsedDeps(fields) {
  13. this._fields = fields;
  14. }, klass = ParsedDeps, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  15. /**
  16. * Extracts fields from the input into a new Document, based on the caller.
  17. *
  18. * @method extractFields
  19. * @param {Object} input The JSON object to extract from
  20. * @return {Document}
  21. */
  22. proto.extractFields = function extractFields(input) {
  23. return proto._documentHelper(input, this._fields);
  24. };
  25. /**
  26. * Private: Handles array-type values for extractFields()
  27. *
  28. * @method _arrayHelper
  29. * @param {Object} array Array to iterate over
  30. * @param {Object} neededFields
  31. * @return {Array}
  32. */
  33. proto._arrayHelper = function _arrayHelper(array, neededFields) {
  34. var values = [];
  35. array.sort().forEach(function (it) {
  36. if (it instanceof Array)
  37. values.push(_arrayHelper(it, neededFields));
  38. else if (it instanceof Object)
  39. values.push(proto._documentHelper(it, neededFields));
  40. });
  41. return values;
  42. };
  43. /**
  44. * Private: Handles object-type values for extractFields()
  45. *
  46. * @method _documentHelper
  47. * @param {Object} json Object to iterate over and filter
  48. * @param {Object} neededFields Fields to not exclude
  49. * @return {Document}
  50. */
  51. proto._documentHelper = function _documentHelper(json, neededFields) {
  52. var doc = {};
  53. Object.keys(json).sort().forEach(function (it) {
  54. var jsonElement = json[it],
  55. isNeeded = neededFields[it];
  56. if (!isNeeded)
  57. return;
  58. if (typeof(isNeeded) === 'boolean') {
  59. doc[it] = jsonElement;
  60. return;
  61. }
  62. if (typeof(isNeeded) === 'object') {
  63. if (jsonElement instanceof Array)
  64. doc[it] = proto._arrayHelper(jsonElement, isNeeded);
  65. if (jsonElement instanceof Object)
  66. doc[it] = proto._documentHelper(jsonElement, isNeeded);
  67. }
  68. });
  69. return doc;
  70. };