All checks were successful
Vercel Production Deployment / Deploy-Production (push) Successful in 1m7s
44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
"use server";
|
|
|
|
import { revalidatePath } from "next/cache";
|
|
import { db } from "../db";
|
|
import { countries } from "../db/schema";
|
|
import * as z from "zod";
|
|
|
|
const schema = z.object({
|
|
name: z.string().min(1, { message: "Name is required" }),
|
|
});
|
|
|
|
export async function addCountry(prevstate: any, formData: FormData) {
|
|
const name = formData.get("name") as string;
|
|
const newCountry = schema.safeParse({ name: name.toLowerCase() });
|
|
|
|
if (!newCountry.success) {
|
|
const errors = newCountry.error.issues.map((issue) =>
|
|
console.log(issue.message),
|
|
);
|
|
return {
|
|
message: errors,
|
|
data: newCountry.data,
|
|
};
|
|
} else {
|
|
const confirmCreate = await db
|
|
.insert(countries)
|
|
.values(newCountry.data)
|
|
.onConflictDoNothing()
|
|
.returning({ name: countries.name });
|
|
if (!confirmCreate[0]) {
|
|
return {
|
|
message: `${newCountry.data.name} already exists`,
|
|
data: newCountry.data,
|
|
};
|
|
} else {
|
|
revalidatePath("/");
|
|
return {
|
|
message: `${confirmCreate[0].name} added`,
|
|
data: newCountry.data,
|
|
};
|
|
}
|
|
}
|
|
}
|