【问题标题】:How to create a stream of objects from remote JSON array via highland?如何通过高地从远程 JSON 数组创建对象流?
【发布时间】:2016-12-11 14:34:15
【问题描述】:

通过以下方式从 URL http://foo.bar/overview 获取 JSON:

const request = request.get('http://foo.bar/overview');

生成包含对象数组的 JSON 响应:

[
    {
        id: 1,
        narf: 'foo',
        poit: 'bar',
    },
    {
        id: 2,
        narf: 'fizz',
        poit: 'buzz',
    },
]

我现在正在尝试设置一个包含数组的每个对象的高地流。然而,我似乎只能从请求的整个响应中构建它,这似乎首先会适得其反。

我的第一个天真的解决方案是通过以下方式构建它:

let body: [];
request.on('data', (chunk: any) => {
    body.push(chunk);
}).on('end', () => {
    const responseData = JSON.parse(Buffer.concat(body).toString());
    _(responseData) // now I have the stream
});

四处挖掘我还意识到 highland 支持从请求对象本身设置流:

_(request).map((bufferedResponse: Buffer) => {
    const overview = <Overview[]> JSON.parse(bufferedResponse.toString()); // again this is the entire respone already
    return _(overview); // now I have the stream
});

如何在不使用存储在内存中的整个响应的情况下从远程 JSON 动态创建一个对象数组流?

【问题讨论】:

    标签: javascript arrays typescript stream highland.js


    【解决方案1】:

    我正在尝试oboejs,可以通过以下方式用它构建高地溪流:

    import * as _ from 'highland';
    import oboe = require('oboe');
    
    const idStream = _((push: any, next: any) => {
        oboe({
            url: 'http://foo.bar/overview',
            method: 'GET',
            headers: {
                'X-Token': token,
            },
        }).node('{id narf poit}', (overview) => {
            push(null, overview.id);
            return oboe.drop;
        }).done((response) => {
            // without drop, the entire response would now be stored here       
            push(null, _.nil);
        }).fail((reason) => {
            console.error(reason);
            push(null, _.nil);
        });
    });
    
    idStream.each((id: number) => {
        console.log(id);
    });
    

    打印:

    1
    2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 2020-07-11
      • 1970-01-01
      相关资源
      最近更新 更多