all files / lib/offshore/query/ stream.js

100% Statements 14/14
100% Branches 0/0
100% Functions 2/2
100% Lines 14/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49                                                                     
/**
 * Streaming Queries
 */
 
var usageError = require('../utils/usageError');
var utils = require('../utils/helpers');
var normalize = require('../utils/normalize');
var ModelStream = require('../utils/stream');
 
module.exports = {
 
  /**
   * Stream a Result Set
   *
   * @param {Object} criteria
   * @param {Object} transformation, defaults to JSON
   */
 
  stream: function(criteria, transformation, metaContainer) {
    var self = this;
 
    var usage = utils.capitalize(this.identity) + '.stream([criteria],[options])';
 
    // Normalize criteria and fold in options
    criteria = normalize.criteria(criteria);
 
    // Transform Search Criteria
    criteria = self._transformer.serialize(criteria);
 
    // Configure stream to adapter, kick off fetch, and return stream object
    // so that user code can use it as it fires data events
    var stream = new ModelStream(transformation);
 
    // very important to wait until next tick before triggering adapter
    // otherwise write() and end() won't fire properly
    process.nextTick(function() {
 
      // Write once immediately to force prefix in case no models are returned
      stream.write();
 
      // Trigger Adapter Method
      self.adapter.stream(criteria, stream, metaContainer);
    });
 
    return stream;
  }
 
};