DocumentSourceRunner.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. "use strict";
  2. var Runner = require("./Runner"),
  3. DocumentSource = require("../pipeline/documentSources/DocumentSource");
  4. /**
  5. * This class is a runner used to wrap a document source
  6. * @param {Array} items The array source of the data
  7. **/
  8. var klass = module.exports = function DocumentSourceRunner(docSrc, pipeline){
  9. base.call(this);
  10. if (!docSrc || !(docSrc instanceof DocumentSource)) throw new Error("DocumentSource runner requires a DocumentSource");
  11. if (!(pipeline instanceof Array)) throw new Error("DocumentSource runner requires pipeline to be an Array");
  12. this._docSrc = docSrc;
  13. this._pipeline = pipeline || [];
  14. while (this._pipeline.length && this._docSrc.coalesce(this._pipeline[0])) {
  15. this._pipeline.shift();
  16. }
  17. this._state = Runner.RunnerState.RUNNER_ADVANCED;
  18. }, base = Runner, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}}); //jshint ignore:line
  19. /**
  20. * Get the next result from the array.
  21. *
  22. * @method getNext
  23. * @param [callback] {Function}
  24. */
  25. proto.getNext = function getNext(callback) {
  26. var self = this;
  27. if (self._state === Runner.RunnerState.RUNNER_ADVANCED) {
  28. return self._docSrc.getNext(function (err, obj){
  29. if (err){
  30. self._state = Runner.RunnerState.RUNNER_ERROR;
  31. }
  32. if (obj === null){
  33. self._state = Runner.RunnerState.RUNNER_EOF;
  34. }
  35. return callback(err, obj, self._state);
  36. });
  37. }
  38. return callback(null, null, self._state);
  39. };
  40. /**
  41. * Save any state required to yield.
  42. *
  43. * @method saveState
  44. */
  45. proto.saveState = function saveState() {
  46. //nothing to do here
  47. };
  48. /**
  49. * Restore saved state, possibly after a yield. Return true if the runner is OK, false if
  50. * it was killed.
  51. *
  52. * @method restoreState
  53. */
  54. proto.restoreState = function restoreState() {
  55. //nothing to do here
  56. };
  57. /**
  58. * Returns a description of the Runner
  59. *
  60. * @method getInfo
  61. * @param [explain]
  62. * @param [planInfo]
  63. */
  64. proto.getInfo = function getInfo(explain) {
  65. if (explain){
  66. return {
  67. type: this.constructor.name,
  68. docSrc: this._docSrc.serialize(explain),
  69. state: this._state
  70. };
  71. }
  72. return undefined;
  73. };
  74. /**
  75. * dispose of the Runner.
  76. *
  77. * @method reset
  78. */
  79. proto.reset = function reset(){
  80. this._docSrc.dispose();
  81. this._state = Runner.RunnerState.RUNNER_DEAD;
  82. };