# node: getMessages URL: https://generaltranslation.com/zh/docs/node/api/get-messages.mdx --- title: getMessages description: getMessages 函数的 API 参考文档 --- ## 概述 `getMessages` 函数是一个异步函数,会返回一个用于解析预先注册消息的解析器。 请将它与 [`msg`](/docs/node/api/strings/msg) (从 `gt-node` 导入) 配合使用,在 build time 注册字符串,并在 runtime 解析其对应的翻译。 ```js import { msg, getMessages } from 'gt-node'; // 在构建时(或模块作用域)注册 const greeting = msg('Hello, world!'); // 在 runtime 解析 const m = await getMessages(); const translated = m(greeting); ``` **必须提供请求上下文:** `getMessages` 必须在 [`withGT`](/docs/node/api/with-gt) 回调中调用,这样它才能知道应使用哪个区域设置。 ## 参考 ### 参数 无。 ### 返回值 一个 Promise,解析结果为消息解析函数 `m`: ```ts Promise<(encodedMsg: string | null | undefined, options?: InlineResolveOptions) => string | null | undefined> ``` | 名称 | 类型 | 描述 | | ------------ | ----------------------------- | --------------------------------------------------------------------- | | `encodedMsg` | `string \| null \| undefined` | 由 `msg()` 返回的已编码消息字符串;如果传入 `null`/`undefined`,则返回 `null`/`undefined`。 | | `options?` | `InlineResolveOptions` | 可选的变量值,用于插入到解析后的消息中。 | *** ## 示例 ### 基本用法 ```js title="messages.js" import { msg } from 'gt-node'; // 在模块作用域注册消息 export const GREETING = msg('Hello, world!'); export const WELCOME = msg('Welcome, {name}!'); ``` ```js title="handler.js" import { withGT, getMessages } from 'gt-node'; import { GREETING, WELCOME } from './messages'; function handleRequest(locale: string) { return withGT(locale, async () => { const m = await getMessages(); return { greeting: m(GREETING), welcome: m(WELCOME, { name: 'Alice' }), }; }); } ``` ### 使用变量 将变量作为第二个参数传入,以插入对应的值: ```js title="handler.js" import { msg, getMessages, withGT } from 'gt-node'; const ORDER_STATUS = msg('Order {orderId} is {status}.'); function getOrderMessage(locale: string, orderId: string, status: string) { return withGT(locale, async () => { const m = await getMessages(); return m(ORDER_STATUS, { orderId, status }); }); } ``` *** ## 注意事项 * `msg` 会将字符串注册为可在构建时翻译的内容。`getMessages` 会在 runtime 解析它。 * 这种模式适用于定义在模块作用域中的字符串 (常量、枚举、错误消息) ,且这些字符串需要按 per-request 进行翻译。 * 如果将 `null` 或 `undefined` 传给 `m`,它会分别返回 `null` 或 `undefined`。 ## 后续步骤 * 直接翻译内联字符串,请参阅 [`getGT`](/docs/node/api/get-gt)。 * 设置区域设置上下文,请参阅 [`withGT`](/docs/node/api/with-gt)。