Skip to content

Instantly share code, notes, and snippets.

@ahmadarif
Created September 10, 2019 14:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmadarif/94f287213eb1b0cec68df3297ef3924f to your computer and use it in GitHub Desktop.
Save ahmadarif/94f287213eb1b0cec68df3297ef3924f to your computer and use it in GitHub Desktop.
Nest - UndefinedInterceptor
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class UndefinedInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next
.handle()
.pipe(map(value => this.traverse(value)));
}
traverse(data: any) {
for (const key in data) {
if (typeof data[key] === 'undefined') {
data[key] = null;
}
if (data[key] !== null && typeof(data[key]) === 'object') {
this.traverse(data[key]);
}
}
return data;
}
}
@ahmadarif
Copy link
Author

Add this line to main.ts file

app.useGlobalInterceptors(new UndefinedInterceptor());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment