import { TRPCError } from '@trpc/server'
import { z } from 'zod'
import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc'
export const commentRouter = createTRPCRouter({
getAllComments: publicProcedure
.input(
z.object({
slug: z.string()
})
)
.query(async ({ ctx, input }) => {
return await ctx.db.comment.findMany({
where: {
Post: {
slug: input.slug
}
}
})
}),
addComment: protectedProcedure
.input(
z.object({
body: z.string(),
slug: z.string(),
parentId: z.string().optional()
})
)
.mutation(async ({ ctx, input }) => {
const { body, slug, parentId } = input
const user = ctx.session.user
try {
return await ctx.db.comment.create({
data: {
body,
Post: {
connect: {
slug
}
},
user: {
connect: {
id: user.id
}
},
...(parentId && {
parent: {
connect: {
id: parentId
}
}
})
}
})
} catch {
throw new TRPCError({
code: 'BAD_REQUEST'
})
}
})
})
import { TRPCError } from '@trpc/server'
import { z } from 'zod'
import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc'
export const commentRouter = createTRPCRouter({
getAllComments: publicProcedure
.input(
z.object({
slug: z.string()
})
)
.query(async ({ ctx, input }) => {
return await ctx.db.comment.findMany({
where: {
Post: {
slug: input.slug
}
}
})
}),
addComment: protectedProcedure
.input(
z.object({
body: z.string(),
slug: z.string(),
parentId: z.string().optional()
})
)
.mutation(async ({ ctx, input }) => {
const { body, slug, parentId } = input
const user = ctx.session.user
try {
return await ctx.db.comment.create({
data: {
body,
Post: {
connect: {
slug
}
},
user: {
connect: {
id: user.id
}
},
...(parentId && {
parent: {
connect: {
id: parentId
}
}
})
}
})
} catch {
throw new TRPCError({
code: 'BAD_REQUEST'
})
}
})
})