Jenya7771
Jenya7771

Reputation: 41

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

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

Upvotes: 1

Views: 174

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70490

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.

Upvotes: 0

Related Questions