😎 κ³΅λΆ€ν•˜λŠ” μ§•μ§•μ•ŒνŒŒμΉ΄λŠ” μ²˜μŒμ΄μ§€?

[Nest JS 둜 CRUD κ²Œμ‹œνŒ λ§Œλ“€κΈ°] (12) μ»€μŠ€ν…€ νŒŒμ΄ν”„λ₯Ό μ΄μš©ν•œ μœ νš¨μ„± 체크 λ³Έλ¬Έ

πŸ‘©‍πŸ’» λ°±μ—”λ“œ(Back-End)/Nest js

[Nest JS 둜 CRUD κ²Œμ‹œνŒ λ§Œλ“€κΈ°] (12) μ»€μŠ€ν…€ νŒŒμ΄ν”„λ₯Ό μ΄μš©ν•œ μœ νš¨μ„± 체크

μ§•μ§•μ•ŒνŒŒμΉ΄ 2023. 6. 2. 01:32
728x90
λ°˜μ‘ν˜•

<λ³Έ λΈ”λ‘œκ·ΈλŠ” John Ahn μ˜ 유튜브λ₯Ό μ°Έκ³ ν•΄μ„œ κ³΅λΆ€ν•˜λ©° μž‘μ„±ν•˜μ˜€μŠ΅λ‹ˆλ‹€ :-)>

=> λ”°λΌν•˜λ©΄μ„œ λ°°μš°λŠ” NestJS

 

🧸 μ»€μŠ€ν…€ νŒŒμ΄ν”„λ₯Ό μ΄μš©ν•œ μœ νš¨μ„± μ²΄ν¬ 

: Pipe Transform μ΄λž€ μΈν„°νŽ˜μ΄μŠ€λ₯Ό μƒˆλ‘­κ²Œ λ§Œλ“€ μ»€μŠ€ν…€ νŒŒμ΄ν”„μ— κ΅¬ν˜„ν•΄μ€˜μ•Ό 함

: Pipe Transform μΈν„°νŽ˜μ΄μŠ€λŠ” λͺ¨λ“  νŒŒμ΄ν”„μ—μ„œ κ΅¬ν˜„ν•΄μ€˜μ•Ό ν•˜λŠ” μΈν„°νŽ˜μ΄μŠ€

: λͺ¨λ“  νŒŒμ΄ν”„λŠ” transform() λ©”μ†Œλ“œ ν•„μš”

: NestJS κ°€ 인자λ₯Ό μ²˜λ¦¬ν•˜κΈ° μœ„ν•΄ μ‚¬μš©λ¨

 

πŸŽ€ transform() λ©”μ†Œλ“œ

: 두 개의 νŒŒλΌλ―Έν„°λ₯Ό 가짐

: 첫 번째 νŒŒλΌλ―Έν„°λŠ” μ²˜λ¦¬κ°€ 된 인자의 κ°’ (value)

: 두 번째 νŒŒλΌλ―Έν„°λŠ” μΈμžμ— λŒ€ν•œ 메타 데이터λ₯Ό ν¬ν•¨ν•œ 객체

-> transform() λ©”μ†Œλ“œμ—μ„œ return 된 값은 Route ν•Έλ“€λŸ¬λ‘œ 전해짐 (μ˜ˆμ™Έκ°€ 생기면 ν΄λΌμ΄μ–ΈνŠΈλ‘œ 전해짐)

μ²˜λ¦¬κ°€ 된 인자의 κ°’ (value) & μΈμžμ— λŒ€ν•œ 메타 데이터λ₯Ό ν¬ν•¨ν•œ 객체

 

🧸 μ»€μŠ€ν…€ νŒŒμ΄ν”„λ‘œ μƒνƒœ κΈ°λŠ₯ κ΅¬ν˜„ν•˜κΈ°

: μƒνƒœλŠ” PUBLIC, PRIVATE 둜만 올 수 있음

: 이외 값이 였면 μ—λŸ¬ λ°˜ν™˜ν•˜κΈ°

import { BadRequestException, PipeTransform } from "@nestjs/common";
import { BoardStatus } from "../board.model";

export class BoardStatusValidationPipe implements PipeTransform {
    readonly StatusOptions = [
        BoardStatus.PRIVATE,
        BoardStatus.PUBLIC
    ]

    transform(value: any) {
        value = value.toUpperCase();
        
        if (!this.isStatusValid(value)) {
            throw new BadRequestException(`${value} isn't in the status options`);
        }
        return value;
    }

    private isStatusValid(status: any) {
        const index = this.StatusOptions.indexOf(status);
        // μΈλ±μŠ€μ— μ—†λŠ” 숫자λ₯Ό λ„£μœΌλ©΄ -1 κ°€ λ‚˜μ˜΄ -> μ—†λŠ” status 확인!
        return index !== -1;
    }
}

728x90
λ°˜μ‘ν˜•
Comments