summaryrefslogtreecommitdiff
path: root/api/db/_updateAuthenticator.ts
blob: 6c723279ee45f00f16e4fc48d5ab72e8800ce778 (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
import type Authenticator from '../types/Authenticator';

import { sql } from '@vercel/postgres';
import { AUTHENTICATORS } from './_tables';

export default async function updateAuthenticator<
  T extends keyof Omit<Authenticator, 'id'>
>(id: Authenticator['id'], updatedFields: Pick<Authenticator, T>): Promise<void> {
  const assignments = Object.entries(updatedFields)
    .filter(([key]) => key !== 'id') // never update the ID
    .map(([key, value]) => `${key}=${value}`)
    .join(', ');

  const query = `
    UPDATE ${AUTHENTICATORS.name}
    SET ${assignments}
    WHERE ${AUTHENTICATORS.fields.id} = '{ ${id.toString()} }';
  `;

  try {
    await sql.query(query);
  } catch (err) {
    throw new Error(`Failed to update authenticator with ID [${id.toString()}] in database. Query was ${query.replace(/\s+/g, ' ')}. ${err}`);
  }
}