ParsedDeps.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 i = 0; i < array.length; i++) {
  37. var it = array[i];
  38. if (it instanceof Array)
  39. values.push(_arrayHelper(it, neededFields));
  40. else if (it instanceof Object)
  41. values.push(proto._documentHelper(it, neededFields));
  42. }
  43. return values;
  44. };
  45. /**
  46. * Private: Handles object-type values for extractFields()
  47. *
  48. * @method _documentHelper
  49. * @param {Object} json Object to iterate over and filter
  50. * @param {Object} neededFields Fields to not exclude
  51. * @return {Document}
  52. */
  53. proto._documentHelper = function _documentHelper(json, neededFields) {
  54. var doc = {};
  55. for (var fieldName in json) {
  56. var jsonElement = json[fieldName],
  57. isNeeded = neededFields[fieldName];
  58. if (isNeeded === undefined)
  59. continue;
  60. if (Value.getType(isNeeded) === 'boolean') {
  61. doc[fieldName] = jsonElement;
  62. continue;
  63. }
  64. if (!isNeeded instanceof Object) throw new Error("dassert failure");
  65. if (Value.getType(isNeeded) === 'object') {
  66. if (jsonElement instanceof Array)
  67. doc[fieldName] = proto._arrayHelper(jsonElement, isNeeded);
  68. if (jsonElement instanceof Object)
  69. doc[fieldName] = proto._documentHelper(jsonElement, isNeeded);
  70. }
  71. }
  72. return doc;
  73. };