@@ -3,21 +3,52 @@ import { z } from 'zod';
3
3
import { sql } from '@vercel/postgres' ;
4
4
import { revalidatePath } from 'next/cache' ;
5
5
import { redirect } from 'next/navigation' ;
6
+ import { signIn } from '@/auth' ;
7
+ import { AuthError } from 'next-auth' ;
6
8
7
9
const FormSchema = z . object ( {
8
10
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
+ } ) ,
12
21
date : z . string ( ) ,
13
22
} ) ;
14
23
24
+ export type State = {
25
+ errors ?: {
26
+ customerId ?: string [ ] ;
27
+ amount ?: string [ ] ;
28
+ status ?: string [ ] ;
29
+ } ;
30
+ message ?: string | null ;
31
+ } ;
32
+
15
33
// 删除 id 和 date 字段
16
34
const CreateInvoice = FormSchema . omit ( { id : true , date : true } ) ;
17
35
18
36
const UpdateInvoice = FormSchema . omit ( { id : true , date : true } ) ;
19
37
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
+ }
21
52
const { customerId, amount, status } = CreateInvoice . parse ( {
22
53
customerId : formData . get ( 'customerId' ) ,
23
54
amount : formData . get ( 'amount' ) ,
@@ -88,3 +119,22 @@ export async function deleteInvoice(id: string) {
88
119
*/
89
120
revalidatePath ( '/dashboard/invoices' ) ;
90
121
}
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