@@ -3,21 +3,52 @@ import { z } from 'zod';
33import { sql } from '@vercel/postgres' ;
44import { revalidatePath } from 'next/cache' ;
55import { redirect } from 'next/navigation' ;
6+ import { signIn } from '@/auth' ;
7+ import { AuthError } from 'next-auth' ;
68
79const FormSchema = z . object ( {
810 id : z . string ( ) ,
9- customerId : z . string ( ) ,
10- amount : z . coerce . number ( ) , // 将string转为number
11- status : z . enum ( [ 'pending' , 'paid' ] ) ,
11+ customerId : z . string ( {
12+ invalid_type_error : 'Please select a customer.' ,
13+ } ) ,
14+ amount : z . coerce
15+ . number ( )
16+ . gt ( 0 , { message : 'Please enter an amount greater than $0.' } ) ,
17+ // 将string转为number
18+ status : z . enum ( [ 'pending' , 'paid' ] , {
19+ invalid_type_error : 'Please select an invoice status.' ,
20+ } ) ,
1221 date : z . string ( ) ,
1322} ) ;
1423
24+ export type State = {
25+ errors ?: {
26+ customerId ?: string [ ] ;
27+ amount ?: string [ ] ;
28+ status ?: string [ ] ;
29+ } ;
30+ message ?: string | null ;
31+ } ;
32+
1533// 删除 id 和 date 字段
1634const CreateInvoice = FormSchema . omit ( { id : true , date : true } ) ;
1735
1836const UpdateInvoice = FormSchema . omit ( { id : true , date : true } ) ;
1937
20- export async function createInvoice ( formData : FormData ) {
38+ export async function createInvoice ( _ : State , formData : FormData ) {
39+ // Validate form fields using Zod
40+ const validatedFields = CreateInvoice . safeParse ( {
41+ customerId : formData . get ( 'customerId' ) ,
42+ amount : formData . get ( 'amount' ) ,
43+ status : formData . get ( 'status' ) ,
44+ } ) ;
45+ // If form validation fails, return errors early. Otherwise, continue.
46+ if ( ! validatedFields . success ) {
47+ return {
48+ errors : validatedFields . error . flatten ( ) . fieldErrors ,
49+ message : 'Missing Fields. Failed to Create Invoice.' ,
50+ } ;
51+ }
2152 const { customerId, amount, status } = CreateInvoice . parse ( {
2253 customerId : formData . get ( 'customerId' ) ,
2354 amount : formData . get ( 'amount' ) ,
@@ -88,3 +119,22 @@ export async function deleteInvoice(id: string) {
88119 */
89120 revalidatePath ( '/dashboard/invoices' ) ;
90121}
122+
123+ export async function authenticate (
124+ prevState : string | undefined ,
125+ formData : FormData ,
126+ ) {
127+ try {
128+ await signIn ( 'credentials' , formData ) ;
129+ } catch ( error ) {
130+ if ( error instanceof AuthError ) {
131+ switch ( error . type ) {
132+ case 'CredentialsSignin' :
133+ return 'Invalid credentials.' ;
134+ default :
135+ return 'Something went wrong.' ;
136+ }
137+ }
138+ throw error ;
139+ }
140+ }
0 commit comments