All checks were successful
Vercel Preview Deployment / Deploy-Preview (push) Successful in 1m38s
67 lines
1.4 KiB
TypeScript
67 lines
1.4 KiB
TypeScript
'use server'
|
|
import { ZodError, z } from 'zod';
|
|
import { db } from '../db/index'
|
|
import { wines } from '../db/schema'
|
|
import { QueryResult } from 'pg';
|
|
|
|
type NewWine = typeof wines.$inferInsert;
|
|
|
|
export type InsertResult = {
|
|
name: string;
|
|
producer: string;
|
|
id: string;
|
|
createdAt: Date;
|
|
updatedAt: Date | null;
|
|
|
|
}[];
|
|
export type Fields = {
|
|
name: FormDataEntryValue | null
|
|
producer: FormDataEntryValue | null;
|
|
}
|
|
|
|
export type FormState = {
|
|
message: string | QueryResult<never>;
|
|
errors: Record<keyof Fields, string> | undefined;
|
|
fieldValues: NewWine;
|
|
}
|
|
|
|
const schema = z.object({
|
|
name: z.string(),
|
|
producer: z.string().uuid(),
|
|
})
|
|
|
|
export const addWine = async (
|
|
prevState: FormState,
|
|
formData: FormData): Promise<FormState> => {
|
|
const newWine: NewWine = {
|
|
name: formData.get('name') as string,
|
|
producer: formData.get('producer') as string
|
|
}
|
|
try {
|
|
schema.parse(newWine)
|
|
|
|
await db.insert(wines).values(newWine);
|
|
return {
|
|
message: 'success',
|
|
errors: undefined,
|
|
fieldValues: {
|
|
name: "",
|
|
producer: ""
|
|
}
|
|
}
|
|
} catch (error) {
|
|
const zodError = error as ZodError;
|
|
const errorMap = zodError.flatten().fieldErrors;
|
|
return {
|
|
message: "error",
|
|
errors: {
|
|
name: errorMap["name"]?.[0] ?? "",
|
|
producer: errorMap["producer"]?.[0] ?? ""
|
|
},
|
|
fieldValues: {
|
|
name: newWine.name,
|
|
producer: newWine.producer
|
|
}
|
|
}
|
|
}
|
|
} |