๐Ÿ˜Ž ๊ณต๋ถ€ํ•˜๋Š” ์ง•์ง•์•ŒํŒŒ์นด๋Š” ์ฒ˜์Œ์ด์ง€?

[Nest JS ๋กœ CRUD ๊ฒŒ์‹œํŒ ๋งŒ๋“ค๊ธฐ] (23) ์œ ์ € ๋ฐ์ดํ„ฐ ์œ ํšจ์„ฑ ์ฒดํฌ ๋ณธ๋ฌธ

๐Ÿ‘ฉ‍๐Ÿ’ป ๋ฐฑ์—”๋“œ(Back-End)/Nest js

[Nest JS ๋กœ CRUD ๊ฒŒ์‹œํŒ ๋งŒ๋“ค๊ธฐ] (23) ์œ ์ € ๋ฐ์ดํ„ฐ ์œ ํšจ์„ฑ ์ฒดํฌ

์ง•์ง•์•ŒํŒŒ์นด 2023. 6. 8. 16:52
728x90
๋ฐ˜์‘ํ˜•

<๋ณธ ๋ธ”๋กœ๊ทธ๋Š” 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
๋ฐ˜์‘ํ˜•
Comments