Koa JSON response body streaming for async iterators
const jsonAsyncIterator = require('@koa/json-async-iterator') const app = new Koa() app.use(jsonAsyncIterator()) app.use(async ctx => { const iterator = async function* () { yield Promise.resolve({ foo: 'bar' }) yield Promise.resolve({ baz: 'qux' }) } ctx.body = iterator() })
Output:
[ {"foo":"bar"} , {"baz":"qux"} ]
Example with PostgreSQL:
import QueryStream from 'pg-query-stream' import pg from 'pg' const client = new pg.Client() await client.connect() // later in your middleware app.use(async (ctx) => { // stream all the rows from the database to the client ctx.body = client.query(new QueryStream(` SELECT * FROM posts ORDER BY id ASC `)) })
The string to write before the first value in the iterator.
Default: '[\n'
The string to write between each value in the iterator.
Default: '\n,\n'
The string to write after the last value in the iterator.
Default: '\n]'
A function that takes an error and returns a value to be stringified.
Default: (err) => ({ error: { message: err.message } })
Whether to pretty-print the JSON.
Default: false
The number of spaces to use for pretty-printing.
Default: 2
MIT
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4