1.9 KiB
Relay
Relay is a full stack protocol for communicating between client and server. It is also built around the major HTTP methods allowing for creating public API endpoints.
Quick Start
For this quick start guide we assume the following project setup:
api/
relay/
web/
Relay
First we want to set up our relay space, from the structure above lets start by defining our route.
import { route } from "@valkyr/relay";
import z from "zod";
export default route
.post("/users")
.body(
z.object({
name: z.string(),
email: z.string().check(z.email()),
})
)
.response(z.string());
After creating our first route we mount it onto our relay instance.
import { Relay } from "@valkyr/relay";
import route from "./path/to/route.ts";
export const relay = new Relay([
route
]);
We have now finished defining our initial relay setup which we can now utilize in our api and web spaces.
API
To be able to successfully execute our user create route we need to attach a handler in our api. Lets start off by defining our handler.
import { UnprocessableContentError } from "@valkyr/relay";
import { relay } from "~project/relay/mod.ts";
relay
.route("POST", "/users")
.handle(async ({ name, email }) => {
const user = await db.users.insert({ name, email });
if (user === undefined) {
return new UnprocessableContentError();
}
return user.id;
});
We now have a POST handler for the /users path.
Web
Now that we have both our relay and api ready to recieve requests we can trigger a user creation request in our web application.
import { relay } from "~project/relay/mod.ts"
const userId = await relay.post("/users", {
name: "John Doe",
email: "john.doe@fixture.none"
});
console.log(userId); // => string