Skip to content
File

Blob: src/worker/db/d1/dal/users.ts

typescript27 lines
1import { eq } from "drizzle-orm";
2 
3import type { Db } from "@/worker/db/d1/client";
4import { type NewUserRow, type UserRow, users } from "@/worker/db/d1/schema/users";
5 
6export async function findUserById(db: Db, id: string): Promise<UserRow | undefined> {
7 const rows = await db.select().from(users).where(eq(users.id, id)).limit(1);
8 return rows[0];
9}
10 
11export async function findUserByTesseraSub(
12 db: Db,
13 tesseraSub: string
14): Promise<UserRow | undefined> {
15 const rows = await db.select().from(users).where(eq(users.tesseraSub, tesseraSub)).limit(1);
16 return rows[0];
17}
18 
19// Insert a fresh user row. Returns the inserted row when this call won the
20// race; returns undefined when an existing row already had the same
21// `tessera_sub`. Callers combine this with `findUserByTesseraSub` to obtain
22// the canonical row in either case (see `auth/session` first-login flow).
23export async function insertUserIfNew(db: Db, row: NewUserRow): Promise<UserRow | undefined> {
24 const inserted = await db.insert(users).values(row).onConflictDoNothing().returning();
25 return inserted[0];
26}