In your server/api/routers/posts.ts, you define routes using createTRPCRouter. Each route can be a query or a mutation. For example, to create a post, you define a mutation like this:
If you have already noticed, we use a protectedProcedure in the above example. This is because we use the auth.session() middleware in the server/api/trpc/context.ts file. This is a simple check to ensure that the user is authenticated before they can create or edit a post.
If you are using any database operation that requires authentication, you will need to use the protectedProcedure wrapper.
To edit a post, you would use a similar mutation with the necessary input parameters:
And finally, to get all posts, you would use a query:
The structure of building API's with tRPC is simple. If you want to see the rest of the code for the posts router, you can view it here.
In your client component, such as components/posts.tsx, you can call these routes using hooks provided by tRPC. For example, to fetch all posts, you would use:
tRPC streamlines the development process by allowing you to define your API routes and types in one place, reducing the need for boilerplate code. This leads to quicker development cycles and a more cohesive codebase compared to traditional REST APIs. With tRPC, you can easily manage your API calls and ensure type safety across your application.
A new SQL file for the posts has been added. If anyone from a previous version of Hikari wants to try it locally, they need to run this SQL file to set up the necessary database structure.