How can I change the name of the template that is passed to the @Render decorator in the Interceptor?

142 views Asked by At

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

There are 1 answers

6
Jay McDoniel On

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.