Menu
CoddyTech

쿼리 매개변수

Coddy Node.js 여정의 TypeScript와 NestJS 섹션에 포함된 레슨. 17개 중 3번째.

열린 작업만 원하는 클라이언트가 모든 작업을 다운로드한 뒤 직접 필터링할 필요는 없습니다. ? 뒤에 오는 부분인 쿼리 문자열에는 이와 같은 옵션이 담깁니다.

@Get()
findAll(@Query('author') author?: string) {
    if (!author) {
        return this.books;
    }
    return this.books.filter((book) => book.author === author);
}

@Query('author')는 ?author=Le%20Guin을 읽거나, 요청에 값이 없으면 undefined를 반환합니다.

TypeScript 타입은 코드가 실행될 때 제거됩니다. Node는 타입이 제거된 뒤 남은 JavaScript를 실행하며, 타입을 검사하는 것은 아무것도 없습니다. inStock?: boolean이라고 작성해도 Nest는 여전히 문자열 'false'를 전달하며, 이 값은 참으로 평가됩니다. 타입은 코드를 설명하고 편집기에 도움을 줍니다. 쿼리 값은 텍스트로 비교하세요.

challenge icon

챌린지

쉬움
  • GET /tasks?done=true는 완료된 작업만 응답하고, GET /tasks?done=false는 진행 중인 작업만 응답합니다.
  • done이 없으면 GET /tasks는 모든 작업을 응답합니다.
  • GET /tasks?done=false를 보낸 다음 GET /tasks?done=true를 보내세요.

직접 해보기

import { Controller, Get, Param } from '@nestjs/common';

interface Task {
    id: number;
    title: string;
    done: boolean;
}

@Controller('tasks')
export class TasksController {
    private tasks: Task[] = [
        { id: 1, title: 'Write the README', done: true },
        { id: 2, title: 'Fix the login bug', done: false },
        { id: 3, title: 'Plan the sprint', done: false },
    ];

    @Get()
    findAll(): Task[] {
        return this.tasks;
    }

    @Get(':id')
    findOne(@Param('id') id: string): Task | undefined {
        return this.tasks.find((task) => task.id === Number(id));
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

TypeScript와 NestJS의 모든 레슨