首页 > 解决方案 > 转换流中的http请求

问题描述

过去几个小时我一直在敲我的脑袋如何做到这一点,我从带有 superagent 的 api 获取一些 json 数据:

superagent.get(url)
            .set('x-rapidapi-host','v3.football.api-sports.io')
            .set('x-rapidapi-key',process.env.FOOTBALL_API_KEY)
            .pipe(JSONStream.parse('response.*')).pipe(oddStream).pipe(transfStream).pipe(JSONStream.stringify()).pipe(f1)

我使用 JSONStream 来解析它,并且必须使用 transformStreams 来聚合一些数据并将其作为 JSON 传输回文件流。问题出在oddStream中,我想获取游戏装置的ID并发出另一个http get请求以获取有关游戏的其他数据(以json形式返回)并将其添加到输出json中:

const oddStream = new Transform({
    objectMode : true,
    transform(chunk,encoding,cb){
        if(allowed(chunk.league.id)){
            const fixtureId = chunk.fixture.id;
            //Here I want to make another get request
            superagent.get(`https://v3.football.api-sports.io/odds?fixture=${fixtureId}&bookmaker=6`)
            .set('x-rapidapi-host','v3.football.api-sports.io')
            .set('x-rapidapi-key',process.env.FOOTBALL_API_KEY)
            .end((err,res) => {
                if(err){
                    console.log(err);
                }
                const odds = res.body.response[0];
                //?????????? Attach the data to the chunk object
                chunk.odds = odds;
                //Push it no the next transform stream
                this.push(chunk);
            })
        }
        cb();
    }
    
});

另一个转换流工作正常,我什至不会打扰显示代码。问题出在第二个转换流中,任何建议我如何在转换方法中发出 http 请求并向块对象添加更多数据和将其传递给下一个转换流?

标签: node.jsnodejs-stream

解决方案


您可以尝试如下所述更改您的代码吗?

const oddStream = new Transform({
objectMode: true,
transform(chunk, encoding, cb) {
    if (!allowed(chunk.league.id)) {
        return cb()
    }
    const fixtureId = chunk.fixture.id;
    //Here I want to make another get request
    superagent.get(`https://v3.football.api-sports.io/odds?fixture=${fixtureId}&bookmaker=6`)
        .set('x-rapidapi-host', 'v3.football.api-sports.io')
        .set('x-rapidapi-key', process.env.FOOTBALL_API_KEY)
        .end((err, res) => {
            if (err) {
                console.log(err);
            }
            const odds = res.body.response[0];
            //?????????? Attach the data to the chunk object
            chunk.odds = odds;
            //Push it no the next transform stream
            this.push(chunk);
            //callback from here
            return cb()
        })
 }
})

推荐阅读