summaryrefslogtreecommitdiff
path: root/api/db/_setCurrentChallenge.ts
blob: bd168fe0034c2742e0f41ddb119efd31dfb15a8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { sql } from '@vercel/postgres';
import { CURRENT_CHALLENGES } from './_tables';

export default async function setCurrentChallenge(userId: string, challenge: string) {
  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 query = `
    BEGIN;
    ${deleteExistingChallenges};
    ${insertCurrentChallenge};
    COMMIT;
  `;

  try {
    await sql.query(query);
  } catch (err) {
    throw new Error(`Failed to set current challenge for user with ID ${userId} in database. Query was ${query.replace(/\s+/g, ' ')}. ${err}`);
  }
}