diff options
| author | Joe Carstairs <65492573+Sycamost@users.noreply.github.com> | 2023-12-24 15:18:31 +0000 |
|---|---|---|
| committer | Joe Carstairs <jcarstairs@scottlogic.com> | 2024-01-29 10:46:51 +0000 |
| commit | 973d8b7dc2675b82b875c0c998272997acf996be (patch) | |
| tree | 45330726b21d30d9978729345cca7a11b8cee7b1 | |
| parent | 2f7541ae836a99d9f189845547010e470e0efa8c (diff) | |
Rewrites query to set current challenge (#54)
| -rw-r--r-- | api/db/_setCurrentChallenge.ts | 31 |
1 files changed, 13 insertions, 18 deletions
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 { |
