From 4ea2a178f3cebcfc5bef046104564f8151ae47c0 Mon Sep 17 00:00:00 2001 From: Thanu Poptiphueng Date: Fri, 19 Apr 2024 19:26:10 +0700 Subject: [PATCH] added validation to opinion --- Taskfile.yml | 5 +++++ src/userRoute.ts | 37 ++++++++++++++++++++++++++----------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/Taskfile.yml b/Taskfile.yml index fe1051f..17db892 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -16,3 +16,8 @@ tasks: studio: cmds: - pnpm drizzle-kit studio + start: + cmds: + - node -r @swc-node/register src/app.ts + env: + NODE_ENV: production diff --git a/src/userRoute.ts b/src/userRoute.ts index d3d94bf..0db71fa 100644 --- a/src/userRoute.ts +++ b/src/userRoute.ts @@ -1,11 +1,6 @@ -import { - router, - verifiedPhone, - publicProcedure, - protectedProcedure, -} from "./trpc"; +import { router, publicProcedure, protectedProcedure } from "./trpc"; import { db } from "./db"; -import { phoneToken, user, userOpinion } from "./schema"; +import { opinion, user, userOpinion } from "./schema"; import { createInsertSchema } from "drizzle-zod"; import { z } from "zod"; import { SQL, eq } from "drizzle-orm"; @@ -45,6 +40,7 @@ export const userRoute = router({ limit: z.number().max(50).default(10), group: z.number().optional(), zone: z.number().optional(), + opinionCount: z.number().default(3), }) ) .query( @@ -154,19 +150,38 @@ function createJWT(phone: string) { async function changeOpinion( opinionId: number, userId: number, - opinion: OpinionInsertSchema[0]["choice"] + opinionChoice: OpinionInsertSchema[0]["choice"] ) { try { - db.insert(userOpinion) + let thisOpinion = await db + .select() + .from(opinion) + .where(eq(opinion.id, opinionId)) + .then((opinions) => opinions.at(0)); + + if (thisOpinion === undefined) { + throw new TRPCError({ + message: "Invalid Opinion ID", + code: "BAD_REQUEST", + }); + } else if (thisOpinion.type === "3Choice" && opinionChoice === "ignore") { + throw new TRPCError({ + message: "Invalid Opinion Choice", + code: "BAD_REQUEST", + }); + } + await db + .insert(userOpinion) .values({ opinionId, userId, - choice: opinion, + choice: opinionChoice, }) .onConflictDoUpdate({ target: [userOpinion.userId, userOpinion.opinionId], - set: { choice: opinion }, + set: { choice: opinionChoice }, }); + return { status: "success" }; } catch (e) { console.error(e); throw new TRPCError({