summaryrefslogtreecommitdiff
path: root/api/db/_getCurrentChallenge.ts
diff options
context:
space:
mode:
Diffstat (limited to 'api/db/_getCurrentChallenge.ts')
-rw-r--r--api/db/_getCurrentChallenge.ts24
1 files changed, 24 insertions, 0 deletions
diff --git a/api/db/_getCurrentChallenge.ts b/api/db/_getCurrentChallenge.ts
new file mode 100644
index 0000000..ec82e4d
--- /dev/null
+++ b/api/db/_getCurrentChallenge.ts
@@ -0,0 +1,24 @@
+import { QueryResultRow, sql } from '@vercel/postgres';
+import { CURRENT_CHALLENGES } from './_tables';
+
+export default async function getCurrentChallenge(userId: string): Promise<string | null> {
+ try {
+ const result = await sql.query(`
+ SELECT ${CURRENT_CHALLENGES.fields.currentChallenge}
+ FROM ${CURRENT_CHALLENGES.name}
+ WHERE ${CURRENT_CHALLENGES.fields.userId} = '${userId}';
+ `);
+
+ 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.`, err);
+ }
+} \ No newline at end of file