VergeStackVergeStack

Create Action

The createAction function is used for defining actions typesafe and runtime-validated actions. It provides the ability to define input and output schemas in addition to the action handler. Server actions are best suited for mutations originating from your own application.

Usage

Here's an example of using createAction to define a server action:

actions.ts
'use server';
 
import { createAction } from '@vergestack/api';
import { z } from 'zod';
 
export const greetingAction = createAction()
  .input(z.string())
  .output(z.string())
  .handler(async ({ input }) => {
    return `Hello, ${input}!`;
  });

Please ensure the file is annotated with the 'use server' directive. All exports within this file will be transformed into publicly facing endpoints. Learn more here.

API

FunctionDescription
createAction()Creates a new action creator instance.
.input(schema: ZodType)Defines the input schema for the action using a Zod schema.
.output(schema: ZodType)Defines the output schema for the action using a Zod schema.
.handler(fn: (input: InputType) => Promise<OutputType>)Defines the handler function for the action. This function receives the validated input and should return a promise that resolves to the output matching the defined output schema.

Detailed Example

'use server';
 
import { createAction } from '@vergestack/api';
import { z } from 'zod';
 
export const greetingAction = createAction()
  .input(
    z.object({
      name: z.string().min(1, 'Name is required')
    })
  )
  .output(
    z.object({
      message: z.string()
    })
  )
  .handler(async ({ input }) => {
    return {
      message: `Hello, ${input.name}!`
    };
  });

Testing

You can easily test actions by calling them directly from a testing framework of your choice. Here is an example with Jest:

index.test.ts
import { greetingAction } from './actions.ts';
import { StatusCodes } from 'http-status-codes';
import { z } from 'zod';
 
test('greetingAction successful response', async () => {
  // references greetingAction defined under the "Usage" section
  const result = await greetingAction('World');
 
  expect(result.status).toBe(StatusCodes.OK);
  expect(result.data).toBe('Hello, World!');
  expect(result.errors).toBeUndefined();
});

On this page