Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 0210b38

Browse files
committed
Improve API request compression
1 parent 9ea6cec commit 0210b38

File tree

1 file changed

+15
-5
lines changed

1 file changed

+15
-5
lines changed

server/api.ts

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
import type { BufReader, BufWriter } from 'https://deno.land/[email protected]/io/bufio.ts'
22
import type { MultipartFormData } from 'https://deno.land/[email protected]/mime/multipart.ts'
33
import { MultipartReader } from 'https://deno.land/[email protected]/mime/multipart.ts'
4-
import { compress as brotli } from 'https://deno.land/x/[email protected]/mod.ts'
5-
import { gzipEncode as gzip } from 'https://deno.land/x/[email protected]/mod.ts'
64
import log from '../shared/log.ts'
75
import type { APIRequest, ServerRequest, ServerResponse } from '../types.ts'
86

7+
let brotli: ((data: Uint8Array) => Uint8Array) | null = null
8+
let gzip: ((data: Uint8Array) => Uint8Array) | null = null
9+
910
export class Request implements APIRequest {
1011
#req: ServerRequest
1112
#params: URLSearchParams
@@ -150,14 +151,23 @@ export class Request implements APIRequest {
150151
shouldCompress = true
151152
}
152153
}
153-
if (shouldCompress && body.length > 1024) {
154-
if (this.headers.get('accept-encoding')?.includes('br')) {
154+
if (shouldCompress && Deno.env.get('ALEPH_BUILD_MODE') !== 'development' && body.length > 1024) {
155+
const ae = this.headers.get('accept-encoding') || ''
156+
if (ae.includes('br')) {
155157
this.#resp.headers.set('Vary', 'Origin')
156158
this.#resp.headers.set('Content-Encoding', 'br')
159+
if (brotli === null) {
160+
const { compress } = await import('https://deno.land/x/[email protected]/mod.ts')
161+
brotli = compress
162+
}
157163
body = brotli(body)
158-
} else if (this.headers.get('accept-encoding')?.includes('gzip')) {
164+
} else if (ae.includes('gzip')) {
159165
this.#resp.headers.set('Vary', 'Origin')
160166
this.#resp.headers.set('Content-Encoding', 'gzip')
167+
if (gzip === null) {
168+
const { gzipEncode } = await import('https://deno.land/x/[email protected]/mod.ts')
169+
gzip = gzipEncode
170+
}
161171
body = gzip(body)
162172
}
163173
}

0 commit comments

Comments
 (0)