# gt-node: General Translation Node.js SDK: withGT
URL: https://generaltranslation.com/zh/docs/node/reference/functions/with-gt.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: 在请求处理期间绑定区域设置，使 General Translation 函数据此解析。withGT 的 API 参考。

包装一个回调，为翻译函数提供区域设置上下文。在 Node.js 服务器中，每个请求通常对应着区域设置不同的用户，而 `withGT` 会为回调内调用的每个 General Translation 函数设置区域设置。

## 概览 [#overview]

调用 `withGT` 时，传入一个区域设置和一个函数。在回调函数内部，对 [`getGT`](/docs/node/reference/functions/get-gt)、[`getMessages`](/docs/node/reference/functions/get-messages)、[`getTranslations`](/docs/node/reference/functions/get-translations)、[`tx`](/docs/node/reference/functions/tx) 和 [`getLocale`](/docs/node/reference/functions/get-locale) 的所有调用都会基于该区域设置进行解析。

```ts
import { withGT } from 'gt-node';

app.get('/api/greeting', (req, res) => {
  withGT(req.locale, () => {
    // 此处的翻译函数均使用 req.locale
  });
});
```

签名：

```ts
withGT<T>(locale: string, fn: () => T): T
```

*注意：`withGT` 底层使用异步本地存储，将区域设置限定在当前请求范围内。该上下文不会泄漏到其他并发请求中。*

## 工作原理 [#how-it-works]

* **限定层级的区域设置。** 该区域设置仅在 `fn` 执行期间生效。并发请求会各自保持自己的区域设置。
* **区域设置解析。** 传入的区域设置会根据已配置的 `locales` 进行解析；如果值不受支持，则回退到 `defaultLocale`。
* **同步或异步。** `fn` 可以是同步或异步的，`withGT` 会返回 `fn` 的返回值。
* **需要先完成 setup。** 必须先运行 [`initializeGT`](/docs/node/reference/functions/initialize-gt)，然后才能运行 `withGT`，否则会抛出错误。

## 参数 [#parameters]

| 参数                  | 描述               | 类型        | 可选 | 默认值 |
| ------------------- | ---------------- | --------- | -- | --- |
| [`locale`](#locale) | 为回调绑定的区域设置。      | `string`  | 否  | —   |
| [`fn`](#fn)         | 在该区域设置上下文中运行的函数。 | `() => T` | 否  | —   |

### `locale` [#locale]

**类型** `string` · **必需**

用于指定回调中翻译所使用的[区域设置代码](/docs/platform/core/reference/utility-functions/locales/is-valid-locale) (例如 `'es'`、`'fr-CA'`) 。

### `fn` [#fn]

**类型** `() => T` · **必填**

在给定区域设置上下文中执行的回调函数。既可以是同步的，也可以是异步的。

## 返回值 [#returns]

**类型** `T`

回调函数 `fn` 的返回值。

## 示例 [#examples]

```ts title="server.js"
// Express 中间件
import express from 'express';
import { initializeGT, withGT, getGT } from 'gt-node';

initializeGT({
  defaultLocale: 'en',
  locales: ['en', 'es', 'fr'],
  projectId: process.env.GT_PROJECT_ID,
});

const app = express();

app.use((req, res, next) => {
  const locale = req.headers['accept-language']?.split(',')[0] || 'en';
  withGT(locale, () => {
    next();
  });
});

app.get('/api/greeting', async (req, res) => {
  const gt = await getGT();
  res.json({ message: gt('Hello, world!') });
});
```

```ts title="handler.js"
// 包装异步 handler
import { withGT, getGT } from 'gt-node';

export async function handleRequest(locale) {
  return withGT(locale, async () => {
    const gt = await getGT();
    return gt('Welcome to our app!');
  });
}
```

## 注意事项 [#notes]

* 使用 `withGT` 前，必须先调用 [`initializeGT`](/docs/node/reference/functions/initialize-gt)，否则会抛出错误。
* 区域设置上下文仅作用于该回调，不会泄漏到其他并发请求。
* `withGT` 同时支持同步和异步回调。

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
