2022-09-14 01:17:20 +02:00
|
|
|
import type { MiddlewareHandler } from '../../hono.ts'
|
2022-07-16 03:26:14 +02:00
|
|
|
|
2022-07-17 01:59:40 +02:00
|
|
|
type EncodingType = 'gzip' | 'deflate'
|
|
|
|
|
2022-07-16 03:26:14 +02:00
|
|
|
interface CompressionOptions {
|
2022-07-17 01:59:40 +02:00
|
|
|
encoding?: EncodingType
|
2022-07-16 03:26:14 +02:00
|
|
|
}
|
|
|
|
|
2022-09-14 01:17:20 +02:00
|
|
|
export const compress = (options?: CompressionOptions): MiddlewareHandler => {
|
|
|
|
return async (ctx, next) => {
|
2022-07-16 03:26:14 +02:00
|
|
|
await next()
|
|
|
|
const accepted = ctx.req.headers.get('Accept-Encoding')
|
|
|
|
const pattern = options?.encoding ?? /gzip|deflate/
|
|
|
|
const match = accepted?.match(pattern)
|
|
|
|
if (!accepted || !match || !ctx.res.body) {
|
2022-07-17 01:59:40 +02:00
|
|
|
return
|
2022-07-16 03:26:14 +02:00
|
|
|
}
|
|
|
|
const encoding = match[0]
|
2022-07-17 01:59:40 +02:00
|
|
|
const stream = new CompressionStream(encoding as EncodingType)
|
2022-10-09 16:33:00 +02:00
|
|
|
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)
|
2022-07-16 03:26:14 +02:00
|
|
|
ctx.res.headers.set('Content-Encoding', encoding)
|
|
|
|
}
|
2022-07-17 01:59:40 +02:00
|
|
|
}
|