Routes
Routes are the basic building blocks of Kaito. They represent a single HTTP route with a optional input schemas (body, query) and execution logic.
Creating a Route
Creating a route requires us to have a router already established. If you don’t, please checkout the getting started guide.
Here’s an extremely basic example of a ping/pong route.
const app = router().get('/ping', async () => 'pong');
Constraints
- Route return types must be JSON serializable
- Route execution logic must be async (return a promise). This might change in the future
Execution
Routes are executed by the router. The router is responsible for parsing the request, validating the input, and executing the route. Route run methods must be async. Throwing an error will call your onError handler defined in your server.
Input
Routes can also take a query and body schema provided by Zod. Internally, Kaito wil validate all request bodies and query params so you can be absolutely certain you are processing the right data.
Route query schemas should always take a string, or array of strings as the input. This is because query params are always strings. It is safe to transform them into other types, but you should always be able to handle a string.
import {z} from 'zod';
const router = router().post('/echo', {
query: {
skip: z.string().transform(value => parseInt(value)),
take: z.string().transform(value => parseInt(value)),
},
body: z.number(),
async run({body, query}) {
// Echo it back
return {body, query};
},
});
Zod schemas can be of any shape or size, including objects, booleans, numbers and literals. For more reference, please read the Zod Documentation.