src/common/locale.interceptor.ts
Properties |
|
Methods |
|
constructor(utilsService: UtilsService)
|
||||||
|
Defined in src/common/locale.interceptor.ts:18
|
||||||
|
Parameters :
|
| intercept | |||||||||
intercept(context: ExecutionContext, next: CallHandler)
|
|||||||||
|
Defined in src/common/locale.interceptor.ts:26
|
|||||||||
|
Parameters :
Returns :
Observable<any>
|
| Private modifyDataSafely | |||||||||
modifyDataSafely(o: HttpException, locale: string)
|
|||||||||
|
Defined in src/common/locale.interceptor.ts:21
|
|||||||||
|
Parameters :
Returns :
Object
|
| Private Readonly logger |
Default value : new Logger(LocaleInterceptor.name)
|
|
Defined in src/common/locale.interceptor.ts:18
|
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;
}),
);
}
}