toonvanstrijp / nestjs-i18n

The i18n module for nestjs.
https://nestjs-i18n.com
Other
642 stars 106 forks source link

how can i get I18nContext or lang in xxx.service.ts without @i18n in controller #493

Closed cckit225 closed 1 year ago

cckit225 commented 1 year ago

In microservice project, i call the service from gateway with "accept-language". If i use I18nContext.current().t('xxxxx') in xxx.service.ts without using @I18n() in controller, it will be translated with fallbacklanguage. how can i use I18nContext without passing @I18n() in each function or get the correct lang in service.ts??

itinance commented 1 year ago

I found a solution to just pass the I18nService into any other service:

export class TokensService {
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  constructor(private readonly i18n: I18nService) {}

This way, we can easily write:

console.log("TRANSLATE", await this.i18n.t('HELLO'));

But there is a drawback that in Unit-tests, the translation will not translate at all and instead only return the key (#495) .

rubiin commented 1 year ago

Before 10, you can use I18nRequestScopeService. But as of version 10 and above, I18nRequestScopeService is removed . This because we now have async_hooks support. This allows you to get the current I18nContext by doing I18nContext.current(). That being said, you can follow here for translation for services https://github.com/toonvanstrijp/nestjs-i18n/blob/main/samples/simple/src/app.service.ts. Feel free to open if the issue persists