이번 글에서는 Nest.js에서 User라는 커스템 데코레이터를 사용하여 request header에 있는 jwt 를 받아오는 방법을 알아보겠습니다
실행 절차는 아래와 같이 됩니다.
코드 살펴보기
//main.ts
@Module({
imports: [UserModule, PrismaModule, HomeModule],
controllers: [AppController],
providers: [
AppService,
{ provide: APP_INTERCEPTOR, useClass: UserInterceptor },
],
})
export class AppModule {}
//src/user/interceptors/user.interceptor.ts
import { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
import { Observable } from 'rxjs';
import * as jwt from 'jsonwebtoken';
export class UserInterceptor implements NestInterceptor {
intercept(
context: ExecutionContext,
next: CallHandler<any>,
): Observable<any> | Promise<Observable<any>> {
const request = context.switchToHttp().getRequest();
const token = request?.headers?.autorization.split('Bearer ')[1];
const user = jwt.decode(token);
request.user = user;
return next.handle();
}
}
//src/decorators/user.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export interface UserInfo {
name: string;
id: number;
iat: number;
exp: number;
}
export const User = createParamDecorator((context: ExecutionContext) => {
const request = context.switchToHttp().getRequest();
return request.user as UserInfo;
});
@Post()
createHome(@Body() body: CreateHomeDto, @User() user: UserInfo) {
return this.homeService.createHome(body, user.id);
}