Skip to content

Function: createSafeAction()

createSafeAction<Input, ExceptionHandler>(options): SafeActionBuilder<Input, never, never, Ctx, false, ExceptionHandler>

Defined in: packages/action/src/safe.ts:46

Creates a new safe action builder for composing middleware and action functions that return Results.

Unlike createAction, it'ss designed to work with functions that return Result<T, E> types, providing type-safe error handling without exceptions.

Type Parameters

Input

Input = never

The input type that will be passed to the action when executed.

ExceptionHandler

ExceptionHandler extends (ex) => UnknownResult = (ex) => Err<ThrownActionError>

Function type that converts exceptions to Result types. Should return Ok<T> or Err<E>.

Parameters

options

Configuration options for the safe action

onThrow?

ExceptionHandler

Optional custom exception handler for thrown exceptions

Returns

SafeActionBuilder<Input, never, never, Ctx, false, ExceptionHandler>

A new SafeActionBuilder instance

Example

typescript
const action = createAction<{ token: string }>({ onThrow: console.error })
  .with(async ({ input }) => {
    const session = await getSession(input.token);
    if (!session) return err('SESSION_NOT_FOUND');
    return next({ session });
  })
  .with(async ({ ctx }) => {
    const user = await getUser(ctx.session.userId);
    if (!user) return err('USER_NOT_FOUND');
    return next({ user });
  })
  .do(async ({ ctx }) => {
    const blogPosts = await getBlogPosts(ctx.user.id);
    return ok(blogPosts ?? []);
  });

const result = await action({ token: 'test' });

if (isOk(result)) {
  console.log(result.data); // BlogPost[]
} else {
  console.log(result.error); // "SESSION_NOT_FOUND" | "USER_NOT_FOUND"
}