summaryrefslogtreecommitdiff
path: root/api/db/_getCurrentChallenge.ts
blob: af428cb868bcacb2310bb72acc682c766b731487 (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
import { QueryResultRow, sql } from '@vercel/postgres';
import { CURRENT_CHALLENGES } from './_tables';

export default async function getCurrentChallenge(userId: string): Promise<string | null> {
  const query = `
    SELECT ${CURRENT_CHALLENGES.fields.currentChallenge}
    FROM ${CURRENT_CHALLENGES.name}
    WHERE ${CURRENT_CHALLENGES.fields.userId} = '${userId}';
  `;

  try {
    const result = await sql.query(query);

    if (!result.rows.length) {
      return null;
    }

    const row: QueryResultRow = result.rows.at(0);

    // If the result is NULL in Postgres, it should be JavaScript `null` here.
    // See https://github.com/brianc/node-postgres/blob/master/packages/pg/lib/result.js
    return row[CURRENT_CHALLENGES.fields.currentChallenge];
  } catch (err) {
    throw new Error(`Failed to get current challenge for user with ID ${userId} from database. Query was ${query.replace(/\s+/g, ' ')}. ${err}`);
  }
}