0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

nestjsでエンドポイントを叩かれたときにデータを受け取る(Query)

Last updated at Posted at 2025-02-26

@Queryの使い方

Todoという機能を作っている前提で書きます

目的

引数を一つ以上受け取りたい

本文

Queryをimportして、@getデコレータにくっつける関数の引数に、@Queryデコレータをくっつけるだけ。
以下のような形式で書く

@Query('エンドポイントで受け取るときの名前') 引数の名前:引数の型

引数の型はデフォルトでstring。
型注釈つけるだけでは、string以外にはならない。パイプってのを使えばstring以外でも受け取れる。
(https://zenn.dev/toshinobu/articles/168666b2b1b1dc#%E6%9C%AC%E9%A1%8C%E3%81%AE%E5%95%8F%E9%A1%8C)

todo.controller.ts
import {
  Controller,
  Get,
  Query, //@Query
} from '@nestjs/common';

@Controller('todo')
export class TodoController {
  constructor(private readonly prisma: CustomPrismaService) {}

   @Get('getTodos')
  async getTodos(
    @Query('done') done:boolean
    @Query('name') name:string
    @Query('importance') importance:number
  ){
  //ここに処理を書くとき、done,name,importanceが引数として使える
  }

エンドポイントはこんなかんじ(ローカル想定)
TRUE,lunch,3を渡したいとする。

http://~~~~~:3000/todo/getTodos?done=TRUE&name=lunch&importance=3
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?