generated from kriasoft/react-starter-kit
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.ts
54 lines (52 loc) · 1.5 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
47
48
49
50
51
52
53
54
/* SPDX-FileCopyrightText: 2014-present Kriasoft <hello@kriasoft.com> */
/* SPDX-License-Identifier: MIT */
import type { Environment } from "relay-runtime";
import type { Config } from "../config";
import type { RouteResponse } from "../core/router";
/**
* Injects HTML page metadata (title, description, etc.) as well as
* the serialized Relay store.
*/
export function transform(
res: Response,
route: RouteResponse,
relay: Environment,
env: Config["app"]["env"]
): Response {
return new HTMLRewriter()
.on("body:first-of-type", {
// <body data-env="...">
element(el) {
el.setAttribute("data-env", env);
},
})
.on("title:first-of-type", {
// <title>...</title>
element(el) {
if (route.title) {
el.setInnerContent(route.title);
}
},
})
.on('meta[name="description"]:first-of-type', {
// <meta name="description" content="..." />
element(el) {
if (route.description) {
el.setAttribute("content", route.description);
}
},
})
.on("script#data", {
element(el) {
// <script id="data" type="application/json"></script>
// https://developer.mozilla.org/docs/Web/HTML/Element/script#embedding_data_in_html
const data = relay.getStore().getSource().toJSON();
const json = JSON.stringify(data).replace(
/<\/script/g,
"</\\u0073cript"
);
el.setInnerContent(json, { html: true });
},
})
.transform(res);
}