-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
51 lines (45 loc) · 1.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
const { PassThrough } = require('stream')
module.exports = (options = {}) => {
const before = options.before || '[\n'
const after = options.after || '\n]'
const separator = options.separator || '\n,\n'
const pretty = options.pretty || false
const spaces = pretty ? options.spaces || 2 : 0
const formatError = options.formatError || ((err) => ({
error: {
message: err.message,
}
}))
return async (ctx, next) => {
await next()
if (ctx.body !== ctx.body?.[Symbol.asyncIterator]?.()) return
const iterator = ctx.body
ctx.response.type = 'json'
const stream =
ctx.response.body = new PassThrough()
stream.write(before)
;(async () => {
let first = true
try {
for await (const value of iterator) {
if (!value) continue
if (first) {
first = false
} else {
stream.write(separator)
}
stream.write(JSON.stringify(value, null, spaces))
}
} catch (err) {
if (!first) {
stream.write(separator)
}
stream.write(JSON.stringify(formatError(err), null, spaces))
ctx.app.emit('error', err, ctx)
} finally {
stream.write(after)
stream.end()
}
})()
}
}