summaryrefslogtreecommitdiff
path: root/api/db/_getUser.ts
blob: 118892729ac9ed61272668abadd418582c613f29 (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
import { QueryResultRow, sql } from '@vercel/postgres';
import User from '../types/User';
import { USERS } from './_tables';

export default async function getUser(
  userId: string
): Promise<Pick<User, 'id' | 'displayName'> | null> {
  const query = `
    SELECT
      ${USERS.fields.displayName}
    FROM ${USERS.name}
    WHERE ${USERS.fields.id} = '${userId}';
  `;

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

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

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

    return {
      id: userId,
      displayName: row[USERS.fields.displayName],
    };
  } catch (err) {
    throw new Error(`Failed to get user with ID ${userId} from database. Query was ${query.replace(/\s+/g, ' ')}. ${err}`);
  }
}