From 973d8b7dc2675b82b875c0c998272997acf996be Mon Sep 17 00:00:00 2001 From: Joe Carstairs <65492573+Sycamost@users.noreply.github.com> Date: Sun, 24 Dec 2023 15:18:31 +0000 Subject: Rewrites query to set current challenge (#54) --- api/db/_setCurrentChallenge.ts | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) (limited to 'api/db/_setCurrentChallenge.ts') diff --git a/api/db/_setCurrentChallenge.ts b/api/db/_setCurrentChallenge.ts index 58031b1..bd168fe 100644 --- a/api/db/_setCurrentChallenge.ts +++ b/api/db/_setCurrentChallenge.ts @@ -2,31 +2,26 @@ import { sql } from '@vercel/postgres'; import { CURRENT_CHALLENGES } from './_tables'; export default async function setCurrentChallenge(userId: string, challenge: string) { - const insert = ` + const deleteExistingChallenges = ` + DELETE FROM ${CURRENT_CHALLENGES.name} + WHERE ${CURRENT_CHALLENGES.fields.userId} = '${userId}' + `; + + const insertCurrentChallenge = ` INSERT INTO ${CURRENT_CHALLENGES.name} ( ${CURRENT_CHALLENGES.fields.userId}, ${CURRENT_CHALLENGES.fields.currentChallenge} ) VALUES ( - ${userId}, - ${challenge} - ); - `; - - const update = ` - UPDATE TABLE ${CURRENT_CHALLENGES.name} - SET ${CURRENT_CHALLENGES.fields.currentChallenge} = ${challenge} - WHERE ${CURRENT_CHALLENGES.fields.userId} = '${userId}'; + '${userId}', + '${challenge}' + ) `; const query = ` - BEGIN - IF EXISTS ( - SELECT ${CURRENT_CHALLENGES.fields.userId} FROM ${CURRENT_CHALLENGES.name} - WHERE ${CURRENT_CHALLENGES.fields.userId} = ${userId} - ) - ${update}; - ELSE - ${insert}; + BEGIN; + ${deleteExistingChallenges}; + ${insertCurrentChallenge}; + COMMIT; `; try { -- cgit v1.2.3