인터셉터
Last updated
Last updated
// interceptors/serialize.interceptor.ts
import { UseInterceptors, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from 'rxjs/operators';
import { plainToClass } from "class-transformer";
export class SerializeInterceptor implements NestInterceptor {
intercept(context : ExecutionContext, handler : CallHandler) : Observable<any> {
console.log('running before the handler', context)
return handler.handle().pipe(
map((data : any) => {
console.log('running before response send out', data)
})
)
}
}
// user.controller.ts
...
import { SerializeInterceptor } from 'src/interceptors/serialize.interceptor';
...
@UseInterceptors(SerializeInterceptor)
@Get('/:id')
async findUser(@Param('id') id : string) {
const user = await this.userService.findOne(parseInt(id))
if(!user) {
throw new NotFoundException('user not found')
}
return user
}
...
// user.dto.ts
import { Expose } from 'class-transformer'
export class UserDto {
@Expose()
id : number;
@Expose()
email : string;
}
// serialize.interceptor.ts
import { UseInterceptors, NestInterceptor, ExecutionContext, CallHandler } from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from 'rxjs/operators';
import { plainToClass } from "class-transformer";
import { UserDto } from "src/users/dtos/user.dto";
export class SerializeInterceptor implements NestInterceptor {
intercept(context : ExecutionContext, handler : CallHandler) : Observable<any> {
return handler.handle().pipe(
map((data : any) => {
return plainToClass(UserDto, data, {
excludeExtraneousValues : true
})
})
)
}
}// users.controller.ts
import {UserDto} from './dtos/user.dto'
...
@UseInterceptors(new SerializeInterceptor(UserDto))
@Get('/:id')
async findUser(@Param('id') id : string) {
const user = await this.userService.findOne(parseInt(id))
if(!user) {
throw new NotFoundException('user not found')
}
return user
}
...
// serialize.interceptor.ts
export class SerializeInterceptor implements NestInterceptor {
constructor (private dto : any) {}
intercept(context : ExecutionContext, handler : CallHandler) : Observable<any> {
return handler.handle().pipe(
map((data : any) => {
return plainToClass(this.dto, data, {
excludeExtraneousValues : true
})
})
)
}
}