Public
Script
v12
April 10, 2024
Readme
Appends the "Code on Val Town" ribbon to an HTTP Response.
new modifyResponse(res, { handle: "andre", name: "foo" })
- define which val to link to;new modifyResponse(res)
- infer the val from the call stack.
Example: @andreterron/openable_res
import { modifyResponse } from "https://esm.town/v/andreterron/codeOnVT_modifyResponse";
import { html } from "https://esm.town/v/stevekrouse/html?v=5";
export default async (req: Request): Promise<Response> => {
return modifyResponse(html(`
<h2>Hello world!</h2>
<style>* { font-family: sans-serif }</style>
`));
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { InjectCodeOnValTownStream } from "https://esm.town/v/andreterron/InjectCodeOnValTownStream?v=4";
import { ValRef } from "https://esm.town/v/andreterron/ValRef?v=1";
import { parse } from "npm:content-type";
/**
* @param res Response
* @param val Define which val should open. Defaults to the root reference.
*/
export function modifyResponse(
res: Response,
{ val, style }: { val?: ValRef; style?: string } = {},
) {
if (!res.headers.has("Content-Type") || parse(res.headers.get("Content-Type")).type !== "text/html") {
return res;
}
return new Response(
res.body ? res.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(new InjectCodeOnValTownStream({ val, style }))
.pipeThrough(new TextEncoderStream()) : res.body,
res,
);
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
v12
April 10, 2024
I occasionally get errors
Cannot read properties of null (reading 'pipeThrough')
. Not sure what is causing them or how to mitigate, just wanted to report :)Maybe
res.body
can benull
. I added an extra check.Thanks!