我正在尝试使用nock对针对Oanda交易API编写的代码运行回测。为此,我需要模拟流媒体价格API(参见http://developer.oanda.com/rest-practice/streaming/上的rate streaming)。然而,nock似乎只允许您使用单个回复进行响应,即使响应是流。是否有办法发送数以千计的价格事件流作为单个请求的单独响应?
var scopeStream = nock('https://stream-fxpractice.oanda.com')
.persist()
.filteringPath(function(path) {
return '/stream';
})
.get('/stream')
.reply(function(uri, requestBody) {
return [200, {"tick":{"instrument":"AUD_CAD","time":"2014-01-30T20:47:08.066398Z","bid":0.98114,"ask":0.98139}}]
})
根据Nock文档,你可以在回复中返回一个ReadStream。
我使用stream-spigot npm包生成了以下示例(用于模拟马拉松赛事流):
const nock = require('nock');
const EventSource = require('eventsource');
const spigot = require('stream-spigot');
let i = 0;
nock('http://marathon.com')
.get('/events')
.reply(200, (uri, req) => {
// reply with a stream
return spigot({objectMode: true}, function() {
const self = this;
if (++i < 5)
setTimeout(() => this.push(`id: ${i}ndata: foonn`), 1000);
})
});
const es = new EventSource('http://marathon.com/events');
es.onmessage = m => console.log(m);
es.onerror = e => console.log(e);