-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
response.ts
101 lines (92 loc) · 2.56 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
92
93
94
95
96
97
98
99
100
101
import { Cookie, deleteCookie, ReactDOMServer, setCookie } from "./deps.ts";
import { isJSX } from "./handler.ts";
import { HttpResponse, SSR } from "./types.ts";
type BodyInitResponse = BodyInit | null | undefined;
export function response(_req: Request): HttpResponse {
let headers = new Headers();
let responseAuthorization: string;
let responseStatus = 200;
let cookie: Cookie;
let contentType = "text/plain;charset=UTF-8";
// let requestInstance: Request;
let ssr: SSR;
// if (req) requestInstance = req;
function createResponse(
str: BodyInitResponse | JSX.Element,
) {
if (responseAuthorization) {
headers.set("Authorization", responseAuthorization);
}
if (cookie) setCookie(headers, cookie);
headers.set("Content-Type", contentType);
if (isJSX(str)) {
const component = ReactDOMServer.renderToString(<JSX.Element> str);
return new Response(component, {
status: responseStatus,
headers,
});
}
return new Response(<BodyInitResponse> str, {
status: responseStatus,
headers,
});
}
const instance = {
send: (object: unknown) => {
const str = <string> object;
return createResponse(str);
},
json: (object: unknown) => {
try {
const str = JSON.stringify(object);
contentType = "application/json; charset=UTF-8";
return createResponse(str);
} catch (error) {
throw new Error(`jsonError: ${error.toString()}`);
}
},
html: (html: string) => {
contentType = "text/html; charset=UTF-8";
return createResponse(html);
},
jsx: (element: JSX.Element) => {
contentType = "text/html; charset=UTF-8";
return createResponse(element);
},
status: (status: number) => {
responseStatus = status;
return instance;
},
contentType: (type: string) => {
contentType = type;
return instance;
},
authorization: (authorization: string) => {
responseAuthorization = authorization;
return instance;
},
headers: (customHeaders: Headers) => {
headers = customHeaders;
return instance;
},
setCookie: (appCookie: Cookie) => {
cookie = appCookie;
return instance;
},
deleteCookie: (
name: string,
attributes?: {
path?: string | undefined;
domain?: string | undefined;
} | undefined,
) => {
deleteCookie(headers, name, attributes);
return instance;
},
ssr: (ssrInstance: SSR) => {
ssr = ssrInstance;
return ssr;
},
};
return instance;
}