嘿在我的 nestjs 应用程序中,我已经安装了版本 10.2.6 的 nestjs-i18n npm 包。我在 appModule 中配置了这个 I18nModule 如下:
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { PrismaModule } from './config/database';
import { SessionModule } from './modules/session/session.module';
import {
I18nModule,
QueryResolver,
AcceptLanguageResolver,
HeaderResolver,
} from 'nestjs-i18n';
import * as path from 'path';
import { I18nMiddleware } from './common/hooks/i18n/i18n.middleware';
@Module({
imports: [
PrismaModule,
SessionModule,
ConfigModule.forRoot({ isGlobal: true }),
I18nModule.forRoot({
fallbackLanguage: 'en',
fallbacks: {
'en-CA': 'fr',
'en-*': 'en',
'fr-*': 'fr',
pt: 'pt-BR',
},
loaderOptions: {
path: path.join(__dirname, '/i18n/'),
watch: true,
},
resolvers: [
{
use: QueryResolver,
options: ['lang'],
},
new HeaderResolver(['x-content-lang']),
AcceptLanguageResolver,
],
}),
],
controllers: [],
providers: [],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(I18nMiddleware).forRoutes('*');
}
}
我也有多种语言的 json 文件,结构如下:
src Folder
|
|-i18n Folder
|
|--en Folder
|
|--en.json
| --fr Folder
|
| -- fr.json
| --etc
我在 nest-cli.json 中配置如下:
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"assets": [
{
"include": "i18n/**/*",
"watchAssets":true
}
]
}
}
我想使用 accept-language 标头来获取用户首选的语言来相应地翻译变量。所以我决定实施中间件来实现它。但我不知道如何在 nestjs-i18n 包中做到这一点。请有人帮我做这个:
在此分享我写的中间件:
import { Injectable, NestMiddleware } from '@nestjs/common';
import { FastifyRequest, FastifyReply } from 'fastify';
@Injectable()
export class I18nMiddleware implements NestMiddleware {
constructor() {}
async use(req: FastifyRequest, res: FastifyReply, next: () => void) {
const lang = req.headers['accept-language']?.toString();
console.log('............lang', lang);
if (lang) {
**// I want to what to write here to make the language received from the header**
}
next();
}
}
所以请帮助我。提前致谢。