Scrum4Me/actions/profile.ts
Madhura68 5ed3645ecb feat(ST-507): persist email in updateProfileAction with Zod validation
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 19:37:49 +02:00

55 lines
1.7 KiB
TypeScript

'use server'
import { revalidatePath } from 'next/cache'
import { cookies } from 'next/headers'
import { getIronSession } from 'iron-session'
import { z } from 'zod'
import { prisma } from '@/lib/prisma'
import { SessionData, sessionOptions } from '@/lib/session'
async function getSession() {
return getIronSession<SessionData>(await cookies(), sessionOptions)
}
const profileSchema = z.object({
email: z.string().trim().email('Ongeldig e-mailadres').max(254).optional(),
bio: z.string().max(160).optional(),
bio_detail: z.string().max(2000).optional(),
})
export async function updateProfileAction(_prevState: unknown, formData: FormData) {
const session = await getSession()
if (!session.userId) return { error: 'Niet ingelogd' }
if (session.isDemo) return { error: 'Niet beschikbaar in demo-modus' }
const parsed = profileSchema.safeParse({
email: (formData.get('email') as string)?.trim() || undefined,
bio: (formData.get('bio') as string) || undefined,
bio_detail: (formData.get('bio_detail') as string) || undefined,
})
if (!parsed.success) return { error: parsed.error.flatten().fieldErrors }
try {
await prisma.user.update({
where: { id: session.userId },
data: {
email: parsed.data.email ?? null,
bio: parsed.data.bio ?? null,
bio_detail: parsed.data.bio_detail ?? null,
},
})
} catch (err: unknown) {
if (
typeof err === 'object' &&
err !== null &&
'code' in err &&
(err as { code: string }).code === 'P2002'
) {
return { error: 'Dit e-mailadres is al in gebruik' }
}
throw err
}
revalidatePath('/settings')
return { success: true }
}