๐ ๊ณต๋ถํ๋ ์ง์ง์ํ์นด๋ ์ฒ์์ด์ง?
[Nest JS ๋ก CRUD ๊ฒ์ํ ๋ง๋ค๊ธฐ] (23) ์ ์ ๋ฐ์ดํฐ ์ ํจ์ฑ ์ฒดํฌ ๋ณธ๋ฌธ
๐ฉ๐ป ๋ฐฑ์๋(Back-End)/Nest js
[Nest JS ๋ก CRUD ๊ฒ์ํ ๋ง๋ค๊ธฐ] (23) ์ ์ ๋ฐ์ดํฐ ์ ํจ์ฑ ์ฒดํฌ
์ง์ง์ํ์นด 2023. 6. 8. 16:52728x90
๋ฐ์ํ
<๋ณธ ๋ธ๋ก๊ทธ๋ John Ahn ์ ์ ํ๋ธ๋ฅผ ์ฐธ๊ณ ํด์ ๊ณต๋ถํ๋ฉฐ ์์ฑํ์์ต๋๋ค :-)>
=> ๋ฐ๋ผํ๋ฉด์ ๋ฐฐ์ฐ๋ NestJS
๐งธ ์ ์ ๋ฐ์ดํฐ ์ ํจ์ฑ ์ฒดํฌ
์ ์ ๋ฅผ ์์ฑํ ๋ ์ํ๋ ์ด๋ฆ์ ๊ธธ์ด, ๋น๋ฐ๋ฒํธ ๊ธธ์ด ๋ฑ ์ ํจ์ฑ ์ฒดํฌํ ์ ์๋๋ก Column์ ์กฐ๊ฑด ๋ฃ๊ธฐ
๐ Class-validator
์ ํจ์ฑ ์ฒดํฌ๋ฅผ ํ๊ธฐ ์ํด์๋ class-validator ๋ชจ๋ ์ฌ์ฉ
Dto ์์ Request๋ก ๋ค์ด์ค๋ ๊ฐ์ ์ ์ํจ -> Dto ํ์ผ ๊ฐ๋ค ํ๋ํ๋์ class-validator ์ด์ฉํด์ ์ ํจ์ฑ ์กฐ๊ฑด ๋ฃ๊ธฐ
๐ auth-credentials.ts
import { IsString, Matches, MinLength, MaxLength } from "class-validator";
export class AuthCredentialsDto {
@IsString()
@MinLength(4)
@MaxLength(20)
username: string;
@IsString()
@MinLength(4)
@MaxLength(20)
// ์์ด์ ์ซ์๋ง ๊ฐ๋ฅํ ์ ํจ์ฑ ์ฒดํฌ
@Matches(/^[a-zA-Z0-9]*$/, {
message: 'password only accepts english and number'
})
password: string;
}
๐งธ ValidationPipe
์์ฒญ์ด ์ปจํธ๋กค๋ฌ์ ์๋ ํธ๋ค๋ฌ๋ก ๋ค์ด์์ ๋ Dto ์ ์๋ ์ ํจ์ฑ ์กฐ๊ฑด์ ๋ง๊ฒ ์ฒดํฌํด์ฃผ๋ ค๋ฉด ValidationPipe ๋ฃ๊ธฐ
๐ auth.controller.ts
import { Body, Controller, Post, ValidationPipe } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credential.dto';
@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);
}
}
728x90
๋ฐ์ํ
'๐ฉโ๐ป ๋ฐฑ์๋(Back-End) > Nest js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Comments