-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: added empty string to null converter interceptor
- Loading branch information
1 parent
e742f0a
commit df51d73
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
apps/web-api/src/interceptors/empty-string-to-null.interceptor.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
|