Readme
Turn any function into an API! This lets you call a function in Val Town without manually handling a Request
or Response
object.
This val can be used as a replacement for the Run API, which implicitly did something similar.
This is how you can expose a function as an API:
- Create an HTTP handler val
- Import this val
- Call
rpc
with your function as an argument
Here's an example from @std/rpc_example:
Create valimport { rpc } from "https://esm.town/v/std/rpc?v=5";
export const rpc_example = rpc(async (a: number, b: number) => {
return a + b;
});
You can invoke that function from your client or your local machine with an HTTP request. You can either use a GET or a POST request, passing arguments in the query parameters or the body respectively. Make sure your val's privacy is set to Unlisted or Public.
GET request
Create valconst res = await fetch("https://std-rpc_example.web.val.run/?args=[2,3]");
console.log(await res.json()); // 5
POST request
Create valconst res = await fetch("https://std-rpc_example.web.val.run/", {
method: "POST",
body: JSON.stringify({ args: [2, 3] })
});
console.log(await res.json()); // 5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { parseRPCArgs } from "https://esm.town/v/std/parseRPCArgs";
import { z } from "npm:zod@3.22.4";
export function rpc(fn: Function) {
return async (req: Request): Promise<Response> => {
try {
const args = await parseRPCArgs(req);
const result = await fn.apply(null, args);
return Response.json(result);
} catch (e) {
if (e instanceof Response) {
return e;
}
console.error(e);
return Response.json("Error", { status: 500 });
}
};
}
π 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.