クエリパラメータ
CoddyのNode.jsジャーニー「TypeScriptとNestJS」セクションの一部。レッスン 3/17。
開いているタスクだけを必要とするクライアントが、すべてのタスクをダウンロードして自分で絞り込む必要はありません。クエリ文字列(?の後の部分)には、そのようなオプションを指定できます。
@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'です。型はコードの説明になり、エディターの助けになります。クエリの値はテキストとして比較しましょう。
チャレンジ
簡単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));
}
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。