Skip to content

操作 API 参考

Added in: astro@4.15.0

操作可帮助你构建可从客户端代码和 HTML 表单调用的类型安全后端。定义和调用操作的所有实用程序都由 astro:actions 模块公开。有关示例和使用说明,请参阅 请参阅“操作”指南

¥Actions help you build a type-safe backend you can call from client code and HTML forms. All utilities to define and call actions are exposed by the astro:actions module. For examples and usage instructions, see the Actions guide.

¥Imports from astro:actions

import {
ACTION_QUERY_PARAMS,
ActionError,
actions,
defineAction,
getActionContext,
getActionPath,
isActionError,
isInputError,
} from 'astro:actions';

类型:({ accept, input, handler }) => ActionClient

¥Type: ({ accept, input, handler }) => ActionClient

用于在 src/actions/index.ts 文件中定义新操作的实用程序。这接受包含要运行的服务器逻辑的 handler() 函数,以及可选的 input 属性以在运行时验证输入参数。

¥A utility to define new actions in the src/actions/index.ts file. This accepts a handler() function containing the server logic to run, and an optional input property to validate input parameters at runtime.

src/actions/index.ts
import { defineAction } from 'astro:actions';
import { z } from 'astro:schema';
export const server = {
getGreeting: defineAction({
input: z.object({
name: z.string(),
}),
handler: async (input, context) => {
return `Hello, ${input.name}!`
}
})
}

¥handler() property

类型:(input: TInputSchema, context: ActionAPIContext) => TOutput | Promise<TOutput>

¥Type: (input: TInputSchema, context: ActionAPIContext) => TOutput | Promise<TOutput>

一个必需的函数,包含在调用操作时要运行的服务器逻辑。handler() 返回的数据会自动序列化并发送给调用者。

¥A required function containing the server logic to run when the action is called. Data returned from the handler() is automatically serialized and sent to the caller.

handler() 以用户输入作为其第一个参数进行调用。如果设置了 input 验证器,则在将用户输入传递给处理程序之前,将对其进行验证。第二个参数是 Astro context 的子集对象

¥The handler() is called with user input as its first argument. If an input validator is set, the user input will be validated before being passed to the handler. The second argument is a subset of Astro’s context object.

使用 贬值库 解析返回值。这支持 JSON 值和 Date()Map()Set()URL() 的实例。

¥Return values are parsed using the devalue library. This supports JSON values and instances of Date(), Map(), Set(), and URL().

¥input validator

类型:ZodType | undefined

¥Type: ZodType | undefined

一个可选属性,接受一个 Zod 验证器(例如 Zod 对象、Zod 可区分联合体),用于在运行时验证处理程序输入。如果操作验证失败,则返回 BAD_REQUEST 错误,并且不会调用 handler

¥An optional property that accepts a Zod validator (e.g. Zod object, Zod discriminated union) to validate handler inputs at runtime. If the action fails to validate, a BAD_REQUEST error is returned and the handler is not called.

如果省略 inputhandler 将接收 JSON 请求的 unknown 类型输入和表单请求的 FormData 类型输入。

¥If input is omitted, the handler will receive an input of type unknown for JSON requests and type FormData for form requests.

¥accept property

类型:"form" | "json"
默认:json

¥Type: "form" | "json"
Default: json

定义操作所需的格式:

¥Defines the format expected by an action:

  • 当你的操作接受 FormData 时,请使用 form

  • 所有其他情况下,请使用默认值 json

当你的操作接受表单输入时,z.object() 验证器会自动将 FormData 解析为类型化对象。支持所有 Zod 验证器以验证你的输入。

¥When your action accepts form inputs, the z.object() validator will automatically parse FormData to a typed object. All Zod validators are supported to validate your inputs.

Learn about using validators with form inputs in the Actions guide, including example usage and special input handling.

类型:Record<string, ActionClient>

¥Type: Record<string, ActionClient>

一个包含所有操作的对象,操作名称作为键,并关联一个用于调用该操作的函数。

¥An object containing all your actions with the action name as key associated to a function to call this action.

src/pages/index.astro
---
---
<script>
import { actions } from 'astro:actions';
async () => {
const { data, error } = await actions.myAction({ /* ... */ });
}
</script>

为了使 Astro 识别此属性,你可能需要重启开发服务器或 运行 astro sync 命令s + enter)。

¥In order for Astro to recognize this property, you may need to restart the dev server or run the astro sync command (s + enter).

类型:(error?: unknown) => boolean

¥Type: (error?: unknown) => boolean

用于检查 一个 ActionError 是否为输入验证错误的实用程序。当 input 验证器是 z.object() 时,输入错误包含一个 fields 对象,其中的错误消息按名称分组。

¥A utility used to check whether an ActionError is an input validation error. When the input validator is a z.object(), input errors include a fields object with error messages grouped by name.

See the form input errors guide for more on using isInputError().

类型:(error?: unknown) => boolean

¥Type: (error?: unknown) => boolean

用于检查你的操作是否在 处理程序属性 中引发了 一个 ActionError 的实用程序。这对于缩小通用错误类型范围非常有用。

¥A utility to check whether your action raised an ActionError within the handler property. This is useful when narrowing the type of a generic error.

src/pages/index.astro
---
---
<script>
import { isActionError, actions } from 'astro:actions';
async () => {
const { data, error } = await actions.myAction({ /* ... */ });
if (isActionError(error)) {
// Handle action-specific errors
console.log(error.code);
}
}
</script>

ActionError() 构造函数用于创建由操作 handler 抛出的错误。这接受一个描述所发生错误的 code 属性(例如:"UNAUTHORIZED"),以及一个包含更多详细信息的可选 message 属性。

¥The ActionError() constructor is used to create errors thrown by an action handler. This accepts a code property describing the error that occurred (example: "UNAUTHORIZED"), and an optional message property with further details.

以下示例在用户未登录时创建一个新的 ActionError

¥The following example creates a new ActionError when the user is not logged in:

src/actions/index.ts
import { defineAction, ActionError } from "astro:actions";
export const server = {
getUserOrThrow: defineAction({
accept: 'form',
handler: async (_, { locals }) => {
if (locals.user?.name !== 'florian') {
throw new ActionError({
code: 'UNAUTHORIZED',
message: 'Not logged in',
});
}
return locals.user;
},
}),
}

你还可以使用 ActionError 来缩小处理操作结果时的错误类型范围:

¥You can also use ActionError to narrow the error type when handling the results of an action:

src/pages/index.astro
---
---
<script>
import { ActionError, actions } from 'astro:actions';
async () => {
const { data, error } = await actions.myAction({ /* ... */ });
if (error instanceof ActionError) {
// Handle action-specific errors
console.log(error.code);
}
}
</script>

类型:ActionErrorCode

¥Type: ActionErrorCode

定义 HTTP 状态码 的人类可读版本。

¥Defines a human-readable version of an HTTP status code.

类型:string

¥Type: string

一个可选属性,用于描述错误(例如 “用户必须登录。”)。

¥An optional property to describe the error (e.g. “User must be logged in.”).

类型:string

¥Type: string

一个可选属性,用于传递堆栈跟踪。

¥An optional property to pass the stack trace.

类型:(context: APIContext) => AstroActionContext

¥Type: (context: APIContext) => AstroActionContext

Added in: astro@5.0.0

一个从中间件处理程序调用的函数,用于检索有关入站操作请求的信息。此方法返回一个 action 对象,其中包含请求信息、一个 deserializeActionResult() 方法以及用于以编程方式设置 Astro.getActionResult() 返回值的 setActionResult()serializeActionResult() 函数。

¥A function called from your middleware handler to retrieve information about inbound action requests. This returns an action object with information about the request, a deserializeActionResult() method, and the setActionResult() and serializeActionResult() functions to programmatically set the value returned by Astro.getActionResult().

getActionContext() 允许你以编程方式使用中间件获取和设置操作结果,允许你持久保存 HTML 表单的操作结果、通过添加的安全检查来控制操作请求等等。

¥getActionContext() lets you programmatically get and set action results using middleware, allowing you to persist action results from HTML forms, gate action requests with added security checks, and more.

src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getActionContext } from 'astro:actions';
export const onRequest = defineMiddleware(async (context, next) => {
const { action, setActionResult, serializeActionResult } = getActionContext(context);
if (action?.calledFrom === 'form') {
const result = await action.handler();
setActionResult(action.name, serializeActionResult(result));
}
return next();
});

类型:{ calledFrom: “rpc” | “form”; name: string; handler: () => Promise<SafeResult>; } | undefined

¥Type: { calledFrom: “rpc” | “form”; name: string; handler: () => Promise<SafeResult>; } | undefined

一个包含入站操作请求信息的对象。它可通过 getActionContext() 获取,并提供操作 namehandler,以及该操作是从客户端 RPC 函数(例如 actions.newsletter())还是 HTML 表单操作调用的。

¥An object containing information about an inbound action request. It is available from getActionContext(), and provides the action name, handler, and whether the action was called from a client-side RPC function (e.g. actions.newsletter()) or an HTML form action.

src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getActionContext } from 'astro:actions';
export const onRequest = defineMiddleware(async (context, next) => {
const { action, setActionResult, serializeActionResult } = getActionContext(context);
if (action?.calledFrom === 'rpc' && action.name.startsWith('private')) {
// Check for a valid session token
}
// ...
});

类型:"rpc" | "form"

¥Type: "rpc" | "form"

操作是通过 RPC 函数还是 HTML 表单操作调用的。

¥Whether an action was called using an RPC function or an HTML form action.

类型:string

¥Type: string

操作名称。用于在重定向期间跟踪操作结果的来源。

¥The name of the action. Useful to track the source of an action result during a redirect.

类型:() => Promise<SafeResult>

¥Type: () => Promise<SafeResult>

一个用于以编程方式调用操作以获取结果的方法。

¥A method to programmatically call an action to get the result.

类型:(actionName: string, actionResult: SerializedActionResult) => void

¥Type: (actionName: string, actionResult: SerializedActionResult) => void

用于以编程方式设置中间件中 Astro.getActionResult() 返回值的函数。它传递了由 serializeActionResult() 序列化的操作名称和操作结果。从中间件调用此函数将禁用 Astro 自身的操作结果处理。

¥A function to programmatically set the value returned by Astro.getActionResult() in middleware. It is passed the action name and an action result serialized by serializeActionResult(). Calling this function from middleware will disable Astro’s own action result handling.

当从 HTML 表单调用操作以持久保存和加载会话结果时,这很有用。

¥This is useful when calling actions from an HTML form to persist and load results from a session.

src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getActionContext } from 'astro:actions';
export const onRequest = defineMiddleware(async (context, next) => {
const { action, setActionResult, serializeActionResult } = getActionContext(context);
if (action?.calledFrom === 'form') {
const result = await action.handler();
// ... handle the action result
setActionResult(action.name, serializeActionResult(result));
}
return next();
});
See the advanced sessions guide for a sample implementation using Netlify Blob.

类型:(res: SafeResult) => SerializedActionResult

¥Type: (res: SafeResult) => SerializedActionResult

将操作结果序列化为 JSON 以便持久化。这是正确处理非 JSON 返回值(如 MapDate)以及 ActionError 对象所必需的。

¥Serializes an action result to JSON for persistence. This is required to properly handle non-JSON return values like Map or Date as well as the ActionError object.

在序列化要传递给 setActionResult() 的操作结果时调用此函数:

¥Call this function when serializing an action result to be passed to setActionResult():

src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getActionContext } from 'astro:actions';
export const onRequest = defineMiddleware(async (context, next) => {
const { action, setActionResult, serializeActionResult } = getActionContext(context);
if (action) {
const result = await action.handler();
setActionResult(action.name, serializeActionResult(result));
}
// ...
});

类型:(res: SerializedActionResult) => SafeResult

¥Type: (res: SerializedActionResult) => SafeResult

撤销 serializeActionResult() 的效果,并将操作结果恢复到其原始状态。这对于访问序列化操作结果上的 dataerror 对象很有用。

¥Reverses the effect of serializeActionResult() and returns an action result to its original state. This is useful to access the data and error objects on a serialized action result.

类型:(action: ActionClient) => string

¥Type: (action: ActionClient) => string

Added in: astro@5.1.0

一个接受操作并返回 URL 路径的实用程序,以便你可以直接将操作调用作为 fetch() 操作执行。这允许你在调用操作时提供详细信息,例如自定义标头。然后,你可以根据需要 处理自定义格式的返回数据,就像你直接调用操作一样。

¥A utility that accepts an action and returns a URL path so you can execute an action call as a fetch() operation directly. This allows you to provide details such as custom headers when you call your action. Then, you can handle the custom-formatted returned data as needed, just as if you had called an action directly.

此示例显示如何调用传递 Authorization 标头和 keepalive 选项的已定义 like 操作:

¥This example shows how to call a defined like action passing the Authorization header and the keepalive option:

src/components/my-component.astro
<script>
import { actions, getActionPath } from 'astro:actions'
await fetch(getActionPath(actions.like), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer YOUR_TOKEN'
},
body: JSON.stringify({ id: 'YOUR_ID' }),
keepalive: true
})
</script>

此示例显示如何使用 sendBeacon API 调用相同的 like 操作:

¥This example shows how to call the same like action using the sendBeacon API:

src/components/my-component.astro
<script>
import { actions, getActionPath } from 'astro:actions'
navigator.sendBeacon(
getActionPath(actions.like),
new Blob([JSON.stringify({ id: 'YOUR_ID' })], {
type: 'application/json'
})
)
</script>

类型:{ actionName: string, actionPayload: string }

¥Type: { actionName: string, actionPayload: string }

一个包含 Astro 在处理表单操作提交时内部使用的查询参数名称的对象。

¥An object containing the query parameter names used internally by Astro when handling form action submissions.

当你使用操作提交表单时,以下查询参数会添加到 URL 中以跟踪操作调用:

¥When you submit a form using an action, the following query parameters are added to the URL to track the action call:

  • actionName - 包含被调用操作名称的查询参数

  • actionPayload - 包含序列化表单数据的查询参数

当需要在表单提交后清理 URL 时,此常量非常有用。例如,你可能希望在重定向期间删除与操作相关的查询参数:

¥This constant can be useful when you need to clean up URLs after a form submission. For example, you might want to remove action-related query parameters during a redirect:

src/pages/api/contact.ts
import type { APIRoute } from "astro";
import { ACTION_QUERY_PARAMS } from 'astro:actions'
export const GET: APIRoute = ({ params, request }) => {
const link = request.url.searchParams;
link.delete(ACTION_QUERY_PARAMS.actionName);
link.delete(ACTION_QUERY_PARAMS.actionPayload);
return redirect(link, 303);
};

¥astro:actions types

import type {
ActionAPIContext,
ActionClient,
ActionErrorCode,
ActionInputSchema,
ActionReturnType,
SafeResult,
} from 'astro:actions';

Astro 上下文对象 的子集。以下属性不可用:callActiongetActionResultpropsredirect

¥A subset of the Astro context object. The following properties are not available: callAction, getActionResult, props, and redirect.

类型:

¥Types:

  • (input?: any) => Promise<SafeResult>
  • { queryString?: string; orThrow: (input?: any) => Promise<Awaited<TOutput>>; }

表示要在客户端调用的操作。你可以将其用作接受输入数据并返回包含操作结果或验证错误的 SafeResult 对象 对象的 Promise 的函数。

¥Represents an action to be called on the client. You can use it as a function that accepts input data and returns a Promise with a SafeResult object containing the action result or validation errors.

以下示例展示了如何在递增点赞数失败时使用 if 语句进行错误处理:

¥The following example shows how you can provide error handling with an if statement when incrementing the like count fails:

src/pages/posts/post-1.astro
---
---
<!-- your template -->
<script>
import { actions } from 'astro:actions';
const post = document.querySelector('article');
const button = document.querySelector('button');
button?.addEventListener('click', async () => {
const { data: updatedLikes, error } = await actions.likePost({ postId: post?.id });
if (error) {
/* handle errors */
}
})
</script>

或者,你可以将其用作对象,从而访问 queryString 和另一种 orThrow() 方法。

¥Alternatively, you can use it as an object giving you access to the queryString and an alternative orThrow() method.

¥queryString property

类型:string

¥Type: string

可用于构建表单操作 URL 的操作字符串表示形式。当你的表单组件在多个位置使用,但需要在提交时重定向到不同的 URL 时,此功能非常有用。

¥A string representation of the action that can be used to construct form action URLs. This can be useful when your form component is used in multiple places but you need to redirect to a different URL on submit.

以下示例使用 queryString 语句构造一个 URL,该 URL 将通过自定义属性传递给表单的 action 属性:

¥The following example uses queryString to construct a URL that will be passed to the form action attribute through a custom prop:

src/pages/postal-service.astro
---
import { actions } from 'astro:actions';
import FeedbackForm from "../components/FeedbackForm.astro";
const feedbackUrl = new URL('/feedback', Astro.url);
feedbackUrl.search = actions.myAction.queryString;
---
<FeedbackForm sendTo={feedbackUrl.pathname} />

¥orThrow() property

类型:(input?: any) => Promise<Awaited<TOutput>>

¥Type: (input?: any) => Promise<Awaited<TOutput>>

一个在失败时抛出错误而不是返回错误信息的方法。这对于需要异常处理而不是错误处理非常有用。

¥A method that throws an error on failure instead of returning the errors. This is useful when you want exceptions rather than error handling.

以下示例使用 orThrow() 语句在递增点赞数失败时跳过错误处理:

¥The following example uses orThrow() to skip error handling when incrementing the like count fails:

src/pages/posts/post-1.astro
---
---
<!-- your template -->
<script>
import { actions } from 'astro:actions';
const post = document.querySelector('article');
const button = document.querySelector('button');
button?.addEventListener('click', async () => {
const updatedLikes = await actions.likePost.orThrow({ postId: post?.id });
})
</script>

类型:string

¥Type: string

使用以下划线分隔的大写字符串表示的人类可读版本的标准 HTTP 状态代码 由 IANA 定义 的并集类型(例如 BAD_REQUESTPAYLOAD_TOO_LARGE)。

¥A union type of standard HTTP status codes defined by IANA using the human-readable versions as uppercase strings separated by an underscore (e.g. BAD_REQUEST or PAYLOAD_TOO_LARGE).

类型:ZodType

¥Type: ZodType

Added in: astro@5.16.0

一种工具类型,可根据操作的 Zod schema 自动推断其输入的 TypeScript 类型。这对于在自己的类型定义中将操作的 input 验证器类型 作为对象引用非常有用。

¥A utility type that automatically infers the TypeScript type of an action’s input based on its Zod schema. This can be useful to reference an action’s input validator type as an object in your own type definitions.

如果省略 input 验证器,则返回 never

¥Returns never when input validator is omitted.

以下示例在名为 contact 的操作上使用 ActionInputSchema 语句:

¥The following example uses ActionInputSchema on an action named contact to:

  • 检索操作输入的 Zod 模式类型。

  • 检索操作验证器的预期输入类型。

src/components/Form.astro
---
import { actions, ActionInputSchema } from 'astro:actions';
import { z } from 'astro/zod';
type ContactSchema = ActionInputSchema<typeof actions.contact>;
type ContactInput = z.input<ContactSchema>;
---

类型:Awaited<ReturnType<ActionHandler>>

¥Type: Awaited<ReturnType<ActionHandler>>

一种工具类型,可从 一个操作处理程序 中提取输出类型。此方法解包 Promise(如果处理程序是异步的)和 ReturnType,从而返回 实际输出类型。如果你需要在自己的类型定义中引用操作的输出类型,这将非常有用。

¥A utility type that extracts the output type from an action handler. This unwraps both the Promise (if the handler is async) and the ReturnType to give you the actual output type. This can be useful if you need to reference an action’s output type in your own type definitions.

以下示例使用 ActionReturnType 语句检索名为 contact 的操作的预期输出类型:

¥The following example uses ActionReturnType to retrieve the expected output type for an action named contact:

src/components/Form.astro
---
import { actions, ActionReturnType } from 'astro:actions';
type ContactResult = ActionReturnType<typeof actions.contact>;
---

类型:{ data: TOutput, error: undefined } | { data: undefined, error: ActionError }

¥Type: { data: TOutput, error: undefined } | { data: undefined, error: ActionError }

表示操作调用的结果:

¥Represents the result of an action call:

  • 成功时,data 包含操作的输出,并且 errorundefined

  • 失败时,error 包含一个带有验证错误或运行时错误的 ActionError,并且 dataundefined

Astro v5.16 中文网 - 粤ICP备13048890号