NestJS中文文档
应用 / 国际化
已译 191/191

国际化

@nestjs/i18n 把 Nest 应用返回的内容(响应、错误、校验消息、GraphQL 字段)翻译成每个请求所用的语言。

一家销售猫粮与用品的网店面向美国、波兰和德国的顾客,其订单 API 应当用顾客自己的语言回复。在本教程中,你会翻译订单确认(含正确的波兰语复数)、错误消息、校验消息(来自 class-validator 或 Zod)以及 GraphQL 字段。你还会按各语言环境格式化价格与日期。

该包每个请求只解析一次语言环境,并保存在 AsyncLocalStorage 存储中。服务、异常、管道和 GraphQL 字段解析器无需访问请求对象即可翻译,所有提供者都保持单例。它在 Express 与 Fastify 上行为一致,也适用于微服务和 WebSocket 网关。

安装

本教程扩展示例商店的订单 API,该 API 面向英语、波兰语和德语顾客。订单是保存在内存中的普通对象。示例预置了订单 #1001:两袋三文鱼猫粮和三包结团猫砂,总计 $97.95。下单时间为 2026 年 9 月 14 日,目前已经发货。

安装该包:

$ npm i --save @nestjs/i18n

第一节会从 JSON 文件推导类型,因此请在 tsconfig.json 中启用 resolveJsonModule。

添加词条目录并注册模块

翻译存放在 JSON 文件中,每个语言环境一个目录。每个文件都会成为一个以文件名命名的命名空间,因此 orders.json 中的 notFound 消息,其键为 orders.notFound。

src
├── i18n
│   ├── de
│   │   ├── orders.json
│   │   └── validation.json
│   ├── en
│   │   ├── orders.json
│   │   └── validation.json
│   ├── pl
│   │   ├── orders.json
│   │   └── validation.json
│   └── translations.ts
├── orders
└── app.module.ts

下面是订单的英文词条目录。花括号中的词是占位符,由翻译时传入的参数填充。items 是复数消息,翻译订单确认一节会说明。

src/i18n/en/orders.json
{
  "items": {
    "one": "{count} item",
    "other": "{count} items"
  },
  "confirmed": "Thank you! Order #{id} is confirmed: {items}.",
  "notFound": "Order #{id} was not found.",
  "invalidId": "The order number must be a whole number.",
  "unknownProduct": "Product {id} is not in our catalog.",
  "tooManyItems": {
    "one": "{path} must not exceed {count} item per product",
    "other": "{path} must not exceed {count} items per product"
  },
  "unsupportedCountry": "We only ship to the United States, Poland and Germany.",
  "status": {
    "pending": "Awaiting payment",
    "paid": "Paid",
    "shipped": "Shipped"
  }
}

TypeScript 编译器不会把 JSON 文件复制到 dist。请把它们加入 nest-cli.json 的资源:

{
  "compilerOptions": {
    "assets": ["i18n/**/*.json"],
    "watchAssets": true
  }
}

现在在根模块中注册 I18nModule:

app.module.ts
import { Module } from '@nestjs/common';
import {
  AcceptLanguageLocaleResolver,
  HeaderLocaleResolver,
  I18nModule,
  JsonI18nLoader,
  QueryLocaleResolver,
} from '@nestjs/i18n';
import { join } from 'node:path';
import { OrdersModule } from './orders/orders.module.js';

@Module({
  imports: [
    I18nModule.forRoot({
      defaultLocale: 'en',
      supportedLocales: ['en', 'pl', 'de'],
      fallbacks: { 'de-AT': 'de' },
      loader: new JsonI18nLoader({
        path: join(import.meta.dirname, 'i18n'),
      }),
      resolvers: [
        new QueryLocaleResolver('lang'),
        new HeaderLocaleResolver('x-lang'),
        new AcceptLanguageLocaleResolver(),
      ],
    }),
    OrdersModule,
  ],
})
export class AppModule {}

该模块是全局的,它会在每个路由上挂载一个中间件,在守卫、拦截器、管道和处理器运行之前解析语言环境。解析过程如下:

  • 解析器按顺序运行。 每个解析器返回一个或多个候选,第一个匹配受支持语言环境的候选胜出。这里 ?lang=pl 优先于 x-lang 请求头,后者又优先于 Accept-Language。
  • Accept-Language 会被正确解析。 语言按 q 值排序,不支持的语言会被跳过,因此 fr-CH, fr;q=0.9, de;q=0.8 解析为 de。
  • 区域会匹配其基础语言。 pl-PL 解析为 pl,无需配置。
  • fallbacks 让某个区域保留为独立语言环境。 de-AT 解析为 de-AT,而其消息来自 de。这个语言环境在格式化价格与日期时很重要:奥地利顾客会得到奥地利的数字格式。未列出的区域(例如 de-CH)会解析为纯 de。
  • 都不匹配,或根本没有请求(cron 任务、队列消费者):使用 defaultLocale。

CookieLocaleResolver 改为读取 cookie(默认 lang),适用于记住访客所选语言的站点。使用顾客保存的语言会添加你自己写的解析器。

每个响应都会说明它用的是哪个语言环境。中间件把 Content-Language 设为解析出的语言环境,并把解析器读取的请求头加入 Vary(这里是 Vary: x-lang, Accept-Language),使缓存按语言各存一份。设置 responseHeaders: false 可关闭。

supportedLocales 是可选的,默认取加载器发现的目录。显式固定它,可以避免某个误放的目录变成语言环境。

最后,给键加上类型。英文词条目录是唯一事实来源,仅类型导入会在编译期读取其形状而不加载文件。declare module 块把该形状注册给包:

i18n/translations.ts
import type orders from './en/orders.json';
import type validation from './en/validation.json';

export interface Translations {
  orders: typeof orders;
  validation: typeof validation;
}

declare module '@nestjs/i18n' {
  interface I18nTypes {
    translations: Translations;
  }
}

从此以后,I18nService 以及用于本地化异常与校验消息的辅助函数 t()、i18nValidationMessage()、i18nIssueMessage() 只接受英文词条目录中存在的键。像 orders.notFund 这样的拼写错误会编译失败,orders.status 也会失败,因为它是命名空间而不是消息。若某个提供者翻译的是另一种形状的词条目录(例如某个库自带的),请注入 I18nService<OtherTranslations>,它会改为按 OtherTranslations 检查键。

翻译订单确认

顾客下单时,API 会返回一条包含商品数量的确认消息。把 I18nService 注入 OrdersService 并调用 t():

orders/orders.service.ts
@Injectable()
export class OrdersService {
  // ...
  constructor(private readonly i18nService: I18nService) {}

  create(userId: number, dto: CreateOrderDto) {
    const order: Order = {
      id: this.nextId++,
      userId,
      items: dto.items,
      total: this.priceOf(dto.items),
      status: 'pending',
      createdAt: new Date(),
    };
    this.orders.push(order);

    return {
      id: order.id,
      message: this.i18nService.t('orders.confirmed', {
        args: { id: order.id, items: this.describeItems(order) },
      }),
    };
  }

  describeItems(order: Order): string {
    const count = order.items.reduce((sum, item) => sum + item.quantity, 0);
    return this.i18nService.t('orders.items', { args: { count } });
  }
  // ...
}

你不必给 t() 传语言环境。它会读取为当前请求解析出的那个,即使 OrdersService 是永远看不到请求的单例。只有在需要覆盖时才设置 locale 选项,例如后台任务按顾客档案中保存的语言发邮件。该选项的匹配方式与请求语言环境相同:pl-PL 变成 pl,不支持的语言环境变成默认语言环境,因此过期的档案值不会弄坏任务。

控制器里没有任何与语言环境相关的东西:

orders/orders.controller.ts
@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Post()
  create(@Body() dto: CreateOrderDto) {
    // 身份验证教程会把固定的顾客替换成已登录用户。
    return this.ordersService.create(1, dto);
  }
}

英语和德语有两种复数形式。波兰语有四种,一个数字用哪种取决于其末位数字。复数消息是一个以复数类别为键的对象:

src/i18n/pl/orders.json
{
  "items": {
    "one": "{count} produkt",
    "few": "{count} produkty",
    "many": "{count} produktów",
    "other": "{count} produktu"
  },
  "confirmed": "Dziękujemy! Zamówienie #{id} zostało przyjęte: {items}.",
  "notFound": "Nie znaleziono zamówienia #{id}.",
  "invalidId": "Numer zamówienia musi być liczbą całkowitą.",
  "unknownProduct": "Produktu {id} nie ma w naszym katalogu.",
  "tooManyItems": {
    "one": "{path}: można zamówić najwyżej {count} sztukę jednego produktu",
    "few": "{path}: można zamówić najwyżej {count} sztuki jednego produktu",
    "many": "{path}: można zamówić najwyżej {count} sztuk jednego produktu",
    "other": "{path}: można zamówić najwyżej {count} sztuki jednego produktu"
  },
  "unsupportedCountry": "Wysyłamy tylko do Stanów Zjednoczonych, Polski i Niemiec.",
  "status": {
    "pending": "Oczekuje na płatność",
    "paid": "Opłacone",
    "shipped": "Wysłane"
  }
}

当参数中包含数字 count 时,服务会用消息语言环境的 Intl.PluralRules 选择形式。若缺少某个类别,则使用 other。德语文件与英文一致,只有 one 和 other 两种形式。

商品数 英语 波兰语 德语
1 1 item 1 produkt 1 Produkt
2 2 items 2 produkty 2 Produkte
5 5 items 5 produktów 5 Produkte
22 22 items 22 produkty 22 Produkte

确认消息由两条消息组合而成:先翻译复数短语,再插入句子。占位符不能嵌套,这就是组合它们的方式。

占位符的名称由字母、数字和下划线组成。没有传参的占位符会按原样留在文本中,花括号中的其他文本也一样。要在名称旁写出花括号,请双写:{{ '{' }}{{ '{' }}id{{ '}' }}{{ '}' }} 会输出 {{ '{' }}id{{ '}' }}。select、序数和精确匹配请使用 ICU 消息语法。

提示

只有 count 参数会选择复数形式,因此在每个用 t() 翻译的复数消息中都把它命名为 count。得益于已注册的词条目录类型,复数消息缺少它时 t() 无法通过编译。校验消息会自动获得 count,本地化校验消息一节会说明。

本地化异常

订单不存在时,应当用顾客的语言返回 404。在抛出异常时翻译消息:

orders/orders.service.ts
findOne(id: number): Order {
  const order = this.orders.find((order) => order.id === id);
  if (!order) {
    throw new NotFoundException(this.i18nService.t('orders.notFound', { args: { id } }));
  }
  return order;
}

异常携带的是完成后的文本,因此无需额外配置:Nest 的默认异常过滤器、你自己的过滤器以及 GraphQL 错误格式都会收到翻译后的消息。带 x-lang: pl 的 GET /orders/999 返回:

{
  "message": "Nie znaleziono zamówienia #999.",
  "error": "Not Found",
  "statusCode": 404
}

手边没有 I18nService 的代码可以改用 t() 函数。它以同样的方式为当前请求翻译。ParseIntPipe 之类的内置管道产生英文消息,因此请为解析订单 ID 的管道提供异常工厂:

orders/orders.controller.ts
const orderIdPipe = new ParseIntPipe({
  exceptionFactory: () => new BadRequestException(t('orders.invalidId')),
});

@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}
  // ...

  @Get(':id')
  findOne(@Param('id', orderIdPipe) id: number) {
    return this.ordersService.getSummary(id);
  }
}

这个管道在依赖注入之外创建一次,却仍能用各自的语言响应每个请求。getSummary() 会在格式化价格与日期中实现。

如果你的 API 用自己的异常过滤器塑造错误(例如 RFC 9457 problem details),该过滤器会像读取普通消息一样读取翻译后的消息:

common/problem-details.filter.ts
import {
  Catch,
  NotFoundException,
  type ArgumentsHost,
  type ExceptionFilter,
} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';

@Catch(NotFoundException)
export class ProblemDetailsFilter implements ExceptionFilter {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  catch(exception: NotFoundException, host: ArgumentsHost) {
    const { httpAdapter } = this.httpAdapterHost;
    const response = host.switchToHttp().getResponse();
    httpAdapter.setHeader(response, 'Content-Type', 'application/problem+json');
    httpAdapter.reply(
      response,
      { type: 'about:blank', title: 'Not Found', status: 404, detail: exception.message },
      404,
    );
  }
}

注册该过滤器后,同一个请求返回:

{
  "type": "about:blank",
  "title": "Not Found",
  "status": 404,
  "detail": "Nie znaleziono zamówienia #999."
}

本地化校验消息

这一步假设你的应用用 class-validator 校验请求体;若用 Zod 或其他 Standard Schema 库校验,请跳到使用 Zod。I18nValidationPipe 是 Nest ValidationPipe 的直接替代品:它接受相同的选项,只翻译消息。把它绑定在原 ValidationPipe 的位置,这里作为 AppModule 的 APP_PIPE 提供者:

app.module.ts
providers: [
  {
    provide: APP_PIPE,
    useValue: new I18nValidationPipe({ whitelist: true, transform: true }),
  },
],

从新订单的 DTO 开始。它使用 class-validator 装饰器,不带任何消息:

orders/dto/create-order.dto.ts
import { i18nValidationMessage } from '@nestjs/i18n';
import { Type } from 'class-transformer';
import { ArrayNotEmpty, IsInt, IsString, Max, Min, ValidateNested } from 'class-validator';

export class OrderItemDto {
  @IsString()
  productId: string;

  @IsInt()
  @Min(1)
  @Max(10, { message: i18nValidationMessage('orders.tooManyItems') })
  quantity: number;
}

export class CreateOrderDto {
  @ArrayNotEmpty()
  @ValidateNested({ each: true })
  @Type(() => OrderItemDto)
  items: OrderItemDto[];
}

没有 message 的约束会按约束名在 validation 命名空间中查找:@IsInt() 读取 validation.isInt,@Min() 读取 validation.min。i18nValidationMessage() 把单个约束指向你选定的键,这里是商店自定义的商品上限消息。写成普通字符串的消息保持原样。消息可以使用以下占位符:

  • property:字段名,例如 quantity。
  • path:从 DTO 开始的点号路径,例如 items.1.quantity。对顶层字段而言与 property 相同。
  • value:被拒绝的值,当它是字符串、数字或布尔值时可用。
  • constraint1、constraint2 等:装饰器的参数。列表(例如 @IsIn() 接受的值)读作 US, PL, DE。
  • count:第一个数字参数,使复数消息与之一致。@Max(10) 会选择 10 对应的形式。

商品上限是复数消息(见翻译订单确认中的波兰语词条目录),因此 @Max(10) 在波兰语中读作「10 sztuk」。下面是本教程所用约束的波兰语 validation 词条目录。minLength 也是复数消息,因此 @MinLength(2) 读作「2 znaki」,@MinLength(5) 读作「5 znaków」:

src/i18n/pl/validation.json
{
  "isInt": "{path} musi być liczbą całkowitą",
  "isString": "{path} musi być tekstem",
  "min": "{path} musi wynosić co najmniej {constraint1}",
  "arrayNotEmpty": "{path} musi zawierać co najmniej jeden element",
  "minLength": {
    "one": "{path} musi mieć co najmniej {count} znak",
    "few": "{path} musi mieć co najmniej {count} znaki",
    "many": "{path} musi mieć co najmniej {count} znaków",
    "other": "{path} musi mieć co najmniej {count} znaku"
  },
  "matches": "{path} ma nieprawidłowy format"
}

没有翻译的约束会保留 class-validator 的消息,因此你可以逐个翻译用到的约束。

对于嵌套对象,Nest 的 ValidationPipe 会在每条消息前加上父级路径。I18nValidationPipe 则让已翻译的消息保持原样,由每条消息自行决定:path 给出 items.1.quantity,property 只给出 quantity。没有翻译的消息仍保留前缀。

顾客为订单设置收货地址。其 DTO 依赖词条目录中的 minLength 与 matches 条目,并为国家指定了商店自定义消息:

orders/dto/shipping-address.dto.ts
import { i18nValidationMessage } from '@nestjs/i18n';
import { IsIn, Matches, MinLength } from 'class-validator';

export class ShippingAddressDto {
  @MinLength(2)
  recipient: string;

  @MinLength(2)
  city: string;

  @Matches(/^[0-9-]{5,6}$/)
  postalCode: string;

  @IsIn(['US', 'PL', 'DE'], { message: i18nValidationMessage('orders.unsupportedCountry') })
  country: 'US' | 'PL' | 'DE';
}
orders/orders.controller.ts
@Put(':id/shipping-address')
updateShippingAddress(
  @Param('id', orderIdPipe) id: number,
  @Body() address: ShippingAddressDto,
) {
  return this.ordersService.updateShippingAddress(id, address);
}

一位德国顾客如果收件人只写一个字母、邮编四位、国家填 AT,会收到三条翻译后的消息。试一试一节展示了响应。

使用 Zod

如果你的应用用 Zod、Valibot、ArkType 或其他 Standard Schema 库校验,请绑定 I18nStandardSchemaValidationPipe 而不是 I18nValidationPipe。它是 Nest StandardSchemaValidationPipe 的直接替代品,一个应用只绑定两者之一,不能同时绑定:

app.module.ts
providers: [{ provide: APP_PIPE, useValue: new I18nStandardSchemaValidationPipe() }],

下面把同样的输入写成 Zod schema。库的消息是普通字符串,因此 i18nIssueMessage() 把翻译键编码在消息本身中,这对任何 Standard Schema 库都有效:

orders/orders.schemas.ts
import { i18nIssueMessage } from '@nestjs/i18n';
import { z } from 'zod';

export const orderItemSchema = z.object({
  productId: z.string(),
  quantity: z.number().int().min(1).max(10, i18nIssueMessage('orders.tooManyItems')),
});

export const createOrderSchema = z.object({
  items: z.array(orderItemSchema).nonempty(),
});
export type CreateOrderDto = z.infer<typeof createOrderSchema>;

export const shippingAddressSchema = z.object({
  recipient: z.string().min(2),
  city: z.string().min(2),
  postalCode: z.string().regex(/^[0-9-]{5,6}$/),
  country: z.enum(['US', 'PL', 'DE'], i18nIssueMessage('orders.unsupportedCountry')),
});
export type ShippingAddress = z.infer<typeof shippingAddressSchema>;

请求体参数改为声明 schema,而不是类:

orders/orders.controller.ts
import {
  createOrderSchema,
  shippingAddressSchema,
  type CreateOrderDto,
  type ShippingAddress,
} from './orders.schemas.js';
// ...
@Post()
create(@Body({ schema: createOrderSchema }) dto: CreateOrderDto) {
  // ...
}

@Put(':id/shipping-address')
updateShippingAddress(
  @Param('id', orderIdPipe) id: number,
  @Body({ schema: shippingAddressSchema }) address: ShippingAddress,
) {
  return this.ordersService.updateShippingAddress(id, address);
}

没有显式键的问题,会按库分配的代码查找,从最具体的键到最宽泛的键:

  • 先看格式。 正则失败读取 validation.invalid_format.regex。
  • 再看来源。 Zod 对过短字符串、过小数字和过短数组都报告 too_small,并在 origin 中说明是哪一种。过短字符串读取 validation.too_small.string,这样词条目录就能谈论字符而不会把数字弄错。
  • 最后只用代码,例如 validation.too_small。

Valibot 的问题 type 同理。消息可以使用上述 property 与 path 占位符,库自身的文本作为 message,以及问题的参数(例如 minimum 或 expected)。count 持有数字 minimum 或 maximum,因此「2 znaki」与「5 znaków」都能正确输出,.max(10) 的 orders.tooManyItems 也一样。下面是波兰语词条目录,问题代码条目放在约束名之前:

src/i18n/pl/validation.json
{
  "invalid_type": "{path} musi być typu {expected}",
  "too_small": {
    "string": {
      "one": "{path} musi mieć co najmniej {count} znak",
      "few": "{path} musi mieć co najmniej {count} znaki",
      "many": "{path} musi mieć co najmniej {count} znaków",
      "other": "{path} musi mieć co najmniej {count} znaku"
    },
    "number": "{path} musi wynosić co najmniej {minimum}",
    "array": "{path} musi zawierać co najmniej jeden element"
  },
  "invalid_format": {
    "regex": "{path} ma nieprawidłowy format"
  },
  "isInt": "{path} musi być liczbą całkowitą",
  "isString": "{path} musi być tekstem",
  "min": "{path} musi wynosić co najmniej {constraint1}",
  "arrayNotEmpty": "{path} musi zawierać co najmniej jeden element",
  "minLength": {
    "one": "{path} musi mieć co najmniej {count} znak",
    "few": "{path} musi mieć co najmniej {count} znaki",
    "many": "{path} musi mieć co najmniej {count} znaków",
    "other": "{path} musi mieć co najmniej {count} znaku"
  },
  "matches": "{path} ma nieprawidłowy format"
}

有了这些条目,试一试中那个无效收货地址会得到与类校验相同的三条德语消息,而无效订单会读作:

{
  "message": [
    "items.0.quantity musi wynosić co najmniej 1",
    "items.1.productId musi być typu string",
    "items.1.quantity: można zamówić najwyżej 10 sztuk jednego produktu"
  ],
  "error": "Bad Request",
  "statusCode": 400
}

没有翻译的问题保留 Nest 的常规格式,即路径后跟库的消息。

本地化 GraphQL 字段

这一步适用于用 @nestjs/graphql 提供 GraphQL 的应用。移动端通过 GraphQL 读取订单,使用 Apollo 驱动和在 AppModule 中注册的 code first schema:

app.module.ts
GraphQLModule.forRoot<ApolloDriverConfig>({
  driver: ApolloDriver,
  autoSchemaFile: true,
}),

对象类型暴露原始订单数据:

orders/order.model.ts
import { Field, Float, Int, ObjectType } from '@nestjs/graphql';

@ObjectType('Order')
export class OrderModel {
  @Field(() => Int)
  id: number;

  @Field()
  status: string;

  @Field(() => Float)
  total: number;
}

本地化字段由字段解析器计算,使用与 REST 控制器相同的 I18nService:

orders/orders.resolver.ts
import { Args, Int, Parent, Query, ResolveField, Resolver } from '@nestjs/graphql';
import { I18nService } from '@nestjs/i18n';
import type { Order } from './order.entity.js';
import { OrderModel } from './order.model.js';
import { OrdersService } from './orders.service.js';

@Resolver(() => OrderModel)
export class OrdersResolver {
  constructor(
    private readonly ordersService: OrdersService,
    private readonly i18nService: I18nService,
  ) {}

  @Query(() => OrderModel)
  order(@Args('id', { type: () => Int }) id: number) {
    return this.ordersService.findOne(id);
  }

  @ResolveField(() => String)
  statusLabel(@Parent() order: Order) {
    return this.i18nService.t(`orders.status.${order.status}`);
  }

  @ResolveField(() => String)
  items(@Parent() order: Order) {
    return this.ordersService.describeItems(order);
  }
}

statusLabel 的键是由 OrderStatus 联合类型构建的模板字面量,因此编译器仍会检查每个状态都有标签。

在 Express 上,Apollo 挂载在 Nest 中间件之后,因此添加词条目录并注册模块中的语言环境中间件会包裹每个 GraphQL 操作。?lang、x-lang 和 Accept-Language 在解析器、字段解析器和守卫中的行为与 REST 完全一致。findOne() 抛出的 NotFoundException 会以翻译后的形式到达客户端,位于 errors[0].message。

警告

语言环境中间件不会包裹运行在 WebSockets 上的订阅,也不会包裹挂载在其之外的 GraphQL 驱动。这包括常见的全局前缀场景:Nest 把中间件挂在前缀之下,而 Apollo 仍在 /graphql,因此使用全局前缀时请给 GraphQLModule 设置 useGlobalPrefix: true。中间件不运行的地方,包会退回到一个全局拦截器,它从 GraphQL 上下文中的请求(订阅则是 WebSocket 握手)读取语言环境,并在守卫之后运行。字段解析器(包括订阅事件的字段解析器)只有在你设置 fieldResolverEnhancers: ['interceptors'] 时才被覆盖,守卫看不到语言环境,响应也不带 Content-Language。

格式化价格与日期

订单摘要显示状态、商品数量、总计和下单日期,并按每位顾客期望的方式格式化:

orders/orders.service.ts
getSummary(id: number) {
  const order = this.findOne(id);
  return {
    id: order.id,
    status: this.i18nService.t(`orders.status.${order.status}`),
    items: this.describeItems(order),
    total: this.i18nService.formatNumber(order.total, { style: 'currency', currency: 'USD' }),
    placedAt: this.i18nService.formatDate(order.createdAt, {
      dateStyle: 'long',
      timeZone: 'UTC',
    }),
  };
}

formatNumber() 与 formatDate() 用请求的语言环境包装 Intl.NumberFormat 与 Intl.DateTimeFormat。它们接受常规的 Intl 选项,外加一个可覆盖当前语言环境的 locale 选项,与 t() 中一样。对订单 #1001:

语言环境 total placedAt
en $97.95 September 14, 2026
pl 97,95 USD 14 września 2026
de 97,95 $ 14. September 2026
de-AT $ 97,95 14. September 2026

de-AT 得到奥地利格式,是因为模块注册时把它列在了 fallbacks 中。它的消息仍来自德语词条目录。

有两件事不由语言环境决定:

  • 货币。 语言环境控制金额怎么写,而不决定它值什么。商店以美元结算,因此每位顾客看到的都是 USD。货币应取自订单或商店,绝不能取自语言环境。
  • 时区。 没有 timeZone 时,日期按服务器时区格式化,可能把日期挪一天。如果你保存了顾客时区就传入它,或像这里一样按 UTC 格式化。

使用顾客保存的语言

顾客注册时会选择语言,顾客记录把它保存在 locale 字段中,就像邮件一章的 customers 表。这里 CustomersService 把顾客保存在内存中,正如 OrdersService 保存订单。对已登录顾客,这个选择应优先于 Accept-Language(后者只是浏览器的默认值)。@nestjs/authentication 的守卫(类似 Passport 守卫)会把已登录用户放到 request.user。

解析器在语言环境中间件中运行,先于守卫,此时还没人登录。设置了 afterGuards 的解析器改为在守卫之后运行,并接收该次调用的 executionContext:

customers/customer-locale.resolver.ts
import { Injectable } from '@nestjs/common';
import { LocaleResolver, type LocaleResolverInput } from '@nestjs/i18n';
import { CustomersService } from './customers.service.js';

@Injectable()
export class CustomerLocaleResolver extends LocaleResolver {
  // 在守卫之后,身份验证守卫已把已登录用户放到请求上
  readonly afterGuards = true;

  constructor(private readonly customersService: CustomersService) {
    super();
  }

  resolve({ executionContext }: LocaleResolverInput) {
    const request = executionContext?.switchToHttp().getRequest<{ user?: { id: number } }>();
    const user = request?.user;
    return user ? this.customersService.findOne(user.id)?.locale : undefined;
  }
}

Nest 会实例化解析器类,因此它可以注入提供者。把它放进 resolvers 中它应有的位置,并导入提供其依赖的模块:

app.module.ts
I18nModule.forRoot({
  // ...
  resolvers: [
    new QueryLocaleResolver('lang'),
    new HeaderLocaleResolver('x-lang'),
    CustomerLocaleResolver,
    new AcceptLanguageLocaleResolver(),
  ],
  imports: [CustomersModule],
  // ...
}),

解析器的顺序仍然起决定作用:

  • ?lang 与 x-lang 优先。 它们是为本次请求所做的选择,来自语言切换链接或应用设置。其中之一匹配时,顾客解析器不会运行。
  • 保存的语言优先于 Accept-Language。 Zofia 保存了波兰语,因此她在任何浏览器里都读波兰语。Lukas 保存了 de-AT,它会像其他候选一样被匹配,因此他得到奥地利格式。
  • 匿名顾客,以及没有保存受支持语言的顾客,得到其下解析器的结果,这里来自 Accept-Language。

守卫看到的是守卫之前那些解析器找到的语言环境,守卫抛出的错误(例如 401)的响应也是如此。处理器及其之后的一切看到的是顾客的语言环境。解析器每个请求运行一次,对包含多个根字段的 GraphQL 操作也一样。在 GraphQL 上,请求位于 GqlExecutionContext.create(executionContext).getContext().req。

提示

已登录顾客的响应现在取决于提问者。这类响应通常本就是私有的,但如果共享缓存会存储它们,请把标识顾客的请求头(例如 Authorization)列进解析器的 varyHeaders,中间件会把它加入 Vary。

顾客更改语言时,立即用新语言回复。I18nContext.setLocale() 会改变本次请求余下部分(包括 Content-Language)的语言环境:

customers/customers.controller.ts
@Controller('customers')
export class CustomersController {
  constructor(
    private readonly customersService: CustomersService,
    private readonly i18nContext: I18nContext,
    private readonly i18nService: I18nService,
  ) {}

  @Put('me/locale')
  updateLocale(@Req() request: { user: { id: number } }, @Body('locale') locale: string) {
    const supported = this.i18nContext.setLocale(locale);
    if (!supported) {
      throw new BadRequestException(this.i18nService.t('customers.unsupportedLocale'));
    }

    this.customersService.updateLocale(request.user.id, supported);
    return { locale: supported, message: this.i18nService.t('customers.localeUpdated') };
  }
}

setLocale() 按解析时的方式匹配语言环境并返回匹配结果:de-DE 变成 de。若商店不使用该语言书写,它返回 undefined 并保持语言环境不变,因此错误用的是顾客正在阅读的语言。这两条消息放在各语言的 customers 词条目录中,并在 Translations 中以 customers: typeof customers 注册:

src/i18n/de/customers.json
{
  "localeUpdated": "Erledigt! Ab jetzt schreiben wir Ihnen auf Deutsch.",
  "unsupportedLocale": "Wir schreiben nur auf Englisch, Polnisch und Deutsch."
}

微服务与 WebSocket 网关

消息处理器与 WebSocket 网关不经过 HTTP 中间件。在那里,模块在全局拦截器中用同样的解析器解析语言环境,因此服务、异常和 t() 函数的行为与 HTTP 请求一致。

消息没有请求头或查询串,但解析器会收到 executionContext,因此解析器可以读取生产者放进消息本身的语言环境。把它加入微服务 I18nModule 的 resolvers:

common/message-locale.resolver.ts
import { LocaleResolver, type LocaleResolverInput } from '@nestjs/i18n';

export class MessageLocaleResolver extends LocaleResolver {
  resolve({ executionContext }: LocaleResolverInput) {
    if (executionContext?.getType() !== 'rpc') {
      return undefined;
    }
    return executionContext.switchToRpc().getData<{ locale?: string }>()?.locale;
  }
}

解析器也可以用同样的方式读取消息的传输元数据,例如 NATS 或 Kafka 消息的请求头,来源是 executionContext.switchToRpc().getContext()。

对网关而言,内置解析器读取连接升级请求的请求头与查询串。Socket.IO 把该请求保留为握手信息,解析器能在那里找到它。@nestjs/platform-ws 的 WsAdapter 背后的 ws 库什么都不保留,因此请在客户端连接时把请求存到 client.request(@nestjs/authentication 的 WsAuthenticator 也是这么做的):

orders/order-updates.gateway.ts
@WebSocketGateway({ path: '/orders/updates' })
export class OrderUpdatesGateway implements OnGatewayConnection {
  constructor(private readonly ordersService: OrdersService) {}

  handleConnection(client: WebSocket & { request?: IncomingMessage }, request: IncomingMessage) {
    // ws 库不保留升级请求的引用,而解析器要读取它的请求头与查询串
    client.request = request;
  }

  @SubscribeMessage('orders.summary')
  summary(@MessageBody() id: number) {
    return { event: 'orders.summary', data: this.ordersService.getSummary(id) };
  }
}

连接到 /orders/updates?lang=de 的客户端会读到德语摘要。拦截器在守卫之后运行,因此在这些路径上守卫看到的是默认语言环境,守卫抛出的错误也是默认语言。管道和处理器看到的是解析后的语言环境,而带 afterGuards 的解析器无需额外处理:这里所有解析器本来就在守卫之后运行。

处理缺失的键并重载词条目录

缺失的翻译在开发和 CI 中应当让构建失败,在生产中则应安静降级。下面是最终的 AppModule:

app.module.ts
import { ApolloDriver, type ApolloDriverConfig } from '@nestjs/apollo';
import { Module } from '@nestjs/common';
import { APP_PIPE } from '@nestjs/core';
import { GraphQLModule } from '@nestjs/graphql';
import {
  AcceptLanguageLocaleResolver,
  HeaderLocaleResolver,
  I18nModule,
  I18nValidationPipe,
  JsonI18nLoader,
  QueryLocaleResolver,
} from '@nestjs/i18n';
import { join } from 'node:path';
import { CustomerLocaleResolver } from './customers/customer-locale.resolver.js';
import { CustomersModule } from './customers/customers.module.js';
import { OrdersModule } from './orders/orders.module.js';

const env = process.env.NODE_ENV ?? 'development';

@Module({
  imports: [
    I18nModule.forRoot({
      defaultLocale: 'en',
      supportedLocales: ['en', 'pl', 'de'],
      fallbacks: { 'de-AT': 'de' },
      loader: new JsonI18nLoader({
        path: join(import.meta.dirname, 'i18n'),
        watch: env === 'development',
      }),
      resolvers: [
        new QueryLocaleResolver('lang'),
        new HeaderLocaleResolver('x-lang'),
        CustomerLocaleResolver,
        new AcceptLanguageLocaleResolver(),
      ],
      imports: [CustomersModule],
      missingKey: env === 'production' ? 'fallback' : 'throw',
    }),
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: true,
    }),
    CustomersModule,
    OrdersModule,
  ],
  providers: [
    {
      provide: APP_PIPE,
      useValue: new I18nValidationPipe({ whitelist: true, transform: true }),
    },
  ],
})
export class AppModule {}

missingKey 选项决定请求的语言环境中找不到键时会发生什么:

  • 生产环境之外用 'throw'。 t() 和 translate() 抛出 I18nMissingKeyError,请求以 500 失败。只存在于英文的波兰语消息同样失败,因为该策略从不回退到默认语言环境。Vitest 会把 NODE_ENV 设为 test,因此测试套件以该策略运行。
  • 生产环境用 'fallback'。 缺失的波兰语消息取自默认语言环境英语,并输出一条警告指明键与语言环境,每对只警告一次。在任何地方都不存在的键会返回键本身并记录警告,每个键一次。

de-AT 到 de 的回退以及区域到基础语言的匹配在任何策略下都生效。按约束名或问题代码查找的校验消息也不会抛出:没有翻译的约束或问题保留库的消息。用 i18nValidationMessage() 或 i18nIssueMessage() 指定的键遵循该策略,与 t() 一样。其他策略包括 'key'、'empty',以及一个接收键与语言环境的函数。

提示

回退是按键进行的。当消息像翻译订单确认那样组合时,波兰语顾客可能收到一句英文句子包裹着波兰语复数。警告会告诉你发生了这件事;测试中的词条目录测试会阻止它上线。

设置 watch: true 后,JSON 加载器会监视词条目录并在文件变化时重载,译者无需重启应用即可修改消息。只在开发环境启用:

  • 重载是原子的。 整个词条目录会被重新读取并一次性替换,请求不会看到新旧混用。
  • 损坏的文件会被忽略。 若某个文件解析失败,先前的词条目录继续使用,并以文件路径记录错误。下一次有效保存会被采纳。
  • 关闭时停止监视。 应用关闭时监视器随之关闭。在 main.ts 中调用 app.enableShutdownHooks(),终止信号下也能关闭。

在 nest-cli.json 中启用 watchAssets 后,CLI 会把编辑后的词条目录复制到 dist,加载器从那里读取。

来自配置的选项

为简短起见,教程直接读取 process.env。在实际应用中,请通过 @nestjs/config 配合校验 schema 加载环境,并用 forRootAsync() 注册模块。其工厂接收注入的 ConfigService 并返回选项:

app.module.ts
I18nModule.forRootAsync({
  inject: [ConfigService],
  useFactory: (configService: ConfigService) => {
    const env = configService.get<string>('NODE_ENV', 'development');
    return {
      defaultLocale: 'en',
      supportedLocales: ['en', 'pl', 'de'],
      fallbacks: { 'de-AT': 'de' },
      loader: new JsonI18nLoader({
        path: join(import.meta.dirname, 'i18n'),
        watch: env === 'development',
      }),
      missingKey: env === 'production' ? 'fallback' : 'throw',
    };
  },
  // 列表中包含类,Nest 会实例化它,因此它留在 useFactory 旁边
  resolvers: [
    new QueryLocaleResolver('lang'),
    new HeaderLocaleResolver('x-lang'),
    CustomerLocaleResolver,
    new AcceptLanguageLocaleResolver(),
  ],
  imports: [CustomersModule],
}),

工厂可以返回加载器、解析器和格式化器实例,但不能返回类:Nest 会在构建模块时、任何工厂运行之前实例化类。因此列出 CustomerLocaleResolver 的 resolvers 与 imports 一起留在顶层。若工厂返回类,或某个选项在两处都设置,应用会在启动时失败,消息会指明是哪个选项。

要把选项放进独立的类,请把它作为 useClass 传入。它实现 I18nOptionsFactory,Nest 会调用其 createI18nOptions() 方法:

i18n/i18n-config.service.ts
@Injectable()
export class I18nConfigService implements I18nOptionsFactory {
  constructor(private readonly configService: ConfigService) {}

  createI18nOptions(): I18nModuleOptions {
    const env = this.configService.get<string>('NODE_ENV', 'development');
    return {
      defaultLocale: 'en',
      // ...
    };
  }
}
app.module.ts
I18nModule.forRootAsync({
  useClass: I18nConfigService,
  resolvers: [
    // ...
  ],
  imports: [CustomersModule],
}),

模块最终使用的选项可以通过 I18N_MODULE_OPTIONS 标记注入,供依赖它们的自建提供者使用。

自定义加载器

译者常使用翻译平台,平台会把所有词条目录导出为一个 JSON 文档。加载器继承 I18nLoader:load() 返回按语言环境索引的词条目录,可选的 watch() 把新的目录传给回调,以实现热重载。下面这个加载器在启动时抓取导出,之后每五分钟再抓一次:

i18n/remote-i18n.loader.ts
import { Logger } from '@nestjs/common';
import { I18nLoader, type I18nCatalogs } from '@nestjs/i18n';

/** 翻译平台导出的单 JSON 文档形式的词条目录,每 `interval` 毫秒重新抓取。 */
export class RemoteI18nLoader extends I18nLoader {
  private readonly logger = new Logger(RemoteI18nLoader.name);

  constructor(
    private readonly url: string,
    private readonly interval = 5 * 60_000,
  ) {
    super();
  }

  async load(): Promise<I18nCatalogs> {
    const response = await fetch(this.url, { signal: AbortSignal.timeout(10_000) });
    if (!response.ok) {
      throw new Error(`GET ${this.url} answered ${response.status}`);
    }
    return (await response.json()) as I18nCatalogs;
  }

  watch(onChange: (catalogs: I18nCatalogs) => void): () => void {
    const timer = setInterval(() => {
      this.load().then(onChange, (err: Error) =>
        this.logger.warn(`Keeping the current catalogs: ${err.message}`),
      );
    }, this.interval);
    // 仅轮询不会让进程保持存活
    timer.unref();
    return () => clearInterval(timer);
  }
}

把实例作为 loader 传入。启动时抓取失败会导致引导启动失败,轮询失败则继续使用现有词条目录。模块在初始化时调用 watch(),在关闭时调用 watch() 返回的函数。新词条目录会像第一批一样被检查,不符合要求的(例如缺少默认语言环境的目录)会被记录并忽略。要从数据库读取词条目录,请改为传入加载器类,Nest 会用它注入的仓储实例化,并把它所在模块列进 imports。

使用 ICU 消息语法

内置语法提供占位符,并以词条目录对象表示复数形式。Crowdin、Lokalise 等翻译平台常以 ICU MessageFormat 导出词条目录,它还支持 =0 这样的精确匹配、select(消息取决于某个值,例如宠物的物种)以及 selectordinal(第 1、第 2、第 3)。下面是 ICU 形式的波兰语 items 消息:

{
  "items": "{count, plural, one {# produkt} few {# produkty} many {# produktów} other {# produktu}}"
}

formatter 选项接入另一种语法。格式化器继承 I18nMessageFormatter 并实现 format(),它接收消息、参数和语言环境。下面这个把消息交给应用自行安装的 intl-messageformat 库:

i18n/icu-message.formatter.ts
import { I18nMessageFormatter } from '@nestjs/i18n';
import { IntlMessageFormat } from 'intl-messageformat';

export class IcuMessageFormatter extends I18nMessageFormatter {
  // 解析消息的开销远大于格式化,而词条目录是固定的一组
  private readonly compiled = new Map<string, IntlMessageFormat>();

  format(message: string, args: Record<string, unknown>, locale: string): string {
    const key = `${locale}\u0000${message}`;
    let compiled = this.compiled.get(key);
    if (!compiled) {
      compiled = new IntlMessageFormat(message, locale, undefined, { ignoreTag: true });
      this.compiled.set(key, compiled);
    }
    return String(compiled.format<unknown>(args));
  }
}

ignoreTag 让 < 与 > 保持为文本,否则库会把它们当作富文本标签。把实例或由 Nest 实例化的类作为 formatter 传入:

app.module.ts
I18nModule.forRoot({
  // ...
  formatter: new IcuMessageFormatter(),
}),

有了格式化器之后:

  • 教程的词条目录无需改动即可工作。 占位符就是简单的 ICU 参数,复数对象也仍然有效:模块选择形式,格式化器负责格式化。波兰语 items 无论是复数对象还是上面的 ICU 消息,都读作「5 produktów」。
  • 语言环境是请求的那个。 de-AT 从德语词条目录读取的消息会按 de-AT 格式化,因此带货币样式的数字参数读作 $ 97,95。回退到默认语言环境的消息按默认语言环境格式化,因为它就是按那门语言的语法写的。
  • 键仍受检查,复数计数不受。 编译器要求复数对象带数字 count,但 ICU 复数对它来说是字符串,因此需要你自行传入参数。

试一试

启动应用,用 Accept-Language 中的波兰语下单:

$ curl -X POST http://localhost:3000/orders \
    -H 'Content-Type: application/json' \
    -H 'Accept-Language: pl-PL,pl;q=0.9,en;q=0.8' \
    -d '{"items":[{"productId":"salmon-kibble-2kg","quantity":2},{"productId":"sisal-scratching-post","quantity":3}]}'
{"id":1002,"message":"Dziękujemy! Zamówienie #1002 zostało przyjęte: 5 produktów."}

lang 查询参数优先于任何请求头:

$ curl -X POST 'http://localhost:3000/orders?lang=de' \
    -H 'Content-Type: application/json' \
    -d '{"items":[{"productId":"feather-wand","quantity":1}]}'
{"id":1003,"message":"Vielen Dank! Bestellung #1003 ist bestätigt: 1 Produkt."}

以奥地利顾客身份读取订单 #1001 的摘要:

$ curl http://localhost:3000/orders/1001 -H 'Accept-Language: de-AT'
{
  "id": 1001,
  "status": "Versandt",
  "items": "5 Produkte",
  "total": "$ 97,95",
  "placedAt": "14. September 2026"
}

用 x-lang 请求头查询一个不存在的订单:

$ curl http://localhost:3000/orders/999 -H 'x-lang: pl'
{
  "message": "Nie znaleziono zamówienia #999.",
  "error": "Not Found",
  "statusCode": 404
}

发送一个无效订单:

$ curl -X POST 'http://localhost:3000/orders?lang=pl' \
    -H 'Content-Type: application/json' \
    -d '{"items":[{"productId":"salmon-kibble-2kg","quantity":0},{"productId":42,"quantity":12}]}'
{
  "message": [
    "items.0.quantity musi wynosić co najmniej 1",
    "items.1.productId musi być tekstem",
    "items.1.quantity: można zamówić najwyżej 10 sztuk jednego produktu"
  ],
  "error": "Bad Request",
  "statusCode": 400
}

发送一个无效收货地址:

$ curl -X PUT http://localhost:3000/orders/1001/shipping-address \
    -H 'Content-Type: application/json' \
    -H 'Accept-Language: de' \
    -d '{"recipient":"A","city":"Wien","postalCode":"1010","country":"AT"}'
{
  "message": [
    "recipient muss mindestens 2 Zeichen lang sein",
    "postalCode hat ein ungültiges Format",
    "Wir liefern nur in die USA, nach Polen und nach Deutschland."
  ],
  "error": "Bad Request",
  "statusCode": 400
}

最后,通过 GraphQL 查询该订单:

$ curl -X POST 'http://localhost:3000/graphql?lang=pl' \
    -H 'Content-Type: application/json' \
    -d '{"query":"{ order(id: 1001) { id status statusLabel items } }"}'
{
  "data": {
    "order": {
      "id": 1001,
      "status": "shipped",
      "statusLabel": "Wysłane",
      "items": "5 produktów"
    }
  }
}
提示

Intl 在 97,95 USD、97,95 $ 和 $ 97,95 中会用不换行空格(U+00A0)分隔金额与货币。上面的响应显示的是普通空格。在测试中比较格式化字符串时请留意这一点。

测试

端到端测试像客户端那样设置语言:

test/orders.e2e.spec.ts
import type { INestApplication } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import request from 'supertest';
import { AppModule } from '../src/app.module.js';

describe('Orders (e2e)', () => {
  let app: INestApplication;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    app = moduleRef.createNestApplication();
    await app.listen(0, '127.0.0.1');
  });

  afterAll(() => app.close());

  it('confirms an order in the language of the request', async () => {
    const res = await request(app.getHttpServer())
      .post('/orders')
      .set('Accept-Language', 'pl-PL,pl;q=0.9')
      .send({ items: [{ productId: 'salmon-kibble-2kg', quantity: 5 }] })
      .expect(201);

    expect(res.body.message).toBe(
      'Dziękujemy! Zamówienie #1002 zostało przyjęte: 5 produktów.',
    );
  });

  it('localizes errors', async () => {
    const res = await request(app.getHttpServer())
      .get('/orders/999?lang=de')
      .expect(404);

    expect(res.body.message).toBe('Bestellung #999 wurde nicht gefunden.');
  });
});

在请求之外,I18nService 使用默认语言环境。要在不走 HTTP 的情况下测试其他语言的服务,请把调用放进 I18nContext.run(),它会像请求那样把语言环境设为当前:

test/orders.service.spec.ts
import { I18nContext } from '@nestjs/i18n';
import { Test } from '@nestjs/testing';
import { AppModule } from '../src/app.module.js';
import { OrdersService } from '../src/orders/orders.service.js';

describe('OrdersService', () => {
  let ordersService: OrdersService;
  let i18nContext: I18nContext;

  beforeAll(async () => {
    const moduleRef = await Test.createTestingModule({
      imports: [AppModule],
    }).compile();
    ordersService = moduleRef.get(OrdersService);
    i18nContext = moduleRef.get(I18nContext);
  });

  it.each([
    [1, '1 produkt'],
    [2, '2 produkty'],
    [5, '5 produktów'],
    [22, '22 produkty'],
  ])('describes %i item(s) in Polish', (quantity, expected) => {
    const order = {
      ...ordersService.findOne(1001),
      items: [{ productId: 'salmon-kibble-2kg', quantity }],
    };
    expect(i18nContext.run('pl', () => ordersService.describeItems(order))).toBe(expected);
  });

  it('falls back to the default locale outside a request', () => {
    const order = ordersService.findOne(1001);
    expect(ordersService.describeItems(order)).toBe('5 items');
  });
});

要用其他词条目录运行应用(例如删掉一条翻译以测试缺失键策略),请在测试模块上替换加载器:overrideProvider(I18nLoader).useValue(new InMemoryI18nLoader(catalogs))。

'throw' 策略能抓住测试覆盖路径上的缺失键。词条目录测试抓住其余的:每个语言环境必须与英文拥有相同的键和占位符,每条复数消息必须包含该语言所需的所有形式。Intl.PluralRules 知道这些形式是哪些:

test/catalogs.spec.ts
import { JsonI18nLoader, type I18nCatalog } from '@nestjs/i18n';
import { join } from 'node:path';

type Message = string | Record<string, string>;

/** 把词条目录摊平成 [key, message] 对;复数形式算作一条消息。 */
function messages(tree: I18nCatalog, prefix = ''): [string, Message][] {
  return Object.entries(tree).flatMap(([name, value]): [string, Message][] =>
    typeof value === 'string' || 'other' in value
      ? [[prefix + name, value as Message]]
      : messages(value, `${prefix}${name}.`),
  );
}

const placeholders = (message: Message) =>
  [...new Set(JSON.stringify(message).match(/\{\w+\}/g))].sort();

const loader = new JsonI18nLoader({ path: join(import.meta.dirname, '../src/i18n') });
const catalogs = await loader.load();
const english = new Map(messages(catalogs.en));

describe.each(Object.keys(catalogs))('the %s catalog', (lang) => {
  const translated = new Map(messages(catalogs[lang]));

  it('has the same keys and placeholders as the English one', () => {
    expect([...translated.keys()].sort()).toEqual([...english.keys()].sort());
    for (const [key, message] of translated) {
      expect(placeholders(message), key).toEqual(placeholders(english.get(key)!));
    }
  });

  it('has every plural form the language needs', () => {
    const forms = new Intl.PluralRules(lang).resolvedOptions().pluralCategories;
    for (const [key, message] of translated) {
      if (typeof message === 'object') {
        expect(Object.keys(message), key).toEqual(expect.arrayContaining(forms));
      }
    }
  });
});

把波兰语 items 消息中的 many 形式删掉,第二个测试就会失败,并列出波兰语需要的形式。

生产检查清单

  • 发布词条目录。 nest build 之后确认 dist/i18n 存在。加载器在启动时读取该目录,目录缺失会导致引导启动失败。
  • 生产用 'fallback',其他地方用 'throw',并在 CI 中运行词条目录测试。留意生产日志中的回退警告。
  • 生产环境关闭 watch。 热重载是开发工具。
  • 固定 supportedLocales。 否则 i18n 下的每个目录都会变成语言环境,包括启用 watch 时运行期间出现的目录。
  • 把需要格式化的区域加入 fallbacks。 未列出的区域会解析为其基础语言,格式化也随之使用基础语言的格式。
  • 在请求之外设置语言环境。 Cron 任务、队列消费者和出站邮件没有请求,因此 I18nService 会退回默认语言环境,t() 函数返回键本身。保存每位顾客偏好的语言环境,并把工作放进 I18nContext.run() 中运行。
  • 留意缓存。 同一 URL 的响应会因 Accept-Language 与 x-lang 而不同。中间件把两者都列进 Vary;请确认你的缓存或 CDN 遵守它。lang 查询参数是 URL 的一部分,无需额外处理。
  • 让 GraphQL 待在全局前缀之下。 使用 setGlobalPrefix() 时,语言环境中间件只覆盖前缀下的路由。给 GraphQLModule 设置 useGlobalPrefix: true,否则解析器上的守卫将看不到语言环境(见本地化 GraphQL 字段)。
  • 转义最终进入 HTML 的消息。 顾客姓名之类的参数会原样插入。这对 JSON 响应没问题,但 HTML 邮件必须像其他文本一样转义消息。
  • 数字与日期交给语言环境,货币与时区不要交给它。 参见格式化价格与日期。

参考

模块选项

I18nModule.forRoot() 接受以下选项。forRootAsync() 通过其工厂(带 inject 的 useFactory,或实现 I18nOptionsFactory 的 useClass/useExisting 类)接受相同的值,而 imports、isGlobal 以及加载器、解析器、格式化器类留在顶层。参见来自配置的选项。解析后的选项可以通过 I18N_MODULE_OPTIONS 标记注入。

选项 默认值 说明
loader 必填 词条目录的来源:I18nLoader 实例(如 JsonI18nLoader),或由 Nest 实例化的加载器类。参见添加词条目录并注册模块。
resolvers [new AcceptLanguageLocaleResolver()] 语言环境解析器,按顺序尝试:实例,或由 Nest 实例化的类。
formatter 内置语法 I18nMessageFormatter 实例,或由 Nest 实例化的类,把消息转成文本。参见使用 ICU 消息语法。
defaultLocale 'en' 没有任何解析器找到受支持语言环境时使用,请求之外也使用。
supportedLocales 已加载的语言环境 请求可以得到的语言环境,以 BCP 47 标签表示。
fallbacks 无 把一个语言环境映射到其消息来源语言环境的对象,例如 'de-AT': 'de'。键也算作受支持的语言环境。
missingKey 'fallback' 缺失键的返回方式:'fallback'、'key'、'empty'、'throw',或接收键与语言环境的函数。参见处理缺失的键并重载词条目录。
logMissingKeys 'once' 对缺失键和默认语言环境回退发出警告:每个键 'once'、'always' 或 'never'。
responseHeaders true 在 HTTP 响应上设置 Content-Language 与 Vary。
imports 无 加载器、解析器、格式化器类所注入的提供者所在的模块。
isGlobal true 全局注册该模块。

JsonI18nLoader 接受 path(包含每个语言环境一个子目录的目录)和 watch(默认 false,文件变化时重载词条目录)。InMemoryI18nLoader 接受以语言环境为键的词条目录对象。

语言环境解析器

解析器 读取 默认名称
QueryLocaleResolver 查询参数 lang
HeaderLocaleResolver 请求头 x-lang
AcceptLanguageLocaleResolver Accept-Language,按 q 值排序 无
CookieLocaleResolver Cookie 请求头中的 cookie lang

自定义解析器继承 LocaleResolver 并实现 resolve(),它接收请求的 headers 与 query,返回一个候选、候选列表或什么都不返回。它在 varyHeaders 中列出自己读取的请求头。设置 afterGuards 后,它在守卫之后运行并保持原排名,同时接收 executionContext——对微服务、WebSocket 网关和 GraphQL 订阅,所有解析器都是如此。参见使用顾客保存的语言。

翻译 API

  • I18nService.t(key, options):按当前语言环境翻译。options 接受 args(占位符值,数字 count 会选择复数形式)和 locale(显式语言环境)。参见翻译订单确认。I18nService<OtherTranslations> 按另一种词条目录形状检查键。
  • I18nService.translate(key, options):同上,但键不做检查,适用于运行时构建的键。
  • I18nService.exists(key, locale):某个键是否有消息。
  • I18nService.formatNumber(value, options) 与 formatDate(value, options):按当前语言环境做 Intl 格式化,接受常规 Intl 选项外加 locale。参见格式化价格与日期。
  • I18nService.matchLocale(candidate):把某个语言环境(例如档案中保存的)映射为受支持的语言环境,或 undefined。
  • I18nService.defaultLocale 与 supportedLocales:已配置的语言环境,供语言选择器使用。
  • I18nContext.locale 与 I18nContext.run(locale, fn):读取当前语言环境,或为请求之外的代码设置当前语言环境。
  • I18nContext.setLocale(locale):改变本次请求余下部分的语言环境,并返回匹配到的语言环境;不支持时返回 undefined 且不做改变。它在请求之外抛出,也会在微服务、WebSocket 网关和 GraphQL 订阅的守卫中抛出(守卫在语言环境解析之前运行)。
  • @CurrentLocale():把当前语言环境作为处理器参数。
  • t(key, options):为没有依赖注入的代码提供 I18nService.t()。在请求之外,它返回键本身。参见本地化异常。

校验

导出 说明
I18nValidationPipe 接受 ValidationPipe 选项,外加 namespace(默认 'validation')用于约束消息。参见本地化校验消息。
I18nStandardSchemaValidationPipe 接受 StandardSchemaValidationPipe 选项,外加 namespace 和 issueKeys(为某个问题返回额外候选键的函数)。参见使用 Zod。
i18nValidationMessage(key, args) 把某个 class-validator 约束指向一个键。
i18nIssueMessage(key, args) 把某个 Standard Schema 问题指向一个键。
translateValidationErrors(errors, options) 翻译 class-validator 错误,供自建管道使用。
translateStandardSchemaIssues(issues, options) 翻译 Standard Schema 问题,供自建管道使用。

错误

错误 触发时机
I18nMissingKeyError 在 missingKey: 'throw' 下缺少某个键。它携带 key 与 locale,且不是 HttpException,因此请求以 500 失败。