trpc
Han Chen
Han Chen
How to use tRPC
import { z } from "zod";
import httpService from "@/services/httpService";
import { createTRPCRouter, publicProcedure } from "../trpc";
type PostType = {
userId: number;
id: number;
title: string;
body: string;
};
export const todoRouter = createTRPCRouter({
hello: publicProcedure
.input(z.object({ text: z.string() }))
.query(({ input }) => {
return {
greeting: `Hello ${input.text}`,
};
}),
getTodos: publicProcedure.query(async () => {
const { data: posts } = await httpService.get(
"https://jsonplaceholder.typicode.com/posts"
)
return posts as Array<PostType>
}),
todoById: publicProcedure
.input(z.object({ id: z.number() }))
.query(async ({ input }) => {
const { data: post } = await httpService.get(`https://jsonplaceholder.typicode.com/todos/${input.id}`)
return post as PostType;
}),
});
How tRPC do each(a batch) request
Firstly decode the code from tRPC request
http://localhost:3000/api/trpc/example.hello,abacus.addition?batch=1&input=%7B%220%22%3A%7B%22json%22%3A%7B%22text%22%3A%22from%20tRPC%22%7D%7D%2C%221%22%3A%7B%22json%22%3A%7B%22row%22%3A10%2C%22column%22%3A4%2C%22decimal%22%3A2%7D%7D%7D
http://localhost:3000/api/trpc/example.hello,abacus.addition?batch=1&input={"0":{"json":{"text":"from tRPC"}},"1":{"json":{"row":10,"column":4,"decimal":2}}}