2022-10-31 15:07:56 +00:00
|
|
|
import type { MiddlewareHandler } from '../../types.ts'
|
2022-07-16 01:26:14 +00:00
|
|
|
|
2023-08-18 07:14:58 +00:00
|
|
|
const ENCODING_TYPES = ['gzip', 'deflate'] as const
|
2022-07-16 23:59:40 +00:00
|
|
|
|
2022-07-16 01:26:14 +00:00
|
|
|
interface CompressionOptions {
|
2023-08-18 07:14:58 +00:00
|
|
|
encoding?: typeof ENCODING_TYPES[number]
|
2022-07-16 01:26:14 +00:00
|
|
|
}
|
|
|
|
|
2022-09-13 23:17:20 +00:00
|
|
|
export const compress = (options?: CompressionOptions): MiddlewareHandler => {
|
|
|
|
return async (ctx, next) => {
|
2022-07-16 01:26:14 +00:00
|
|
|
await next()
|
|
|
|
const accepted = ctx.req.headers.get('Accept-Encoding')
|
2023-08-18 07:14:58 +00:00
|
|
|
const encoding =
|
|
|
|
options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))
|
|
|
|
if (!encoding || !ctx.res.body) {
|
2022-07-16 23:59:40 +00:00
|
|
|
return
|
2022-07-16 01:26:14 +00:00
|
|
|
}
|
2022-11-22 22:27:42 +00:00
|
|
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
|
|
|
// @ts-ignore
|
2023-08-18 07:14:58 +00:00
|
|
|
const stream = new CompressionStream(encoding)
|
2022-10-09 14:33:00 +00:00
|
|
|
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)
|
2023-08-23 00:11:37 +00:00
|
|
|
ctx.res.headers.delete('Content-Length')
|
2022-07-16 01:26:14 +00:00
|
|
|
ctx.res.headers.set('Content-Encoding', encoding)
|
|
|
|
}
|
2022-07-16 23:59:40 +00:00
|
|
|
}
|