nestjs-i18n-2
v9.1.8
Published
The i18n module for Nest. Replace field `data` by `data` in response. Translate `Bad Request` to your language
Downloads
4
Readme
nestjs-i18n-2
This is a fork version from nestjs-i18n. This package help you to translate message
, instead of default "Bad Request" message. Your input invalid errors[]
now change to data[]
field. You can make same API response structure in every case of HTTP Status.
Example API response:
{
"statusCode": 400,
"message": "Invalid input",
"data": [
{
"field": "username",
"error": "Invalid phone number."
}
]
}
Installation
npm i nestjs-i18n-2
or custom version:
npm i [email protected]
Note: Just install nestjs-i18n-2
or nestjs-i18n
only. You should remove one package:
npm uninstall nestjs-i18n
Update your import (from nestjs-i18n
to nestjs-i18n-2
) in any files in /src
. The best method is use replace in all file feature in your editor.
Usage (nestjs-i18n-2)
- Enable i18n validation in
main.ts
// after const app = await NestFactory.create(AppModule) app.useGlobalPipes( new ValidationPipe({ exceptionFactory: i18nValidationErrorFactory, transform: true, }), );
- (Optional) Custom your
data[]
like as example API responseapp.useGlobalFilters(new I18nValidationExceptionFilter({ errorFormatter(data: ValidationError[]) { let customErrors: any[] = [] data.forEach(error => { let element = {} as any element.field = error.property let errorStringJoin: string = "" for (let type in error.constraints) { errorStringJoin = errorStringJoin + error.constraints[type] + ". " } element.error = errorStringJoin.trim() customErrors.push(element) }); return customErrors } }));
- Import
I18nModule
toAppModule
as root module Open app.module.ts then import module:imports: [ I18nModule.forRoot({ fallbackLanguage: 'en', // set a default language, loaderOptions: { path: path.join(__dirname, '/i18n/'), watch: true, }, resolvers: [ { use: QueryResolver, options: ['lang'] }, AcceptLanguageResolver, ], }),]
- Write you language JSON file
4.1. Create
i18n
folder if not exist:
4.2. Createproject: ├───src │ ├───i18n │ │ ├───en (this folder is for English) │ │ ├───fr (this folder is for French) │ │ ├───vi │ │ ├───... more language as you want... │ │ └───_code (this folder is custom for your status code... if you use `nestjs-custom-response` package).
response.json
for multi-language Create filesrc\i18n\en\response.json
:
Create a translated file in your language(my language is{ "message": { "inputInvalid":"Invalid input" } }
vi
, so I createdsrc\i18n\vi\response.json
):{ "message": { "inputInvalid":"Thông tin đầu vào không đúng" } }
More infomation
This is a fork package, so you can read orginal package document here: