Last active
August 15, 2024 10:17
-
-
Save ErickWendel/011593103c117c589fe209cf59cf3db7 to your computer and use it in GitHub Desktop.
Example of how to consume multiple Web APIs in parallel via Node.js Streams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// npm i axios stream-concat | |
import { pipeline } from 'stream/promises' | |
import StreamConcat from 'stream-concat' | |
import axios from 'axios' | |
const API_01 = 'http://localhost:3000' | |
const API_02 = 'http://localhost:4000' | |
const streams = (await Promise.all([ | |
axios({ | |
method: 'get', | |
url: API_01, | |
responseType: 'stream' | |
}), | |
axios({ | |
method: 'get', | |
url: API_02, | |
responseType: 'stream' | |
}) | |
])).map(({ data }) => data) | |
const stream = new StreamConcat(streams) | |
await pipeline( | |
stream, | |
async function* output(stream) { | |
stream.setEncoding('utf8') | |
for await (const data of stream) { | |
console.log(data) | |
} | |
} | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import http from 'http' | |
import { Readable } from 'stream' | |
import { pipeline } from 'stream/promises' | |
const handler = (apiName) => async function (request, response) { | |
let count = 0; | |
const maxItems = 99 | |
const readable = Readable({ | |
read() { | |
const everySecond = (intervalContext) => () => { | |
if (count++ <= maxItems) { | |
this.push(JSON.stringify({ id: Date.now() + count, name: `Erick-${count}`, apiName }) + "\n") | |
return; | |
} | |
clearInterval(intervalContext) | |
this.push(null) | |
} | |
setInterval(everySecond(this)) | |
}, | |
}) | |
await pipeline(readable, response) | |
} | |
http.createServer(handler('api01')).listen(3000, () => console.log('server running at 3000')) | |
http.createServer(handler('api02')).listen(4000, () => console.log('server running at 4000')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment