From df51d73767c495dd9139022fd8239ee7b440b87e Mon Sep 17 00:00:00 2001 From: Navaneethakrishnan Date: Thu, 1 Aug 2024 13:43:18 +0530 Subject: [PATCH] feat: added empty string to null converter interceptor --- apps/web-api/src/app.module.ts | 5 +++ .../empty-string-to-null.interceptor.ts | 35 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 apps/web-api/src/interceptors/empty-string-to-null.interceptor.ts diff --git a/apps/web-api/src/app.module.ts b/apps/web-api/src/app.module.ts index 4bae06eaf..bc087f694 100644 --- a/apps/web-api/src/app.module.ts +++ b/apps/web-api/src/app.module.ts @@ -37,6 +37,7 @@ import { PLEventsModule } from './pl-events/pl-events.module'; import { OfficeHoursModule } from './office-hours/office-hours.module'; import { MemberFollowUpsModule } from './member-follow-ups/member-follow-ups.module'; import { MemberFeedbacksModule } from './member-feedbacks/member-feedbacks.module'; +import { EmptyStringToNullInterceptor } from './interceptors/empty-string-to-null.interceptor'; @Module({ controllers: [AppController], @@ -104,6 +105,10 @@ import { MemberFeedbacksModule } from './member-feedbacks/member-feedbacks.modul provide: APP_INTERCEPTOR, useClass: ConcealEntityIDInterceptor, }, + { + provide: APP_INTERCEPTOR, + useClass: EmptyStringToNullInterceptor + }, { provide: APP_FILTER, useClass: LogException diff --git a/apps/web-api/src/interceptors/empty-string-to-null.interceptor.ts b/apps/web-api/src/interceptors/empty-string-to-null.interceptor.ts new file mode 100644 index 000000000..e0cc8b170 --- /dev/null +++ b/apps/web-api/src/interceptors/empty-string-to-null.interceptor.ts @@ -0,0 +1,35 @@ +import { + Injectable, + NestInterceptor, + ExecutionContext, + CallHandler +} from '@nestjs/common'; +import { Observable } from 'rxjs'; + +@Injectable() +export class EmptyStringToNullInterceptor implements NestInterceptor { + intercept(context: ExecutionContext, next: CallHandler): Observable { + const request = context.switchToHttp().getRequest(); + const method = request.method; + if (method === 'POST' || method === 'PUT' || method === 'PATCH') { + request.body = this.convertEmptyStringsToNull(request.body); + } + return next.handle(); + } + + private convertEmptyStringsToNull(obj: any): any { + if (typeof obj === 'string') { + return obj === '' ? null : obj; + } else if (Array.isArray(obj)) { + return obj.map((item) => this.convertEmptyStringsToNull(item)); + } else if (typeof obj === 'object' && obj !== null) { + const newObj: any = {}; + for (const key of Object.keys(obj)) { + newObj[key] = this.convertEmptyStringsToNull(obj[key]); + } + return newObj; + } + return obj; + } +} + \ No newline at end of file