Best way to architecture server side i18n

时光毁灭记忆、已成空白 提交于 2020-06-12 06:40:11

问题


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?


回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/48195353/best-way-to-architecture-server-side-i18n

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!