safe-action-advanced
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesenext-safe-action Advanced Features
next-safe-action 高级功能
Overview
概述
| Feature | Use Case |
|---|---|
| Bind arguments | Pass extra args to actions via |
| Metadata | Attach typed metadata to actions for use in middleware |
| Framework errors | Handle redirect, notFound, forbidden, unauthorized in actions |
| Type utilities | Infer types from action functions and middleware |
| 功能 | 使用场景 |
|---|---|
| 绑定参数 | 通过 |
| 元数据 | 为actions附加带类型的元数据,供中间件使用 |
| 框架错误 | 在actions中处理redirect、notFound、forbidden、unauthorized等框架错误 |
| 类型工具 | 从action函数和中间件中推断类型 |
Server-Level Action Callbacks
服务器级别Action回调函数
The second argument to accepts callbacks that run on the server (not client-side hooks):
.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 }) => {
// 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 () — server callbacks run in the Node.js runtime, hook callbacks run in the browser.
useAction({ onSuccess }).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);
},
}
);这些回调函数与钩子回调()不同——服务器回调在Node.js运行时中运行,钩子回调在浏览器中运行。
useAction({ onSuccess })throwServerError
throwServerError
Re-throw server errors instead of returning them as :
result.serverErrorts
export const myAction = actionClient
.inputSchema(schema)
.action(serverCodeFn, {
throwServerError: true,
// The handled server error (return of handleServerError) is thrown
});重新抛出服务器错误,而非将其作为返回:
result.serverErrorts
export const myAction = actionClient
.inputSchema(schema)
.action(serverCodeFn, {
throwServerError: true,
// 处理后的服务器错误(handleServerError的返回值)会被抛出
});