Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to architecture server side i18n

Tags:

nestjs

I'm using nestjs to create my REST API, and I got the requirement to support i18n for all the messages that the API returns (exception messages, hints, and so on) and I'm wondering what is the better way to do it with nestjs framework.

With plain express, I can get the user language from the request headers, and that can be translated to a Nestjs Middleware in order to put the language code into someware that lives in the request execution context and then using from my i18n service (I do not want to add language parameters everyware I need the user language) What do you think? Is it a propper architecture to resolve my requirement? Which is the best place to put the language for the current request?

like image 767
Jose Selesan Avatar asked Jan 10 '18 20:01

Jose Selesan


3 Answers

I'd use i18-node package https://github.com/mashpie/i18n-node, is compatible with express, and therefore there are no contradictions to use it with Nest as well. Also, I'd recommend registering a custom decorator as a wrapper around res.__ call.

like image 179
Kamil Myśliwiec Avatar answered Oct 01 '22 15:10

Kamil Myśliwiec


I've been using Nestjs-i18n package.

It contains built-in features such as I18nService and I18nLang decorator.

like image 30
Willian Avatar answered Oct 01 '22 15:10

Willian


I don't think there is a way to get the language code in a service without passing it as a parameter. If you want to access the language code from your services, you will have to pass it as a parameter, or retrieve the language code associated to the user object from another place.

I handle translations in my app as following:

I have a Language decorator for handling the 'accept-language' header overriding by client:

export const Language = createRouteParamDecorator((data, req) => {
if (!req.body.lang) return req.getLocale();
return req.body.lang;
});

And use it like this in a controller:

@Post()
public async testLocale(@Req() req, @Language() locale) {
   return this.myService.someMethod(someParam, locale);
}
like image 34
Antoine Avatar answered Oct 01 '22 13:10

Antoine