Define an API endpoint
To define a new API endpoint you can either create a new module or add a new endpoint to an existing module.
Create a new module
To create a new module you can create a new folder in the modules folder. For example modules/posts. In this folder create a new sub-folder /procedures with an index.ts file.
Then create a new .ts file for the endpoint in the /procedures folder. For example modules/posts/procedures/published-posts.ts:
import { z } from "zod";
import { publicProcedure } from "../../trpc";
import { db, PostSchema } from "database";
export const publishedPosts = publicProcedure
.output(z.array(PostSchema))
.query(async () => {
const posts = await db.post.findMany({
where: {
published: true,
},
});
return posts;
});Export endpoint from module
To export the endpoint from the module you need to add it to the /procedures/index.ts file of the module:
export * from "./published-posts";If you want to add an endpoint to an existing module you can simply add the endpoint to the /procedures folder of the module and export it in the index.ts file.
Register module router
To make the module and it's endpoints available in the API you need to register a router for this module in the /trpc/router.ts file:
import * as postsProcedures from "../posts/procedures";
export const apiRouter = router({
// ...
posts: router(postsProcedures),
});