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 1eb49b8d96
refactor: support new @cloudflare/worker-types (#673)
* refactor: support new `@cloudflare/worker-types`

* do not attach crypto to global

* denoify ignore serve-static for cloudlfare

* ignore the utility for cloudflare

* import types
2022-11-23 07:27:42 +09:00

26 lines
822 B
TypeScript

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