Last active
August 22, 2025 15:55
-
-
Save devhammed/75a5fb90c2d0b468aa2bf332e254e960 to your computer and use it in GitHub Desktop.
Custom Class Serializer Interceptor (support for automatically adding user roles)
This file contains hidden or 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
import { | |
Injectable, | |
ExecutionContext, | |
CallHandler, | |
ClassSerializerInterceptor, | |
PlainLiteralObject, | |
} from '@nestjs/common'; | |
import { Request } from 'express'; | |
import { Observable } from 'rxjs'; | |
import { map } from 'rxjs/operators'; | |
@Injectable() | |
export class CustomClassSerializerInterceptor extends ClassSerializerInterceptor { | |
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> { | |
const request = context.switchToHttp().getRequest<Request>(); | |
const user = request.user; | |
const groups = user ? [user.role.toString()] : []; | |
const contextOptions = this.getContextOptions(context); | |
const options = { | |
...this.defaultOptions, | |
...contextOptions, | |
groups: [...groups, ...(contextOptions?.groups ?? [])], | |
}; | |
return next | |
.handle() | |
.pipe( | |
map((res: PlainLiteralObject | PlainLiteralObject[]) => | |
this.serialize(res, options), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment