🙆‍♀️

【tRPC】NextJs & tRPC 【#8 tRPC Add Posts Route】

に公開

【#8 tRPC Add Posts Route】

YouTube: https://youtu.be/feaH3fcWz2o
https://youtu.be/feaH3fcWz2o

今回は作成したデータベースの
「posts」を操作できるように
「tRPC」側のルートを追加していきます。

src/trpc/routers/posts.ts
import { z } from 'zod'

import {
  baseProcedure,
  createTRPCRouter,
  protectedProcedure,
} from '@/trpc/init'
import { db } from '@/db'
import { posts } from '@/db/schema'

export const postsRouter = createTRPCRouter({
  create: protectedProcedure
    .input(
      z.object({
        title: z.string(),
      })
    )
    .mutation(async ({ ctx, input }) => {
      const [post] = await db
        .insert(posts)
        .values({
          title: input.title,
          userId: ctx.userId,
        })
        .returning()

      return post
    }),
  getMany: baseProcedure.query(async () => {
    const data = await db.select().from(posts)

    return data
  }),
})
src/trpc/routers/_app.ts
import { z } from 'zod'
import { baseProcedure, createTRPCRouter, protectedProcedure } from '../init'
import { postsRouter } from './posts'

export const appRouter = createTRPCRouter({
  hello: protectedProcedure
    .input(
      z.object({
        text: z.string(),
      })
    )
    .query(async (opts) => {
      return {
        greeting: `hello ${opts.input.text}`,
      }
    }),
  posts: postsRouter,
})
// export type definition of API
export type AppRouter = typeof appRouter

Discussion