Readme

HTTP Val Mocking example

This is an example of mocking an HTTP val. Let's say that you're developing a val that responds to a POST request. That's tricky to debug and develop in the Browser preview tab, which just shows a GET request. But you can do it, because with web-standard Request & Response objects, requests and responses are values, and we can create those values ourselves.

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
/**
* This method expects to receive a POST request
* with a body, which is a JSON object with a name
* member.
*/
export const httpHandler = async function(req: Request): Promise<Response> {
if (req.method !== "POST") return new Response("Bad request: only POST allowed", { status: 400 });
const body = await req.json();
return Response.json({ hello: body.name });
};
/**
* This "mocks out" the request: so we're sending a POST request with a JSON
* body here. We can tweak everything about this request - we're the ones
* creating it.
*
* And we can also preview the result of this handler in the standard Browser
* preview. In short, in this chunk of code, we're exporting a _different_
* HTTP handler, which ignores the incoming request and provides one of its
* own, and then sends the resulting response.
*
* When you're ready to deploy and done with testing, you can just
* comment out this block of code.
*/
export default () =>
httpHandler(
new Request("https://tmcw-httpmockingexample.web.val.run/", {
body: JSON.stringify({ name: "Peter" }),
headers: {
"Content-Type": "application/json",
},
method: "POST",
}),
);
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.