Skip to content

Instantly share code, notes, and snippets.

@zavr-1
Last active December 26, 2019 12:52
Show Gist options
  • Save zavr-1/6e719745abf76560d1d4ab738422e532 to your computer and use it in GitHub Desktop.
Save zavr-1/6e719745abf76560d1d4ab738422e532 to your computer and use it in GitHub Desktop.
/* original */
// threshold
if (threshold && ctx.response.length < threshold) return
/* fork */
// threshold
if (threshold) {
if (ctx.body instanceof Readable) {
const st = /** @type {!stream.Readable} */ (ctx.body)
let totalLength = 0
let resolved = false
let error
const { newStream, callback } = await new Promise((re, j) => {
const r = new Transform(/** @type {!stream.TransformOptions} */({
transform(data, enc, cb) {
this.push(data)
if (resolved) {
cb()
return
}
totalLength += data.length
if (totalLength > threshold) {
resolved = true
re({ newStream: this, callback: cb })
} else cb()
},
}))
r.once('finish', () => re({ newStream: r }))
st.once('error', (err) => {
error = err
re({})
})
r.once('error', j)
st.pipe(r)
r.pause()
})
if (error) return // handled by Koa
body = newStream
body.resume()
if (!callback) {
ctx.body = body
return
}
callback()
} else if (ctx.response.length < threshold) return
}
/* common end of middleware */
ctx.set('Content-Encoding', encoding)
ctx.res.removeHeader('Content-Length')
const stream = ctx.body = encodingMethods[encoding](options)
if (body instanceof Stream) {
body.pipe(stream)
} else {
stream.end(body)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment