-
Notifications
You must be signed in to change notification settings - Fork 169
/
response.ts
91 lines (84 loc) · 2.45 KB
/
response.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
export type CacheControlOptions = {
maxAge?: number;
sMaxAge?: number;
public?: boolean;
private?: boolean;
immutable?: boolean;
mustRevalidate?: boolean;
};
export function content(
body: BodyInit,
init?: ResponseInit & {
contentType?: string;
cacheControl?: CacheControlOptions | "immutable" | "no-cache";
},
): Response {
const headers = new Headers(init?.headers);
const contentType = init?.contentType;
if (contentType) {
headers.set("Content-Type", contentType);
}
const cacheControl = init?.cacheControl;
if (cacheControl) {
if (cacheControl === "no-cache") {
headers.set("Cache-Control", "no-cache, no-store, must-revalidate");
} else if (cacheControl === "immutable") {
headers.set("Cache-Control", "public, max-age=31536000, immutable");
} else {
const { maxAge, sMaxAge, immutable, mustRevalidate } = cacheControl;
headers.set(
"Cache-Control",
[
cacheControl.public && "public",
cacheControl.private && "private",
maxAge && `max-age=${maxAge}`,
sMaxAge && `s-maxage=${sMaxAge}`,
immutable && "immutable",
mustRevalidate && "must-revalidate",
].filter(Boolean).join(", "),
);
}
}
return new Response(body, { ...init, headers });
}
export function json(data: unknown, init?: ResponseInit): Response {
const headers = new Headers(init?.headers);
headers.append("content-type", "application/json; charset=utf-8");
return new Response(JSON.stringify(data), { ...init, headers });
}
export type CookieOptions = {
expires?: number | Date;
maxAge?: number;
domain?: string;
path?: string;
httpOnly?: boolean;
secure?: boolean;
sameSite?: "lax" | "strict" | "none";
};
export function setCookieHeader(name: string, value: string, options?: CookieOptions): string {
const cookie = [`${name}=${value}`];
if (options) {
if (options.expires) {
cookie.push(`Expires=${new Date(options.expires).toUTCString()}`);
}
if (options.maxAge) {
cookie.push(`Max-Age=${options.maxAge}`);
}
if (options.domain) {
cookie.push(`Domain=${options.domain}`);
}
if (options.path) {
cookie.push(`Path=${options.path}`);
}
if (options.httpOnly) {
cookie.push("HttpOnly");
}
if (options.secure) {
cookie.push("Secure");
}
if (options.sameSite) {
cookie.push(`SameSite=${options.sameSite}`);
}
}
return cookie.join("; ");
}