mirror of
https://github.com/honojs/hono.git
synced 2024-12-01 10:51:01 +00:00
1eb49b8d96
* 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
26 lines
822 B
TypeScript
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)
|
|
}
|
|
}
|