File

src/common/locale.interceptor.ts

Index

Properties
Methods

Constructor

constructor(utilsService: UtilsService)
Parameters :
Name Type Optional
utilsService UtilsService No

Methods

intercept
intercept(context: ExecutionContext, next: CallHandler)
Parameters :
Name Type Optional
context ExecutionContext No
next CallHandler No
Returns : Observable<any>
Private modifyDataSafely
modifyDataSafely(o: HttpException, locale: string)
Parameters :
Name Type Optional
o HttpException No
locale string No
Returns : Object

Properties

Private Readonly logger
Default value : new Logger(LocaleInterceptor.name)
import {
  CallHandler,
  ExecutionContext,
  HttpException,
  Injectable,
  Logger,
  NestInterceptor,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';
import { FastifyRequest } from 'fastify';
import { UtilsService } from '../utils/utils.service';
import GetLocale from '../locales/getter';
import { catchError } from 'rxjs/operators';
import { IsUrlSafe } from './decorators/urlsafe.decorator';

@Injectable()
export class LocaleInterceptor implements NestInterceptor {
  private readonly logger = new Logger(LocaleInterceptor.name);
  constructor(private readonly utilsService: UtilsService) {}

  private modifyDataSafely(o: HttpException, locale: string): Object {
    o.message = locale;
    return o;
  }

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context
      .switchToHttp()
      .getRequest<FastifyRequest<{ Headers: { Locale: string } }>>();

    return next.handle().pipe(
      map((data) => {
        if (
          typeof data === 'string' &&
          this.utilsService.isUpper(data) &&
          data.length < 50 &&
          !this.utilsService.isUrl(data) &&
          !this.utilsService.isOnlyDigit(data) &&
          !this.utilsService.isImage(data)
        ) {
          return {
            locale: GetLocale(data, req.headers.Locale || 'en'),
            raw: data,
          };
        } else {
          return this.utilsService.deeplyLocalizeObject(
            data,
            req.headers.Locale || 'en',
          );
        }
      }),
      catchError(async (data: HttpException) => {
        const locale = await GetLocale(data.message, req.headers.Locale || 'en');
        const m = this.modifyDataSafely(data, locale);
        throw m;
      }),
    );
  }
}

results matching ""

    No results matching ""