summaryrefslogtreecommitdiff
path: root/api
diff options
context:
space:
mode:
Diffstat (limited to 'api')
-rw-r--r--api/db/_setCurrentChallenge.ts31
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 {