Parametri di query
Fa parte della sezione TypeScript e NestJS del percorso Node.js di Coddy. Lezione 3 di 17.
Un client che vuole solo le attività aperte non dovrebbe dover scaricare tutte le attività e filtrare autonomamente quelle desiderate. La stringa di query, la parte dopo ?, contiene opzioni di questo tipo.
@Get()
findAll(@Query('author') author?: string) {
if (!author) {
return this.books;
}
return this.books.filter((book) => book.author === author);
}@Query('author') legge ?author=Le%20Guin oppure restituisce undefined se la richiesta non ne contiene una.
I tipi TypeScript vengono rimossi quando il codice viene eseguito: Node esegue il JavaScript che rimane dopo la rimozione dei tipi e non li controlla. Scrivi inStock?: boolean e Nest ti passa comunque la stringa 'false', che è truthy. I tipi documentano il tuo codice e aiutano l'editor; confronta i valori della query come testo.
Sfida
FacileGET /tasks?done=truerestituisce solo le attività completate;GET /tasks?done=falsesolo quelle aperte.- Senza
done,GET /tasksrestituisce tutte le attività. - Invia
GET /tasks?done=false, poiGET /tasks?done=true.
Provalo tu
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));
}
}
Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.
Tutte le lezioni di TypeScript e NestJS
1Fondamenti di Nest
Ciao, NestParametri di route