cloudflare/vinext
Publicmirrored from https://github.com/cloudflare/vinextAvailable
tests/fixtures/app-basic/app/actions/actions.ts
67lines · modecode
| 1 | "use server"; |
| 2 | |
| 3 | import { redirect } from "next/navigation"; |
| 4 | |
| 5 | // Simple in-memory counter for testing server actions |
| 6 | let likeCount = 0; |
| 7 | |
| 8 | export async function incrementLikes(): Promise<number> { |
| 9 | likeCount++; |
| 10 | return likeCount; |
| 11 | } |
| 12 | |
| 13 | export async function getLikes(): Promise<number> { |
| 14 | return likeCount; |
| 15 | } |
| 16 | |
| 17 | export async function addMessage(formData: FormData): Promise<string> { |
| 18 | const message = formData.get("message") as string; |
| 19 | return `Received: ${message}`; |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * Server action that calls redirect() — should result in a redirect response. |
| 24 | */ |
| 25 | export async function redirectAction(): Promise<void> { |
| 26 | redirect("/about"); |
| 27 | } |
| 28 | |
| 29 | /** |
| 30 | * Server action that throws a regular error. |
| 31 | */ |
| 32 | export async function errorAction(): Promise<string> { |
| 33 | throw new Error("Action failed intentionally"); |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Server action that returns complex data (object, array, Date). |
| 38 | */ |
| 39 | export async function complexDataAction(): Promise<{ |
| 40 | items: string[]; |
| 41 | count: number; |
| 42 | nested: { key: string }; |
| 43 | }> { |
| 44 | return { |
| 45 | items: ["alpha", "beta", "gamma"], |
| 46 | count: 3, |
| 47 | nested: { key: "value" }, |
| 48 | }; |
| 49 | } |
| 50 | |
| 51 | /** |
| 52 | * Server action for useActionState — accepts previous state and formData, |
| 53 | * returns new state. This is the idiomatic Next.js 15+ pattern. |
| 54 | */ |
| 55 | export async function counterAction( |
| 56 | prevState: { count: number }, |
| 57 | formData: FormData, |
| 58 | ): Promise<{ count: number }> { |
| 59 | const action = formData.get("action") as string; |
| 60 | if (action === "increment") { |
| 61 | return { count: prevState.count + 1 }; |
| 62 | } |
| 63 | if (action === "decrement") { |
| 64 | return { count: prevState.count - 1 }; |
| 65 | } |
| 66 | return prevState; |
| 67 | } |
| 68 | |