Cursor.js 2.0 KB

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