查询参数
本课属于 Coddy Node.js 学习旅程的“TypeScript 和 NestJS”单元。第 5 课,共 24 课。
只想获取未完成任务的客户端,不应该被迫下载所有任务再自行筛选。查询字符串,也就是 ? 后面的部分,可以携带这类选项。
@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));
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
TypeScript 和 NestJS中的所有课
自己练习: Express 在线编辑器