-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathresponse.ts
More file actions
50 lines (42 loc) · 1.56 KB
/
response.ts
File metadata and controls
50 lines (42 loc) · 1.56 KB
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
import type { RouterResponseInit, CustomResponse } from "../types.js";
export function redirect(url: string, init: number | RouterResponseInit = 302) {
let responseInit: ResponseInit;
let revalidate: string | string[] | undefined;
if (typeof init === "number") {
responseInit = { status: init };
} else {
({ revalidate, ...responseInit } = init);
if (typeof responseInit.status === "undefined") {
responseInit.status = 302;
}
}
const headers = new Headers(responseInit.headers);
headers.set("Location", url);
revalidate !== undefined && headers.set("X-Revalidate", revalidate.toString());
const response = new Response(null, {
...responseInit,
headers: headers
});
return response as CustomResponse<never>;
}
export function reload(init: RouterResponseInit = {}) {
const { revalidate, ...responseInit } = init;
const headers = new Headers(responseInit.headers);
revalidate !== undefined && headers.set("X-Revalidate", revalidate.toString());
return new Response(null, {
...responseInit,
headers
}) as CustomResponse<never>;
}
export function json<T>(data: T, init: RouterResponseInit = {}) {
const { revalidate, ...responseInit } = init;
const headers = new Headers(responseInit.headers);
revalidate !== undefined && headers.set("X-Revalidate", revalidate.toString());
headers.set("Content-Type", "application/json");
const response = new Response(JSON.stringify(data), {
...responseInit,
headers
});
(response as CustomResponse<T>).customBody = () => data;
return response as CustomResponse<T>;
}