generated from egoist/ts-lib-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathactions.ts
36 lines (31 loc) · 948 Bytes
/
actions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { typedAction, ActionError } from "@teamreflex/typed-action"
import { z } from "zod"
import { redirect } from "next/navigation"
const createTeamSchema = z.object({
name: z.string().min(3),
})
/**
* You might have some custom validation logic that you want to run on the server.
* So you can throw an `ActionError` to return a custom error message to the client.
*/
export async function createTeam(prev: unknown, form: FormData) {
form.set("slug", slugify(form.get("name")))
return typedAction({
form,
schema: createTeamSchema,
onValidate: async ({ input }) => {
if (slugIsTaken(input.slug)) {
throw new ActionError({
result: "error",
validationErrors: {
slug: "This slug is already taken",
},
})
}
return await db.insert(teams).values(input)
},
postValidate: ({ output }) => {
redirect(`/team/${output.slug}`)
},
})
}