MCPcopy Create free account
hub / github.com/UsefulSoftwareCo/executor / makeUserStore

Function makeUserStore

apps/cloud/src/auth/user-store.ts:20–100  ·  view source on GitHub ↗
(db: DrizzleDb)

Source from the content-addressed store, hash-verified

18export type Organization = typeof organizations.$inferSelect;
19
20export const makeUserStore = (db: DrizzleDb) => {
21 const getOrganization = async (id: string) => {
22 const rows = await db.select().from(organizations).where(eq(organizations.id, id));
23 return rows[0] ?? null;
24 };
25
26 const slugTaken = async (slug: string) => {
27 const rows = await db
28 .select({ id: organizations.id })
29 .from(organizations)
30 .where(eq(organizations.slug, slug));
31 return rows.length > 0;
32 };
33
34 // Insert a brand-new org row carrying a freshly-minted slug. `ON CONFLICT DO
35 // NOTHING` (no target) absorbs BOTH unique violations without throwing: an
36 // id collision (the org was mirrored concurrently) and a slug collision (the
37 // candidate was claimed by a different org). Returns the inserted row, or
38 // null when either conflict swallowed the insert — the caller decides whether
39 // to re-read (id race) or retry with a new candidate (slug race).
40 const tryInsertOrg = async (id: string, name: string, slug: string) => {
41 const [row] = await db
42 .insert(organizations)
43 .values({ id, name, slug })
44 .onConflictDoNothing()
45 .returning();
46 return row ?? null;
47 };
48
49 // Every new org row is born with a slug — there is no nullable window and no
50 // self-healing. Existing rows keep their slug (stable across renames, so org
51 // URLs survive) and only refresh their name.
52 const upsertOrganization = async (org: { id: string; name: string }) => {
53 const existing = await getOrganization(org.id);
54 if (existing) {
55 const [updated] = await db
56 .update(organizations)
57 .set({ name: org.name })
58 .where(eq(organizations.id, org.id))
59 .returning();
60 return updated ?? existing;
61 }
62 for (let attempt = 0; attempt < 4; attempt++) {
63 const slug = await generateOrgSlug(org.name, slugTaken);
64 const inserted = await tryInsertOrg(org.id, org.name, slug);
65 if (inserted) return inserted;
66 // The insert was swallowed by a conflict. If the id now exists, a
67 // concurrent request mirrored it — return that row. Otherwise the slug
68 // candidate collided; loop and mint a fresh one.
69 const fresh = await getOrganization(org.id);
70 if (fresh) return fresh;
71 }
72 // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: slug minting exhausted retries; surfacing loudly beats a silently unslugged org
73 throw new Error(`unable to mint a slug for organization ${org.id}`);
74 };
75
76 return {
77 // --- Accounts ---

Callers 4

UserStoreServiceClass · 0.90
makeUserStoreLayerFunction · 0.90
db.test.tsFile · 0.90
upsertFunction · 0.90

Calls 1

valuesMethod · 0.80

Tested by 1

upsertFunction · 0.72