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
Yusuke Wada d678c75808
fix(compress): delete content-length header (#1366)
* fix(compress): delete `content-length` header

* denoify
2023-08-23 09:11:37 +09:00

26 lines
854 B
TypeScript

import type { MiddlewareHandler } from '../../types.ts'
const ENCODING_TYPES = ['gzip', 'deflate'] as const
interface CompressionOptions {
encoding?: typeof ENCODING_TYPES[number]
}
export const compress = (options?: CompressionOptions): MiddlewareHandler => {
return async (ctx, next) => {
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
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const stream = new CompressionStream(encoding)
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)
ctx.res.headers.delete('Content-Length')
ctx.res.headers.set('Content-Encoding', encoding)
}
}