Skip to content
This repository was archived by the owner on Apr 7, 2024. It is now read-only.

Commit 452fdfe

Browse files
authored
Gracefully handle error when form doesn't validate (#85)
1 parent 5df51b5 commit 452fdfe

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

apps/app/src/app/(authenticated)/new/actions.ts

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,37 @@ const schema = z
1313
.required();
1414

1515
export async function createWorkspace(formData: FormData) {
16-
const { name } = schema.parse({
16+
const validatedFields = schema.safeParse({
1717
name: formData.get("name"),
1818
});
19-
const slug = slugify(name);
19+
20+
// Return early if the form data is invalid
21+
if (!validatedFields.success) {
22+
return {
23+
status: "error",
24+
message:
25+
validatedFields.error.flatten().fieldErrors.name?.join(", ") ??
26+
"Invalid form data",
27+
slug: null,
28+
};
29+
}
30+
31+
const slug = slugify(validatedFields.data.name);
2032

2133
const session = await getServerSession(authOptions);
2234
const userId = session?.user.id;
2335

36+
/**
37+
* This shouldn't happen
38+
*/
2439
if (!userId) {
2540
throw new Error("User not found");
2641
}
2742

2843
try {
2944
const workspace = await db.workspace.create({
3045
data: {
31-
name,
46+
name: validatedFields.data.name,
3247
slug,
3348
members: {
3449
createMany: {

0 commit comments

Comments
 (0)