-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.ts
46 lines (38 loc) · 1.26 KB
/
transform.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Copyright 2023-latest the httpland authors. All rights reserved. MIT license.
// This module is browser compatible.
import {
CachingHeader,
compressible,
isNull,
parseMediaType,
RepresentationHeader,
} from "./deps.ts";
import { isNoTransform, reCalcContentLength } from "./utils.ts";
import type { Encoder } from "./types.ts";
/** Response with `Content-Encoding` header. */
export async function withContentEncoding(
response: Response,
context: Encoder,
): Promise<Response> {
const contentType = response.headers.get(RepresentationHeader.ContentType);
const cacheControl = response.headers.get(CachingHeader.CacheControl);
if (
isNull(contentType) ||
response.headers.has(RepresentationHeader.ContentEncoding) ||
!response.body ||
response.bodyUsed ||
(!isNull(cacheControl) && isNoTransform(cacheControl))
) return response;
const [mediaType] = parseMediaType(contentType);
const isCompressible = compressible(mediaType);
if (!isCompressible) return response;
const bodyInit = await context.encode(response.body);
const newResponse = await reCalcContentLength(
new Response(bodyInit, response),
);
newResponse.headers.set(
RepresentationHeader.ContentEncoding,
context.encoding,
);
return newResponse;
}