⛳
Nestjs query引数多い時、custom decoratorsまとめ方法
Nestjs query 引数多い時、ustom decoratorsまとめば、コードの可読性改善する。
悪い書き方
引数三つ以上あるの場合、コードの可読性結構下げる。
posts.controller.ts
import { Controller, Get, Query} from '@nestjs/common';
@Controller('posts')
export class PostsController {
@Get()
findPost(
@Query("title") title:string,
@Query("description") description:string,
@Query("author") author:string,
@Query("subtitle") subtitle:string,
@Query("feedback") feedback:string
) {
console.log(title,description,author,subtitle)
return {
"title":title,
"description":description,
"author":author,
"subtitle":subtitle,
"feedback":feedback
}
}
}
対策
Post専用のdecorator作成。
posts.decorator.ts
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
export const Post = createParamDecorator(
(_data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.query;
},
);
Dtoも作成する。
posts.dto.ts
export class GetPostDto {
title:string
description:string
author:string
subtitle:string
feedback:string
}
結果
controllerのコード量すごく減ります。
posts.controller.ts
import { Controller, Get, Query} from '@nestjs/common';
import { Post } from './posts.decorator';
import { GetPostDto } from './posts.dto';
@Controller('posts')
export class PostsController {
@Get()
findPost(
@Post() post:GetPostDto
) {
return post
}
}
Discussion