ParsedDeps.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. var Value = require("./Value");
  16. /**
  17. * Extracts fields from the input into a new Document, based on the caller.
  18. *
  19. * @method extractFields
  20. * @param {Object} input The JSON object to extract from
  21. * @return {Document}
  22. */
  23. proto.extractFields = function extractFields(input) {
  24. return proto._documentHelper(input, this._fields);
  25. };
  26. /**
  27. * Private: Handles array-type values for extractFields()
  28. *
  29. * @method _arrayHelper
  30. * @param {Object} array Array to iterate over
  31. * @param {Object} neededFields
  32. * @return {Array}
  33. */
  34. proto._arrayHelper = function _arrayHelper(array, neededFields) {
  35. var values = [];
  36. for (var it in array) {
  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. for (var fieldName in json) {
  55. var jsonElement = json[fieldName],
  56. isNeeded = neededFields[fieldName];
  57. if (isNeeded === undefined)
  58. continue;
  59. if (Value.getType(isNeeded) === 'boolean') {
  60. doc[fieldName] = jsonElement;
  61. continue;
  62. }
  63. if (!isNeeded instanceof Object) throw new Error("dassert failure");
  64. if (Value.getType(isNeeded) === 'object') {
  65. if (jsonElement instanceof Array)
  66. doc[fieldName] = proto._arrayHelper(jsonElement, isNeeded);
  67. if (jsonElement instanceof Object)
  68. doc[fieldName] = proto._documentHelper(jsonElement, isNeeded);
  69. }
  70. }
  71. return doc;
  72. };