0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-30 01:56:18 +01:00
hono/deno_dist/middleware/compress/index.ts

24 lines
737 B
TypeScript
Raw Normal View History

import type { MiddlewareHandler } from '../../hono.ts'
2022-07-16 03:26:14 +02:00
type EncodingType = 'gzip' | 'deflate'
2022-07-16 03:26:14 +02:00
interface CompressionOptions {
encoding?: EncodingType
2022-07-16 03:26:14 +02:00
}
export const compress = (options?: CompressionOptions): MiddlewareHandler => {
return async (ctx, next) => {
2022-07-16 03:26:14 +02:00
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
2022-07-16 03:26:14 +02:00
}
const encoding = match[0]
const stream = new CompressionStream(encoding as EncodingType)
2022-10-09 16:33:00 +02:00
ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res)
2022-07-16 03:26:14 +02:00
ctx.res.headers.set('Content-Encoding', encoding)
}
}