nextjs/dashboard-app-course/app/lib/actions.ts

118 lines
No EOL
3.1 KiB
TypeScript

'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import postgres from 'postgres';
import { signIn } from '@/auth';
import { AuthError } from 'next-auth';
const sql = postgres(process.env.POSTGRES_URL!, {ssl: 'require'});
export async function authenticate(
prevState: string | undefined,
formData: FormData,
){
try{
await signIn('credentials', formData)
} catch(error){
if(error instanceof AuthError){
switch(error.type){
case 'CredentialsSignIn':
return 'Invalid credentials.';
default:
return 'Something went wrong.';
}
}
throw error;
}
}
const FormSchema = z.object({
id: z.string(),
customerId: z.string({
invalid_type_error: 'Please select a customer.',
}),
amount: z.coerce.number().gt(0, { message: 'Please enter an amount greater than $0.'}),
status: z.enum(['pending', 'paid'], {
invalid_type_error: 'Please select an invoice status.',
}),
date: z.string(),
});
const CreateInvoice = FormSchema.omit({id: true, date: true});
export type State = {
errors?: {
customerId?: string[];
amount?: string[];
status?: string[];
};
message?: string | null;
};
export async function createInvoice(prevState: State, formData: FormData){
const validateFields = CreateInvoice.safeParse({
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
});
if(!validateFields.success){
return{
errors: validateFields.error.flatten().fieldErrors,
message: 'Missing fields. Failed to create invoice.',
}
}
const { customerId, amount, status } = validateFields.data;
const amountInCents = amount * 100;
const date = new Date().toISOString().split('T')[0];
try{
await sql`
INSERT INTO invoices (customer_Id, amount, status, date)
VALUES (${customerId}, ${amountInCents}, ${status}, ${date})
`;
} catch(error){
console.error(error);
}
revalidatePath('/dashboard/invoices');
redirect('/dashboard/invoices');
}
const UpdateInvoice = FormSchema.omit({id: true, date: true});
export async function updateInvoice(id: string, formData: FormData){
const { customerId, amount, status } = UpdateInvoice.parse({
customerId: formData.get('customerId'),
amount: formData.get('amount'),
status: formData.get('status'),
});
const amountInCents = amount * 100;
try{
await sql`
UPDATE invoices
SET customer_id = ${customerId}, amount = ${amountInCents}, status = ${status}
WHERE id = ${id}
`;
} catch(error){
console.error(error);
}
revalidatePath('/dashboard/invoices');
redirect('/dashboard/invoices');
}
export async function deleteInvoice(id: string){
try{
await sql`DELETE FROM invoices WHERE id = ${id}`;
} catch (error){
console.error(error);
}
revalidatePath('/dashboard/invoices');
}