π©π» λ°±μλ(Back-End)/Nest js
[Nest JS λ‘ CRUD κ²μν λ§λ€κΈ°] (29) 컀μ€ν λ°μ½λ μ΄ν° μμ±νκΈ°
μ§μ§μνμΉ΄
2023. 6. 9. 11:16
728x90
λ°μν
<λ³Έ λΈλ‘κ·Έλ John Ahn μ μ νλΈλ₯Ό μ°Έκ³ ν΄μ 곡λΆνλ©° μμ±νμμ΅λλ€ :-)>
=> λ°λΌνλ©΄μ λ°°μ°λ NestJS
𧸠컀μ€ν λ°μ½λ μ΄ν° μμ±νκΈ°
π get-decorator.ts
import { ExecutionContext, createParamDecorator } from "@nestjs/common";
import { User } from "./user.entity";
// 컀μ€ν
λ°μ½λ μ΄ν° μμ±ν¨
// req.user κ° μλ user νλΌλ§ν°λ‘ λ°λ‘ μ μ κ°μ²΄ κ°κ³ μ€κΈ°
export const GetUser = createParamDecorator((data, ctx: ExecutionContext): User => {
const req = ctx.switchToHttp().getRequest();
return req.user;
})
π auth.controller.ts
import { Body, Controller, Post, Req, UseGuards, ValidationPipe } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credential.dto';
import { AuthGuard } from '@nestjs/passport';
import { GetUser } from './get-decorator';
import { User } from './user.entity';
@Controller('auth')
export class AuthController {
constructor( private authService: AuthService) {}
// localhost:3000/auth/signUp
@Post("/signup")
// ValidationPipe : μμ²μ΄ 컨νΈλ‘€λ¬μ μλ νΈλ€λ¬λ‘ λ€μ΄μμ λ Dto μ μλ μ ν¨μ± 쑰건μ λ§κ² 체ν¬
signUp(@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto): Promise<void> {
return this.authService.signUp(authCredentialsDto);
}
// λ‘κ·ΈμΈ κΈ°λ₯ ꡬννκΈ°
@Post("/signin")
signIn(@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto): Promise<{accessToken: string}> {
return this.authService.signIn(authCredentialsDto);
}
// TEST
@Post("/authTest")
// μΈμ¦ λ―Έλ€μ¨μ΄
// μ§μ λ κ²½λ‘λ‘ ν΅κ³Όν μ μλ μ¬λκ³Ό νμ©νμ§ μλ μ¬λμ μλ²μ μλ €μ€
@UseGuards(AuthGuard())
test(@GetUser() user: User) {
console.log("user", user);
}
}
728x90
λ°μν