Connect, collaborate, and grow with a community of TypeScript developers
Use zod schema on server actions (#851)
Sean Boult5fc0b845007a
diff --git a/apps/web/src/app/[locale]/settings/_components/appearance.tsx b/apps/web/src/app/[locale]/settings/_components/appearance.tsxindex 2a8c38f5..31f5c233 100644--- a/apps/web/src/app/[locale]/settings/_components/appearance.tsx+++ b/apps/web/src/app/[locale]/settings/_components/appearance.tsx@@ -15,7 +15,8 @@ import { RadioGroup, RadioGroupItem } from '@repo/ui/components/radio-group';import { Separator } from '@repo/ui/components/separator';import { useToast } from '@repo/ui/components/use-toast';import { useForm } from 'react-hook-form';-import { z } from 'zod';+import { appearanceFormSchema } from './schema';+import type { z } from 'zod';export function Appearances() {return (@@ -32,16 +33,6 @@ export function Appearances() {);}-const appearanceFormSchema = z.object({- theme: z.enum(['light', 'dark'], {- required_error: 'Please select a theme.',- }),- font: z.enum(['inter', 'manrope', 'system'], {- invalid_type_error: 'Select a font',- required_error: 'Please select a font.',- }),-});-type AppearanceFormValues = z.infer<typeof appearanceFormSchema>;// This can come from your database or API.diff --git a/apps/web/src/app/[locale]/settings/_components/index.tsx b/apps/web/src/app/[locale]/settings/_components/index.tsxdeleted file mode 100644index 187a8858..00000000--- a/apps/web/src/app/[locale]/settings/_components/index.tsx+++ /dev/null@@ -1,130 +0,0 @@-'use client';--import { zodResolver } from '@hookform/resolvers/zod';-import { useFieldArray, useForm, useWatch } from 'react-hook-form';-import * as z from 'zod';-import Link from 'next/link';-import { updateProfile } from './settings.action';-import { toast } from '@repo/ui/components/use-toast';-import { Button } from '@repo/ui/components/button';-import { Form, FormField, FormItem, FormMessage } from '@repo/ui/components/form';-import { MagicIcon } from '@repo/ui/components/magic-icon';-import { Input } from '@repo/ui/components/input';-import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';-import { RichMarkdownEditor } from '~/components/rich-markdown-editor';--export interface UserLinkType {- id: string | null;- url: string;-}--const formSchema = z.object({- userLinks: z.array(- z.object({- id: z.union([z.string(), z.null()]),- url: z.union([- createNoProfanitySchemaWithValidate((str) => str.url().max(256)),- z.literal(''),- ]),- }),- ),- bio: createNoProfanitySchemaWithValidate((str) => str.max(256)),-});--export type FormSchema = z.infer<typeof formSchema>;--// million-ignore-export function Settings({ profileData, username }: { profileData: FormSchema; username: string }) {- const form = useForm<FormSchema>({- resolver: zodResolver(formSchema),- defaultValues: {- ...profileData,- },- });-- const {- formState: { errors },- control,- getValues,- register,- } = form;-- const userLinks = useWatch({ control: form.control, name: 'userLinks' });-- const { fields } = useFieldArray({- control,- name: 'userLinks',- });-- const onSubmit = async (values: FormSchema) => {- const isValid = await form.trigger();-- if (!isValid) return;- // call the server action- await updateProfile(values);-- toast({- variant: 'success',- title: 'Your settings have been updated',- });- };-- return (- <div className="container">- <div className="mt-10 flex w-full justify-between">- <div className="mr-10">- <h2 className="text-3xl font-bold">Settings</h2>- <h4 className="mb-4 mt-6 text-xl font-bold">Bio</h4>- </div>-- <Link className="mb-6" href={`@${username}`}>- <Button type="button" variant="outline">- View profile- </Button>- </Link>- </div>-- <Form {...form}>- <form action={() => onSubmit(getValues())}>- <div>- <FormField- control={form.control}- name="bio"- render={({ field }) => (- <FormItem className="h-[300px] w-[600px]">- <RichMarkdownEditor onChange={field.onChange} value={field.value} />- <FormMessage />- </FormItem>- )}- />- </div>- <div className="mt-8 flex flex-col items-start space-y-3">- <h4 className="text-xl font-bold">Social accounts</h4>- {fields.map((val, i) => {- return (- <FormItem className="mb-3" key={`url-link-${i}`}>- <div className="flex items-center gap-2">- <MagicIcon url={userLinks[i]?.url ?? ''} />- <Input- className="w-64"- defaultValue={val.url}- placeholder="Link to social profile"- {...register(`userLinks.${i}.url`)}- />- {errors.userLinks?.[i]?.url?.message ? (- <div className="text-destructive">{errors.userLinks[i]?.url?.message}</div>- ) : null}- </div>- </FormItem>- );- })}- </div>-- <Button className="mt-6" type="submit">- Save- </Button>- </form>- </Form>- </div>- );-}diff --git a/apps/web/src/app/[locale]/settings/_components/profile.tsx b/apps/web/src/app/[locale]/settings/_components/profile.tsxindex 69bf13c6..89411606 100644--- a/apps/web/src/app/[locale]/settings/_components/profile.tsx+++ b/apps/web/src/app/[locale]/settings/_components/profile.tsx@@ -25,38 +25,10 @@ import { Separator } from '@repo/ui/components/separator';import { useToast } from '@repo/ui/components/use-toast';import Link from 'next/link';import { useFieldArray, useForm } from 'react-hook-form';-import { z } from 'zod';import { RichMarkdownEditor } from '~/components/rich-markdown-editor';-import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';import { updateProfile } from './settings.action';+import { profileSchema, type ProfileSchema } from './schema';-const profileFormSchema = z.object({- username: z- .string()- .min(2, {- message: 'Username must be at least 2 characters.',- })- .max(30, {- message: 'Username must not be longer than 30 characters.',- }),- email: z- .string({- required_error: 'Please select an email to display.',- })- .email(),- bio: createNoProfanitySchemaWithValidate((str) => str.max(256)),- userLinks: z.array(- z.object({- id: z.union([z.string(), z.null()]),- url: z.union([- createNoProfanitySchemaWithValidate((str) => str.url().max(256)),- z.literal(''),- ]),- }),- ),-});--type ProfileFormValues = z.infer<typeof profileFormSchema>;interface Props {user: User & { userLinks: { id: string | null; url: string }[] };}@@ -90,8 +62,8 @@ function ProfileForm({ user }: Props) {// NOTE: sort the user links so empty strings are at the bottom.sort((a, b) => b.url.localeCompare(a.url));- const form = useForm<ProfileFormValues>({- resolver: zodResolver(profileFormSchema),+ const form = useForm<ProfileSchema>({+ resolver: zodResolver(profileSchema),mode: 'onChange',defaultValues: {bio: user.bio,@@ -112,15 +84,19 @@ function ProfileForm({ user }: Props) {name: 'userLinks',});- async function onSubmit(data: ProfileFormValues) {- // TODO: handle errors-- await updateProfile(data);-- toast({- title: 'profile updated',- variant: 'success',- });+ async function onSubmit(data: ProfileSchema) {+ try {+ await updateProfile(data);+ toast({+ title: 'profile updated',+ variant: 'success',+ });+ } catch (error) {+ toast({+ title: 'Could not update profile',+ variant: 'destructive',+ });+ }}return (diff --git a/apps/web/src/app/[locale]/settings/_components/schema.ts b/apps/web/src/app/[locale]/settings/_components/schema.tsnew file mode 100644index 00000000..422d19b2--- /dev/null+++ b/apps/web/src/app/[locale]/settings/_components/schema.ts@@ -0,0 +1,42 @@+import { z } from 'zod';+import { createNoProfanitySchemaWithValidate } from '~/utils/antiProfanityZod';++export const appearanceFormSchema = z.object({+ theme: z.enum(['light', 'dark'], {+ required_error: 'Please select a theme.',+ }),+ font: z.enum(['inter', 'manrope', 'system'], {+ invalid_type_error: 'Select a font',+ required_error: 'Please select a font.',+ }),+});++export type ApperenceFormSchema = z.infer<typeof appearanceFormSchema>;++export const profileSchema = z.object({+ username: z+ .string()+ .min(2, {+ message: 'Username must be at least 2 characters.',+ })+ .max(30, {+ message: 'Username must not be longer than 30 characters.',+ }),+ email: z+ .string({+ required_error: 'Please select an email to display.',+ })+ .email(),+ bio: createNoProfanitySchemaWithValidate((str) => str.max(256)),+ userLinks: z.array(+ z.object({+ id: z.union([z.string(), z.null()]),+ url: z.union([+ createNoProfanitySchemaWithValidate((str) => str.url().max(256)),+ z.literal(''),+ ]),+ }),+ ),+});++export type ProfileSchema = z.infer<typeof profileSchema>;diff --git a/apps/web/src/app/[locale]/settings/_components/settings.action.ts b/apps/web/src/app/[locale]/settings/_components/settings.action.tsindex 7db843bd..4936f98b 100644--- a/apps/web/src/app/[locale]/settings/_components/settings.action.ts+++ b/apps/web/src/app/[locale]/settings/_components/settings.action.ts@@ -3,26 +3,29 @@import { getServerAuthSession } from '@repo/auth/server';import { revalidatePath } from 'next/cache';import { prisma } from '@repo/db';-import type { FormSchema } from '.';+import type { ProfileSchema } from './schema';+import { profileSchema } from './schema';/*** This will only let you update your own profile* @param profileData*/-// TODO: add transactions to this update #GFI-export async function updateProfile(profileData: FormSchema) {+export async function updateProfile(profileData: ProfileSchema) {const session = await getServerAuthSession();// 1. Checks that the user is logged in- if (!session?.user.id) return 'unauthorized';+ if (!session?.user.id) return { error: 'unauthorized' };- // 2. Update the user bio field in the db+ // 2. test schema validation with zod+ profileSchema.parse(profileData);++ // 3. Update the user bio field in the dbawait prisma.user.update({where: { id: session.user.id },data: { bio: profileData.bio },});- // 3. Update the users links in the db if the url is not empty+ // 4. Update the users links in the db if the url is not emptyawait prisma.$transaction(profileData.userLinks.map((link) =>prisma.userLink.upsert({@@ -36,6 +39,8 @@ export async function updateProfile(profileData: FormSchema) {),);+ return { success: true };+// do this after we do the shitrevalidatePath('/settings');}diff --git a/apps/web/src/app/[locale]/settings/_components/new-settings.tsx b/apps/web/src/app/[locale]/settings/_components/settings.tsxsimilarity index 85%rename from apps/web/src/app/[locale]/settings/_components/new-settings.tsxrename to apps/web/src/app/[locale]/settings/_components/settings.tsxindex 9f4b2f51..f16bc728 100644--- a/apps/web/src/app/[locale]/settings/_components/new-settings.tsx+++ b/apps/web/src/app/[locale]/settings/_components/settings.tsx@@ -50,7 +50,7 @@ export const links = [},];-export const NewSettings = ({ user }: Props) => {+export const Settings = ({ user }: Props) => {const path = usePathname();let selectedTabValue: string;if (path === '/settings') {@@ -105,19 +105,22 @@ export const NewSettings = ({ user }: Props) => {)}</div><div className="flex gap-4 pr-6 md:flex-col">- {links.map(({ icon: Icon, name, link, disabled }) => (- <Link href={link} key={name} className="w-full">- <VerticalTabsTrigger- className="flex w-full items-center justify-center gap-3 px-2 md:justify-normal md:px-3"- value={name.toLowerCase()}- key={name}- disabled={disabled}- >- <Icon className="h-4 w-4" />- <span className="hidden md:block">{name}</span>- </VerticalTabsTrigger>- </Link>- ))}+ {links.map(({ icon: Icon, name, link, disabled }) => {+ const Comp = disabled ? 'div' : Link;+ return (+ <Comp href={link} key={name} className="w-full">+ <VerticalTabsTrigger+ className="flex w-full items-center justify-center gap-3 px-2 md:justify-normal md:px-3"+ value={name.toLowerCase()}+ key={name}+ disabled={disabled}+ >+ <Icon className="h-4 w-4" />+ <span className="hidden md:block">{name}</span>+ </VerticalTabsTrigger>+ </Comp>+ );+ })}</div></VerticalTabsList><VerticalTabsContent className="shrink grow space-y-4" value={selectedTabValue}>diff --git a/apps/web/src/app/[locale]/settings/appearance/page.tsx b/apps/web/src/app/[locale]/settings/appearance/page.tsxindex ef4c5701..5dbff5ec 100644--- a/apps/web/src/app/[locale]/settings/appearance/page.tsx+++ b/apps/web/src/app/[locale]/settings/appearance/page.tsx@@ -1,6 +1,6 @@import { getServerAuthSession } from '@repo/auth/server';import { prisma } from '@repo/db';-import { NewSettings } from '../_components/new-settings';+import { Settings } from '../_components/settings';export default async function SettingsPage() {const session = await getServerAuthSession();@@ -34,7 +34,7 @@ export default async function SettingsPage() {return (<>- <NewSettings user={profileData} />+ <Settings user={profileData} /></>);}diff --git a/apps/web/src/app/[locale]/settings/notifications/page.tsx b/apps/web/src/app/[locale]/settings/notifications/page.tsxindex ef4c5701..5dbff5ec 100644--- a/apps/web/src/app/[locale]/settings/notifications/page.tsx+++ b/apps/web/src/app/[locale]/settings/notifications/page.tsx@@ -1,6 +1,6 @@import { getServerAuthSession } from '@repo/auth/server';import { prisma } from '@repo/db';-import { NewSettings } from '../_components/new-settings';+import { Settings } from '../_components/settings';export default async function SettingsPage() {const session = await getServerAuthSession();@@ -34,7 +34,7 @@ export default async function SettingsPage() {return (<>- <NewSettings user={profileData} />+ <Settings user={profileData} /></>);}diff --git a/apps/web/src/app/[locale]/settings/page.tsx b/apps/web/src/app/[locale]/settings/page.tsxindex 715510f8..a4a1e336 100644--- a/apps/web/src/app/[locale]/settings/page.tsx+++ b/apps/web/src/app/[locale]/settings/page.tsx@@ -1,7 +1,7 @@import { getServerAuthSession } from '@repo/auth/server';import { prisma } from '@repo/db';import type { Metadata } from 'next';-import { NewSettings } from './_components/new-settings';+import { Settings } from './_components/settings';import { buildMetaForDefault } from '~/app/metadata';export async function generateMetadata(): Promise<Metadata> {@@ -32,7 +32,7 @@ export default async function SettingsPage() {return (<>- <NewSettings user={profileData} />+ <Settings user={profileData} /></>);}