The source code for this blog is available on GitHub.
Note
Top

trpc

Cover Image for 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&amp;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&amp;input={&quot;0&quot;:{&quot;json&quot;:{&quot;text&quot;:&quot;from tRPC&quot;}},&quot;1&quot;:{&quot;json&quot;:{&quot;row&quot;:10,&quot;column&quot;:4,&quot;decimal&quot;:2}}}

Reference

© 2024 WOOTHINK. All Rights Reserved.
Site MapTerms and ConditionsPrivacy PolicyCookie Policy