first commit
This commit is contained in:
commit
5d6023a8af
52 files changed
+5830
No files matched your search
@@ -0,0 +1,75 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "../lib/prisma";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { z } from "zod";
|
||||
|
||||
// Define the state shape returned to the client
|
||||
export type FormState = {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
errors?: {
|
||||
name?: string[];
|
||||
email?: string[];
|
||||
pass?: string[];
|
||||
};
|
||||
};
|
||||
|
||||
// Zod Validation Schema
|
||||
const UserSchema = z.object({
|
||||
name: z
|
||||
.string({ error: "Name must be a string" })
|
||||
.min(2, { error: "Name must be at least 2 characters" }),
|
||||
email: z.email({ error: "Please enter a valid email address" }), // Direct top-level function
|
||||
pass: z.string().min(6, { error: "Password must be at least 6 characters" }),
|
||||
});
|
||||
|
||||
// --- ADD USER SERVER ACTION ---
|
||||
export async function addUserAction(
|
||||
prevState: FormState,
|
||||
formData: FormData,
|
||||
): Promise<FormState> {
|
||||
// 1. Validate Form Input with Zod
|
||||
const validatedFields = UserSchema.safeParse({
|
||||
name: formData.get("name"),
|
||||
email: formData.get("email"),
|
||||
pass: formData.get("pass"),
|
||||
});
|
||||
|
||||
// If validation fails, return targeted field errors
|
||||
if (!validatedFields.success) {
|
||||
// Map error issues directly to field names
|
||||
const fieldErrors: Record<string, string[]> = {};
|
||||
|
||||
for (const issue of validatedFields.error.issues) {
|
||||
const field = issue.path[0] as string;
|
||||
if (field) {
|
||||
fieldErrors[field] = fieldErrors[field] || [];
|
||||
fieldErrors[field].push(issue.message);
|
||||
}
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
message: "Validation failed. Please check your inputs.",
|
||||
errors: fieldErrors,
|
||||
};
|
||||
}
|
||||
|
||||
const { name, email, pass } = validatedFields.data;
|
||||
|
||||
// 2. Perform Database Mutation
|
||||
try {
|
||||
await prisma.user.create({
|
||||
data: { name, email, password: pass },
|
||||
});
|
||||
|
||||
revalidatePath("/users");
|
||||
return { success: true, message: "User added successfully!" };
|
||||
} catch (error) {
|
||||
console.error("Failed to create user:", error);
|
||||
return {
|
||||
success: false,
|
||||
message: "Failed to create user. Email may already be registered.",
|
||||
};
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user