Compress ミドルウェア
このミドルウェアは、Accept-Encoding リクエストヘッダーに応じてレスポンスボディを圧縮します。
情報
注意:Cloudflare Workers と Deno Deploy はレスポンスボディを自動圧縮するため、このミドルウェアは不要です。
インポート
ts
import { Hono } from 'hono'
import { compress } from 'hono/compress'使い方
ts
const app = new Hono()
app.use(compress())オプション
optional encoding: 'gzip' | 'deflate'
レスポンス圧縮に許可する方式で、gzip または deflate です。未指定なら両方を許可し、Accept-Encoding ヘッダーに基づいて選択します。このオプションが未指定で、クライアントが Accept-Encoding に両方を指定した場合は gzip を優先します。
optional threshold: number
圧縮対象とする最小サイズ(バイト単位)。デフォルトは 1024 バイトです。
optional contentTypeFilter: RegExp | (contentType: string) => boolean
レスポンスの Content-Type に基づき圧縮するか判断する RegExp または関数です。デフォルトでは、圧縮可能な Content-Type の組み込みリストを使います。
RegExp を渡して、一致する Content-Type だけを圧縮できます。
ts
// Compress only JSON responses
app.use(compress({ contentTypeFilter: /^application\/json/ }))関数を渡して独自のロジックを使うこともできます。組み込みの COMPRESSIBLE_CONTENT_TYPE_REGEX もエクスポートされており、デフォルト動作を拡張できます。
ts
import {
compress,
COMPRESSIBLE_CONTENT_TYPE_REGEX,
} from 'hono/compress'
// Compress the default Content-Types plus a custom one
app.use(
compress({
contentTypeFilter: (type) =>
COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type) ||
type === 'application/x-myformat',
})
)