Skip to content

Commit

Permalink
feat: added empty string to null converter interceptor
Browse files Browse the repository at this point in the history
  • Loading branch information
navneethkrish committed Aug 1, 2024
1 parent e742f0a commit df51d73
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
5 changes: 5 additions & 0 deletions apps/web-api/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down Expand Up @@ -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
Expand Down
35 changes: 35 additions & 0 deletions apps/web-api/src/interceptors/empty-string-to-null.interceptor.ts
Original file line number Diff line number Diff line change
@@ -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<any> {
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;
}
}

0 comments on commit df51d73

Please sign in to comment.