toonvanstrijp / nestjs-i18n

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

I18nRequestScopeService does not work with gRPC #223

Closed davidramosweb closed 3 years ago

davidramosweb commented 3 years ago

I18nRequestScopeService gets the i18nLang from REQUEST (this.req.i18nLang), but when using gRPC, the interceptor stores this information in context and the service does not get the variable correctly. https://github.com/ToonvanStrijp/nestjs-i18n/blob/master/src/utils/context.ts

case 'rpc':
        return context.switchToRpc().getContext();

Using gRPC, i18nLang is not in the root of the object but inside context:

I18nRequestScopeService {
  req: RequestContextHost {
    pattern: {
      service: 'EmailService',
      rpc: 'sendRegistrationConfirmEmail',
      streaming: 'no_stream'
    },
    data: {
      email: 'test@davidramosweb.com',
    },
    context: Metadata {
      internalRepr: [Map],
      options: {},
      i18nService: [I18nService],
      i18nLang: 'fr'
    }
  },

A possible solution could be to check if this.req.context.i18nLang exists: https://github.com/ToonvanStrijp/nestjs-i18n/blob/master/src/services/i18n-request-scope.service.ts

@Injectable({ scope: Scope.REQUEST })
export class I18nRequestScopeService {
  constructor(
    @Inject(REQUEST) private readonly req,
    private readonly i18nService: I18nService,
  ) {}

  public translate(key: string, options?: translateOptions) {
    const lang = (!this.req.i18nLang && this.req.context) ? this.req.context.i18nLang : this.req.i18nLang;
    options = {
        lang,
      ...options,
    };
    return this.i18nService.translate(key, options);
  }

  public t(key: string, options?: translateOptions) {
    return this.translate(key, options);
  }
}
toonvanstrijp commented 3 years ago

Heey @davidramosweb thanks for noticing this issue. I’m quite busy today but if you could make a pull request and add test cases for this that would be great!