node.js - 转换流中的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 请求并向块对象添加更多数据和将其传递给下一个转换流?
解决方案
您可以尝试如下所述更改您的代码吗?
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()
})
}
})
推荐阅读
- serilog - Serilog 将有效的 JSON 输出到文件
- wpf - Datagrid中图像的工具提示未显示
- c++ - parallel for loop in c++ using MPI
- java - 如何在 Java 中复制 ArrayList?
- wordpress - 具有多个关系和的 WordPress 大型查询
- c# - 制作 GAC 程序集以加载自定义程序集
- angularjs - bootstrap-ui-datetime-picker 未在输入字段中显示预选日期
- html - CSS中带有em单位的响应宽度
- regex - Replace \s with \s, (space + coma) between to strings in a text file
- github-desktop - How to "Open in Git Bash" in Github Desktop