safe-action-advanced

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

next-safe-action Advanced Features

next-safe-action 高级功能

Overview

概述

FeatureUse Case
Bind argumentsPass extra args to actions via
.bind()
(e.g., resource IDs)
MetadataAttach typed metadata to actions for use in middleware
Framework errorsHandle redirect, notFound, forbidden, unauthorized in actions
Type utilitiesInfer types from action functions and middleware
功能使用场景
绑定参数通过
.bind()
向actions传递额外参数(例如资源ID)
元数据为actions附加带类型的元数据,供中间件使用
框架错误在actions中处理redirect、notFound、forbidden、unauthorized等框架错误
类型工具从action函数和中间件中推断类型

Server-Level Action Callbacks

服务器级别Action回调函数

The second argument to
.action()
accepts callbacks that run on the server (not client-side hooks):
ts
export const createPost = authActionClient
  .inputSchema(schema)
  .action(
    async ({ parsedInput, ctx }) => {
      const post = await db.post.create(parsedInput);
      return post;
    },
    {
      onSuccess: async ({ data, parsedInput, ctx, metadata, clientInput }) => {
        // Runs on the server after successful execution
        await invalidateCache("posts");
      },
      onError: async ({ error, metadata, ctx, clientInput, bindArgsClientInputs }) => {
        // error: { serverError?, validationErrors? }
        await logError(error);
      },
      onSettled: async ({ result }) => {
        // Always runs
        await recordMetrics(result);
      },
      onNavigation: async ({ navigationKind }) => {
        // Runs when a framework error (redirect, notFound, etc.) occurs
        console.log("Navigation:", navigationKind);
      },
    }
  );
These are distinct from hook callbacks (
useAction({ onSuccess })
) — server callbacks run in the Node.js runtime, hook callbacks run in the browser.
.action()
的第二个参数接受在服务器端运行的回调函数(而非客户端钩子):
ts
export const createPost = authActionClient
  .inputSchema(schema)
  .action(
    async ({ parsedInput, ctx }) => {
      const post = await db.post.create(parsedInput);
      return post;
    },
    {
      onSuccess: async ({ data, parsedInput, ctx, metadata, clientInput }) => {
        // 成功执行后在服务器端运行
        await invalidateCache("posts");
      },
      onError: async ({ error, metadata, ctx, clientInput, bindArgsClientInputs }) => {
        // error: { serverError?, validationErrors? }
        await logError(error);
      },
      onSettled: async ({ result }) => {
        // 无论成功失败都会运行
        await recordMetrics(result);
      },
      onNavigation: async ({ navigationKind }) => {
        // 当出现框架错误(redirect、notFound等)时运行
        console.log("Navigation:", navigationKind);
      },
    }
  );
这些回调函数与钩子回调(
useAction({ onSuccess })
)不同——服务器回调在Node.js运行时中运行,钩子回调在浏览器中运行。

throwServerError

throwServerError

Re-throw server errors instead of returning them as
result.serverError
:
ts
export const myAction = actionClient
  .inputSchema(schema)
  .action(serverCodeFn, {
    throwServerError: true,
    // The handled server error (return of handleServerError) is thrown
  });
重新抛出服务器错误,而非将其作为
result.serverError
返回:
ts
export const myAction = actionClient
  .inputSchema(schema)
  .action(serverCodeFn, {
    throwServerError: true,
    // 处理后的服务器错误(handleServerError的返回值)会被抛出
  });