Search code examples
localizationnestjsnestjs-i18n

Integrate `nestjs-i18n` in NestJS interceptor


I have created an interceptor ContentTypeInterceptor and want to use nestjs-i18n to send a local message while violating the content-type. I wrote the below codes but it was not working. I explored and got the solution, Please find my solution in the answer section.

'use strict'
import { CallHandler, ExecutionContext, NestInterceptor, UnsupportedMediaTypeException } from '@nestjs/common'
import { Request } from 'express'
import { I18nContext, I18nTranslation } from 'nestjs-i18n'

export class ContentTypeInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    const i18n: any = I18nContext.current<I18nTranslation>(next)
    console.log('i18n:',i18n?.t('lang.HELLO'))
    const request = context.switchToHttp().getRequest<Request>()

    if (this.hasBody(request.method) && !request.is('json')) {
      throw new UnsupportedMediaTypeException(i18n?.t('lang.GENERIC.UNSUPPORTED_MEDIA_TYPE_MESSAGE'))
    }

    return next.handle()
  } 

  private hasBody(httpMethod: string): boolean {
    return ['POST', 'PUT', 'PATCH'].includes(httpMethod)
  }
}

Solution

  • This is how I resolved the issue. I use I18nContext and I18nContext.current() to call the function for translation.

    'use strict'
    import { CallHandler, ExecutionContext, NestInterceptor, UnsupportedMediaTypeException } from '@nestjs/common'
    import { Request } from 'express'
    import { I18nContext } from 'nestjs-i18n'
    
    export class ContentTypeInterceptor implements NestInterceptor {
      intercept(context: ExecutionContext, next: CallHandler) {
        const i18n = I18nContext.current();
        const request = context.switchToHttp().getRequest<Request>()
    
        if (this.hasBody(request.method) && !request.is('json')) {
          throw new UnsupportedMediaTypeException(i18n?.t('lang.GENERIC.UNSUPPORTED_MEDIA_TYPE_MESSAGE'))
        }
    
        return next.handle()
      }
    
      private hasBody(httpMethod: string): boolean {
        return ['POST', 'PUT', 'PATCH'].includes(httpMethod)
      }
    }