fix: Auto-create users on profile access and make email nullable in types

- Update getUserProfile, getUserReports, getUserEvents, and getUserActivity to call findOrCreateUser for Clerk IDs
- This ensures users are automatically created in database when accessing their profile for the first time
- Update User type to have email as 'string | null' instead of 'string'
- Fixes 404 errors when new users try to access their profile

This resolves the issue where new users signing up without email would get 404 errors when accessing their profile page.
This commit is contained in:
2025-11-18 18:15:33 +00:00
parent d71c994f0f
commit d1a06699e5
3 changed files with 12 additions and 25 deletions

View File

View File

@@ -66,6 +66,11 @@ export class UserService {
// Check if this is a Clerk ID (starts with 'user_') // Check if this is a Clerk ID (starts with 'user_')
const isClerkId = userId.startsWith('user_'); const isClerkId = userId.startsWith('user_');
// If it's a Clerk ID, ensure the user exists in our database
if (isClerkId) {
await this.findOrCreateUser(userId);
}
const user = await prisma.user.findUnique({ const user = await prisma.user.findUnique({
where: isClerkId ? { clerkId: userId } : { id: userId }, where: isClerkId ? { clerkId: userId } : { id: userId },
select: { select: {
@@ -174,14 +179,8 @@ export class UserService {
let dbUserId = userId; let dbUserId = userId;
if (isClerkId) { if (isClerkId) {
const user = await prisma.user.findUnique({ // Ensure user exists in database
where: { clerkId: userId }, dbUserId = await this.findOrCreateUser(userId);
select: { id: true },
});
if (!user) {
throw new Error('User not found');
}
dbUserId = user.id;
} }
const reports = await prisma.report.findMany({ const reports = await prisma.report.findMany({
@@ -207,14 +206,8 @@ export class UserService {
let dbUserId = userId; let dbUserId = userId;
if (isClerkId) { if (isClerkId) {
const user = await prisma.user.findUnique({ // Ensure user exists in database
where: { clerkId: userId }, dbUserId = await this.findOrCreateUser(userId);
select: { id: true },
});
if (!user) {
throw new Error('User not found');
}
dbUserId = user.id;
} }
// Get events user has registered for // Get events user has registered for
@@ -315,14 +308,8 @@ export class UserService {
let dbUserId = userId; let dbUserId = userId;
if (isClerkId) { if (isClerkId) {
const user = await prisma.user.findUnique({ // Ensure user exists in database
where: { clerkId: userId }, dbUserId = await this.findOrCreateUser(userId);
select: { id: true },
});
if (!user) {
throw new Error('User not found');
}
dbUserId = user.id;
} }
// Get user's reports // Get user's reports

View File

@@ -18,7 +18,7 @@ export interface Coordinates {
export interface User { export interface User {
id: string; id: string;
clerkId: string; clerkId: string;
email: string; email: string | null;
username: string; username: string;
firstName?: string; firstName?: string;
lastName?: string; lastName?: string;