Skip to content

Instantly share code, notes, and snippets.

@ibayazit
Created April 13, 2023 08:58
Show Gist options
  • Save ibayazit/dee57afc274297490e7265bcf4da63ab to your computer and use it in GitHub Desktop.
Save ibayazit/dee57afc274297490e7265bcf4da63ab to your computer and use it in GitHub Desktop.
NestJS format outgoing response
import {
UseInterceptors,
NestInterceptor,
ExecutionContext,
CallHandler
} from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from "rxjs";
import { plainToInstance } from "class-transformer";
interface ClassConstructor {
new(...args: any[]): {}
}
export function Serialize(dto: ClassConstructor) {
return UseInterceptors(new SerializeInterceptor(dto));
}
export class SerializeInterceptor implements NestInterceptor {
constructor(private dto: ClassConstructor) { }
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((data: ClassConstructor) => {
return {
data: plainToInstance(this.dto, data, {
excludeExtraneousValues: true
})
};
})
);
}
}
import { Expose, Exclude } from "class-transformer";
export class UserDto{
@Expose()
id: number;
@Expose()
email: string;
@Exclude()
password: string;
}
...
import { Serialize } from '../interceptors/serialize.interceptor';
import { UserDto } from './dtos/user.dto';
@Serialize(UserDto)
@Controller('auth')
export class UsersController {
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment