ParsedDeps.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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} json Object to iterate over
  30. * @param {Object} neededFields
  31. * @return {Array}
  32. */
  33. proto._arrayHelper = function _arrayHelper(json, neededFields) {
  34. var iterator = json instanceof Array? json : Object.keys(json),
  35. values = [];
  36. iterator.sort().forEach(function (it) {
  37. if (it instanceof Array)
  38. values.push(_arrayHelper(it, neededFields));
  39. else if (it instanceof Object)
  40. values.push(proto._documentHelper(it, neededFields));
  41. });
  42. return values;
  43. };
  44. /**
  45. * Private: Handles object-type values for extractFields()
  46. *
  47. * @method _documentHelper
  48. * @param {Object} json Object to iterate over and filter
  49. * @param {Object} neededFields Fields to not exclude
  50. * @return {Document}
  51. */
  52. proto._documentHelper = function _documentHelper(json, neededFields) {
  53. var doc = {};
  54. Object.keys(json).sort().forEach(function (it) {
  55. var jsonElement = json[it],
  56. isNeeded = neededFields[it];
  57. if (!isNeeded)
  58. return;
  59. if (typeof(isNeeded) === 'boolean') {
  60. doc[it] = jsonElement;
  61. return;
  62. }
  63. if (typeof(isNeeded) === 'object') {
  64. if (jsonElement instanceof Array)
  65. doc[it] = proto._arrayHelper(jsonElement, isNeeded);
  66. if (jsonElement instanceof Object)
  67. doc[it] = proto._documentHelper(jsonElement, isNeeded);
  68. }
  69. });
  70. return doc;
  71. };