0
0
mirror of https://github.com/honojs/hono.git synced 2024-12-01 10:51:01 +00:00
hono/deno_dist/middleware/compress/index.ts

26 lines
854 B
TypeScript
Raw Normal View History

import type { MiddlewareHandler } from '../../types.ts'
2022-07-16 01:26:14 +00:00
const ENCODING_TYPES = ['gzip', 'deflate'] as const
2022-07-16 01:26:14 +00:00
interface CompressionOptions {
encoding?: typeof ENCODING_TYPES[number]
2022-07-16 01:26:14 +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')
const encoding =
options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))
if (!encoding || !ctx.res.body) {
return
2022-07-16 01:26:14 +00:00
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const stream = new CompressionStream(encoding)
2022-10-09 14:33:00 +00:00
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)
ctx.res.headers.delete('Content-Length')
2022-07-16 01:26:14 +00:00
ctx.res.headers.set('Content-Encoding', encoding)
}
}