From 665c4e6a26fa78b843505044849586671c502fc1 Mon Sep 17 00:00:00 2001 From: hpkoh Date: Sun, 9 Oct 2022 12:11:03 +0800 Subject: [PATCH] [questions][feat] add get crud --- .../server/router/questions-answer-router.ts | 91 ++++++++++++++++++- 1 file changed, 89 insertions(+), 2 deletions(-) diff --git a/apps/portal/src/server/router/questions-answer-router.ts b/apps/portal/src/server/router/questions-answer-router.ts index 587126d7..599b5587 100644 --- a/apps/portal/src/server/router/questions-answer-router.ts +++ b/apps/portal/src/server/router/questions-answer-router.ts @@ -93,6 +93,7 @@ export const questionsAnswerRouter = createProtectedRouter() }), async resolve({ ctx, input }) { const userId = ctx.session?.user?.id; + const {content, id} = input const answerToUpdate = await ctx.prisma.questionsAnswer.findUnique({ where: { @@ -109,10 +110,10 @@ export const questionsAnswerRouter = createProtectedRouter() return await ctx.prisma.questionsAnswer.update({ data: { - ...input, + content, }, where: { - id: input.id, + id, }, }); }, @@ -142,4 +143,90 @@ export const questionsAnswerRouter = createProtectedRouter() }, }); }, + }) + .query('getVote', { + input: z.object({ + id: z.string(), + }), + async resolve({ ctx, input }) { + return await ctx.prisma.questionsAnswerVote.findUnique({ + where: { + ...input, + }, + }); + }, + }) + .mutation('createVote', { + input: z.object({ + answerId: z.string(), + vote: z.nativeEnum(Vote), + }), + async resolve({ ctx, input }) { + const userId = ctx.session?.user?.id; + + return await ctx.prisma.questionsAnswerVote.create({ + data: { + ...input, + userId, + }, + }); + }, + }) + .mutation('updateVote', { + input: z.object({ + id: z.string(), + vote: z.nativeEnum(Vote), + }), + async resolve({ ctx, input }) { + const userId = ctx.session?.user?.id; + const {id, vote} = input + + const voteToUpdate = await ctx.prisma.questionsAnswerVote.findUnique({ + where: { + id: input.id, + }, + }); + + if (voteToUpdate?.id !== userId) { + throw new TRPCError({ + code: 'UNAUTHORIZED', + message: 'User have no authorization to record.', + }); + } + + return await ctx.prisma.questionsAnswerVote.update({ + data: { + vote, + }, + where: { + id, + }, + }); + }, + }) + .mutation('deleteVote', { + input: z.object({ + id: z.string(), + }), + async resolve({ ctx, input }) { + const userId = ctx.session?.user?.id; + + const voteToDelete = await ctx.prisma.questionsAnswerVote.findUnique({ + where: { + id: input.id, + },}); + + if (voteToDelete?.id !== userId) { + throw new TRPCError({ + code: 'UNAUTHORIZED', + message: 'User have no authorization to record.', + }); + } + + return await ctx.prisma.questionsAnswerVote.delete({ + where: { + id: input.id, + }, + }); + }, }); \ No newline at end of file