History

Parse identity metadata with zod record helper

Rhys Sullivan committed 8 months ago

Commit eff91531 parent a2ae3f51 file · +10 −3Browse files

Unified · Split

executor/packages/database/src/auth/identity.ts+10−3
@@ -21,6 +21,12 @@ type WorkosProfile = { · 20 unmodified lines
2121 };
2222
2323 const nonEmptyTrimmedStringSchema = z.string().transform((value) => value.trim()).refine((value) => value.length > 0);
24+const recordSchema = z.record(z.unknown());
25+
26+function parseRecord(value: unknown): Record<string, unknown> | null {
27+ const parsed = recordSchema.safeParse(value);
28+ return parsed.success ? parsed.data : null;
29+}
2430
2531 function deriveFallbackUserLabel(workosUserId: string): string {
2632 return `User ${workosUserId.slice(-6)}`;
@@ -60,7 +66,8 @@ function getIdentityString(identity: Record<string, unknown>, keys: string[]): s · 33 unmodified lines
6066 }
6167
6268 const nestedRecords = Object.values(identity)
63− .filter((value): value is Record<string, unknown> => Boolean(value) && typeof value === "object" && !Array.isArray(value));
69+ .map((value) => parseRecord(value))
70+ .filter((value): value is Record<string, unknown> => value !== null);
6471 for (const nestedRecord of nestedRecords) {
6572 for (const key of keys) {
6673 const parsedValue = nonEmptyTrimmedStringSchema.safeParse(nestedRecord[key]);
@@ -98,8 +105,8 @@ function getProfileString(profile: WorkosProfile | null, keys: string[]): string · 31 unmodified lines
98105 }
99106
100107 const metadata = profileRecord.metadata;
101− if (metadata && typeof metadata === "object") {
102− const metadataRecord = metadata as Record<string, unknown>;
108+ const metadataRecord = parseRecord(metadata);
109+ if (metadataRecord) {
103110 for (const key of keys) {
104111 const parsedValue = nonEmptyTrimmedStringSchema.safeParse(metadataRecord[key]);
105112 if (parsedValue.success) {