mirror of
https://github.com/zoriya/Kyoo.git
synced 2026-03-28 12:27:51 -04:00
25 lines
651 B
TypeScript
25 lines
651 B
TypeScript
import { eq, sql } from "drizzle-orm";
|
|
import { db } from "~/db";
|
|
import { profiles } from "~/db/schema";
|
|
|
|
export async function getOrCreateProfile(userId: string) {
|
|
let [profile] = await db
|
|
.select({ pk: profiles.pk })
|
|
.from(profiles)
|
|
.where(eq(profiles.id, userId))
|
|
.limit(1);
|
|
if (profile) return profile.pk;
|
|
|
|
[profile] = await db
|
|
.insert(profiles)
|
|
.values({ id: userId })
|
|
.onConflictDoUpdate({
|
|
// we can't do `onConflictDoNothing` because on race conditions
|
|
// we still want the profile to be returned.
|
|
target: [profiles.id],
|
|
set: { id: sql`excluded.id` },
|
|
})
|
|
.returning({ pk: profiles.pk });
|
|
return profile.pk;
|
|
}
|