refactor(260607-l6l): extract shared deriveDisplayName helper (BUG 2 DRY)

The displayName claim-preference logic (name → preferred_username → email →
sub fallback) was duplicated verbatim in me.ts and events.ts resolveUserId.
Extract it to auth/user.ts as deriveDisplayName and use it in both call sites,
so the rule has one definition. Update the events.test.ts user.js mock to keep
the real helper (spread importActual) while stubbing only upsertUser.
This commit is contained in:
Lucas Berger
2026-06-07 15:37:18 -04:00
parent 509f4b26e0
commit a99ef1daae
4 changed files with 48 additions and 32 deletions
+5 -11
View File
@@ -31,7 +31,7 @@ import { db } from '../db/client.js'
import { calendarEvents, calendars, users, calendarOutbox } from '../db/schema.js'
import { expandOccurrences } from '../broker/expand.js'
import { getAuth } from '../auth/middleware.js'
import { upsertUser } from '../auth/user.js'
import { upsertUser, deriveDisplayName } from '../auth/user.js'
// Side-effect import: brings in the ContextVariableMap augmentation for c.get('user')
import '../auth/devBypass.js'
@@ -66,16 +66,10 @@ async function resolveUserId(c: any): Promise<number | null> {
const iss = (auth.iss as string | undefined) ?? ''
const sub = auth.sub ?? ''
// Derive displayName with same preference order as me.ts (name → preferred_username
// → email → sub fallback). Both call sites must agree so a write-path upsert does not
// overwrite a correctly-derived name with a worse one.
const claimStr = (v: unknown): string | undefined =>
typeof v === 'string' && v.trim() !== '' ? v.trim() : undefined
const displayName =
claimStr(auth.name) ??
claimStr(auth.preferred_username) ??
claimStr(auth.email) ??
`Member ${String(sub).slice(0, 8)}`
// Derive displayName via the shared helper (name → preferred_username → email
// → sub fallback) so the write-path upsert agrees with me.ts and never
// overwrites a correctly-derived name with a worse one.
const displayName = deriveDisplayName(auth, sub)
const user = await upsertUser(iss, sub, displayName)
return user?.id ?? null