Cursor.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. "use strict";
  2. var Cursor = module.exports = (function(){
  3. // CONSTRUCTOR
  4. /**
  5. * This class is the munge equivalent version of the mongo cursor. Not everything is implemented
  6. * since we only need bits and pieces of their functionality, but the methods that exist
  7. * should be have the same as they do in mongo.
  8. *
  9. * stream-utils.throughStream should eventually be supported, but for now it will probably break things (so dont use it)
  10. *
  11. * @param {Array} throughStreamOrArray The array source of the data
  12. **/
  13. var klass = function Cursor(throughStreamOrArray){
  14. var self = this;
  15. if (!throughStreamOrArray){
  16. throw new Error("Cursor requires a stream-utils.ThroughStream or Array object.");
  17. }
  18. if (throughStreamOrArray.constructor === su.ThroughStream){
  19. this.throughStream = throughStreamOrArray;
  20. this.cachedData = [];
  21. throughStreamOrArray.on('data', function(data){
  22. self.cachedData.push(data);
  23. });
  24. } else if (throughStreamOrArray.constructor === Array){
  25. this.cachedData = throughStreamOrArray.slice(0);
  26. } else {
  27. throw new Error("Cursor requires a stream-utils.ThroughStream or Array object.");
  28. }
  29. }, base = Object, proto = klass.prototype = Object.create(base.prototype, {constructor:{value:klass}});
  30. var su = require("stream-utils");
  31. proto.ok = function ok(){
  32. if (this.throughStream && this.throughStream.readable){
  33. return true;
  34. }
  35. return this.cachedData.length > 0 || this.hasOwnProperty("curr");
  36. };
  37. proto.advance = function advance(){
  38. if (this.cachedData.length === 0){
  39. delete this.curr;
  40. return false;
  41. }
  42. this.curr = this.cachedData.splice(0,1)[0];
  43. //TODO: CHANGE ME!!!!!
  44. //Note: !!BLOCKING CODE!! need to coerce our async stream of objects into a synchronous cursor to mesh with mongos c++ish code
  45. while (!this.curr && this.throughStream && this.throughStream.readable){
  46. this.curr = this.cachedData.splice(0,1)[0];
  47. }
  48. return this.curr;
  49. };
  50. proto.current = function current(){
  51. if (!this.hasOwnProperty("curr")){
  52. this.advance();
  53. }
  54. return this.curr;
  55. };
  56. return klass;
  57. })();