From 776376a296c891bd4db61973c0653933528daf68 Mon Sep 17 00:00:00 2001 From: hpkoh Date: Sun, 9 Oct 2022 12:26:52 +0800 Subject: [PATCH] [questions][feat] add vote crud --- .../questions-question-comment-router.ts | 89 +++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/apps/portal/src/server/router/questions-question-comment-router.ts b/apps/portal/src/server/router/questions-question-comment-router.ts index a28fa78a..12f2bc21 100644 --- a/apps/portal/src/server/router/questions-question-comment-router.ts +++ b/apps/portal/src/server/router/questions-question-comment-router.ts @@ -136,4 +136,93 @@ export const questionsQuestionCommentRouter = createProtectedRouter() }, }); }, + }) + .query('getVote', { + input: z.object({ + questionCommentId: z.string(), + }), + async resolve({ ctx, input }) { + const userId = ctx.session?.user?.id; + const {questionCommentId} = input + + return await ctx.prisma.questionsQuestionCommentVote.findUnique({ + where: { + questionCommentId_userId : {questionCommentId,userId }, + }, + }); + }, + }) + .mutation('createVote', { + input: z.object({ + questionCommentId: z.string(), + vote: z.nativeEnum(Vote), + }), + async resolve({ ctx, input }) { + const userId = ctx.session?.user?.id; + + return await ctx.prisma.questionsQuestionCommentVote.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.questionsQuestionCommentVote.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.questionsQuestionCommentVote.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.questionsQuestionCommentVote.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.questionsQuestionCommentVote.delete({ + where: { + id: input.id, + }, + }); + }, }); \ No newline at end of file