You need to enable JavaScript to run this app. NestJS+TypeORM字段本地化求助:nest-typeorm-i18n用法及替代方案
优惠活动
大模型
产品
解决方案
定价
更多

NestJS+TypeORM字段本地化求助:nest-typeorm-i18n用法及替代方案

Hey there! Let's break down how to handle field localization in your NestJS + TypeORM app, whether you want to use vlzh/nest-typeorm-i18n (the recommended package for NestJS users) or explore more flexible alternatives.


Using vlzh/nest-typeorm-i18n

Since the original typeorm-i18n directs NestJS users to this fork, here's a step-by-step guide to get it working (even without official docs):

Step 1: Install Dependencies

First, install the package and its core dependency:

npm install vlzh/nest-typeorm-i18n typeorm-i18n
# or with yarn
yarn add vlzh/nest-typeorm-i18n typeorm-i18n

Step 2: Configure the Module in AppModule

Import the NestTypeOrmI18nModule after your TypeOrmModule setup, defining your default language and supported languages:

import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { NestTypeOrmI18nModule } from 'nest-typeorm-i18n';
import { Product } from './entities/product.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      // Your existing TypeORM config (database type, host, etc.)
      entities: [Product],
    }),
    NestTypeOrmI18nModule.forRoot({
      defaultLanguage: 'en',
      languages: ['en', 'fr', 'es'], // Add all languages you need
    }),
  ],
})
export class AppModule {}

Step 3: Add Localized Columns to Your Entity

Use the @I18nColumn decorator (from typeorm-i18n) on fields that need localization. This will automatically create separate columns or a dedicated translation table (depending on your TypeORM setup):

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
import { I18nColumn } from 'typeorm-i18n';

@Entity()
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  // Regular non-localized field
  @Column()
  sku: string;

  // Localized fields
  @I18nColumn()
  name: string;

  @I18nColumn({ type: 'text' })
  description: string;
}

Step 4: Use the I18nService in Your Services

Inject the I18nService to save and retrieve localized data. Here's an example service for products:

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from './entities/product.entity';
import { I18nService } from 'nest-typeorm-i18n';

@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(Product)
    private readonly productRepo: Repository<Product>,
    private readonly i18nService: I18nService,
  ) {}

  // Create a product with localized values for a specific language
  async create(lang: string, productData: { sku: string; name: string; description: string }) {
    const product = this.productRepo.create({ sku: productData.sku });
    // Save the translated values for the given language
    await this.i18nService.save(product, lang, {
      name: productData.name,
      description: productData.description,
    });
    return this.productRepo.save(product);
  }

  // Fetch a product with translations for a specific language
  async getOne(id: number, lang: string) {
    const product = await this.productRepo.findOneBy({ id });
    // Translate the product to the requested language (falls back to default if missing)
    return this.i18nService.translate(product, lang);
  }
}

Step 5: Handle Language in Controllers

Accept the desired language from a query parameter, header, or request context, then pass it to your service:

import { Controller, Get, Post, Body, Param, Query } from '@nestjs/common';
import { ProductService } from './product.service';

@Controller('products')
export class ProductController {
  constructor(private readonly productService: ProductService) {}

  @Post()
  create(
    @Query('lang') lang: string = 'en', // Default to English if no lang is provided
    @Body() body: { sku: string; name: string; description: string },
  ) {
    return this.productService.create(lang, body);
  }

  @Get(':id')
  findOne(@Param('id') id: string, @Query('lang') lang: string = 'en') {
    return this.productService.getOne(+id, lang);
  }
}

Alternative Solution: Custom Localization with Associated Tables

If vlzh/nest-typeorm-i18n feels too restrictive, building your own localization setup with associated tables gives you full control. Here's how:

Entity Setup

Create a main entity and a separate translation entity linked via a one-to-many relationship:

// product.entity.ts
import { Entity, Column, PrimaryGeneratedColumn, OneToMany } from 'typeorm';
import { ProductI18n } from './product-i18n.entity';

@Entity()
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  sku: string;

  @OneToMany(() => ProductI18n, translation => translation.product, { cascade: true })
  translations: ProductI18n[];
}

// product-i18n.entity.ts
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne } from 'typeorm';
import { Product } from './product.entity';

@Entity()
export class ProductI18n {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  lang: string; // e.g., 'en', 'fr', 'es'

  @Column()
  name: string;

  @Column('text')
  description: string;

  @ManyToOne(() => Product, product => product.translations)
  product: Product;
}

Querying Localized Data

Use TypeORM's query builder to fetch the main entity along with the correct translation:

async getProductWithTranslation(id: number, lang: string) {
  return this.productRepo.findOne({
    where: { id },
    relations: ['translations'],
    select: {
      id: true,
      sku: true,
      translations: {
        name: true,
        description: true,
      },
    },
    where: {
      id,
      translations: { lang },
    },
  });
}

This approach is great for complex scenarios where you need to manage multiple translations simultaneously or add custom logic to localization.


Final Thoughts
  • Use vlzh/nest-typeorm-i18n if you want a quick, out-of-the-box solution that integrates seamlessly with NestJS and TypeORM.
  • Build a custom associated table setup if you need flexibility (e.g., custom validation, additional translation metadata, or complex querying).

Both approaches will get the job done—pick the one that fits your app's needs best!

内容的提问来源于stack exchange,提问作者Hani Ghazi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 10:42:33