1

How can I change the name of the template that is passed to the @Render decorator in the Interceptor? I need to add the desired locale to the template url, depending on the user's language. I'm trying to do this, but it doesn't work. How can I do this?

@Injectable()
export class RenderByLanguageInterceptor implements NestInterceptor {
  constructor(private reflector: Reflector) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const template = this.reflector.getAllAndOverride<string>(RENDER_METADATA, [
          context.getHandler(),
          context.getClass(),
    ]);

    const lang = context.switchToHttp().getRequest().i18nLang;
    SetMetadata(RENDER_METADATA, `${lang}/${template}`);

    return next.handle();
  }
}
H3AR7B3A7
  • 4,366
  • 2
  • 14
  • 37
Jenya7771
  • 21
  • 1

1 Answers1

0

SetMetadata is a decorator from Nest's library as a helper function. What you're needing to do is use the Reflect API and do something along the lines of

Reflect.defineMetadata(
  RENDER_METADATA,
  `${lang}/${tempalte}`,
  context.getClass(),
  context.getHandler()
);

Where Reflect is from reflect-metadata. This should set the metadata appropriately, so it can be read later. With this approach, you will have to make sure the metadata is set every time, as there's no falling back to the original metadata in the @Render() decorator.

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • The problem is that I can't get context. switch To Http ().GetRequest().i18nlang, it looks like it's not in the context yet, how do I get it after i18nLang appears in the context? – Jenya7771 Sep 26 '21 at 19:26
  • When does `i18nlang` appear on the req object? How does that get populated? – Jay McDoniel Sep 26 '21 at 19:30
  • To the AppModule to imports – Jenya7771 Sep 26 '21 at 19:31
  • The AppModule's imports dont affect the request object per request. The AppModule is just there for defining the the modules, providers, and controllers used in the application – Jay McDoniel Sep 26 '21 at 19:38
  • return next.handle().pipe( map((data) => { const lang = context.switchToHttp().getRequest().i18nLang; console.log(lang); return data; }), ); - This is how I can get lang. How else can I solve my problem, with changing the template path depending on the user's language? – Jenya7771 Sep 26 '21 at 19:50
  • Just do the `Reflect.defineMetadata` in another `tap` after that `map`? I don't know what the new problem is. The above metadata re-definition should be what you're looking for – Jay McDoniel Sep 26 '21 at 19:58