Skip to content

Commit 4ff0a48

Browse files
feat: Add user initials to the session object
1 parent 481192b commit 4ff0a48

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

src/utils/auth.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import type { SessionValidationResult } from "@/types";
2323
import { SESSION_COOKIE_NAME } from "@/constants";
2424
import { ZSAError } from "zsa";
2525
import { addFreeMonthlyCreditsIfNeeded } from "./credits";
26+
import { getInitials } from "./name-initials";
2627

2728
const getSessionLength = () => {
2829
return ms("30d");
@@ -139,6 +140,9 @@ async function validateSessionToken(token: string, userId: string): Promise<Sess
139140
return null;
140141
}
141142

143+
// Update the user initials
144+
updatedSession.user.initials = getInitials(`${updatedSession.user.firstName} ${updatedSession.user.lastName}`);
145+
142146
return updatedSession;
143147
}
144148

@@ -153,6 +157,9 @@ async function validateSessionToken(token: string, userId: string): Promise<Sess
153157
session.user.currentCredits = currentCredits;
154158
}
155159

160+
// Update the user initials
161+
session.user.initials = getInitials(`${session.user.firstName} ${session.user.lastName}`);
162+
156163
// Return the user data directly from the session
157164
return session;
158165
}

src/utils/kv-session.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ export interface KVSession {
1919
userId: string;
2020
expiresAt: number;
2121
createdAt: number;
22-
user: KVSessionUser;
22+
user: KVSessionUser & {
23+
initials?: string;
24+
};
2325
country?: string;
2426
city?: string;
2527
continent?: string;

src/utils/name-initials.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* Generates initials from a name string
3+
* @param name - The full name to generate initials from
4+
* @param maxLength - Maximum number of initials to return (default: 2)
5+
* @returns The initials as a string
6+
*/
7+
export function getInitials(name: string, maxLength = 2): string {
8+
if (!name) return ""
9+
10+
// Split the name into parts and filter out empty strings
11+
const parts = name.split(/\s+/).filter(Boolean)
12+
13+
// If we have no parts, return empty string
14+
if (parts.length === 0) return ""
15+
16+
// Take the first letter of each part up to maxLength
17+
const initials = parts
18+
.slice(0, maxLength)
19+
.map(part => part[0].toUpperCase())
20+
.join("")
21+
22+
return initials
23+
}

0 commit comments

Comments
 (0)