Files
evidencija-rezija/app/lib/actions.ts

69 lines
1.8 KiB
TypeScript

'use server';
import { z } from 'zod';
import { revalidatePath } from 'next/cache';
import { redirect } from 'next/navigation';
import clientPromise from './mongodb';
import { ObjectId } from 'mongodb';
export type State = {
errors?: {
billName?: string[];
};
message?:string | null;
}
const FormSchema = z.object({
_id: z.string(),
billName: z.string({
invalid_type_error: 'Please select a bill name',
}),
});
const UpdateBill = FormSchema.omit({ _id: true });
export async function updateBill(locationId: string, billId:string, prevState:State, formData: FormData) {
const validatedFields = UpdateBill.safeParse({
billName: formData.get('billName'),
});
// If form validation fails, return errors early. Otherwise, continue...
if(!validatedFields.success) {
console.log("updateBill.validation-error");
return({
errors: validatedFields.error.flatten().fieldErrors,
message: "Missing Fields. Field to Update Bill.",
});
}
const {
billName,
} = validatedFields.data;
// update the bill in the mongodb
const client = await clientPromise;
const db = client.db("rezije");
// find a location with the given locationID
const post = await db.collection<Location>("lokacije").updateOne(
{
_id: locationId // find a location with the given locationID
},
{
$set: {
"bills.$[elem].name": billName,
}
}, {
arrayFilters: [
{ "elem._id": { $eq: new ObjectId(billId) } } // find a bill with the given billID
]
});
console.log("updateBill.success", post);
// clear the cache for the path
revalidatePath('/');
// go to the bill list
redirect('/');
}