NestJS - body값과 params값 include 사용법

Seong Hyeon Kim·2022년 10월 17일
0

NestJs

목록 보기
1/14

controller

import { Controller, Post, Body, Get, Param, ParseIntPipe } from '@nestjs/common';
import { PostingsService } from './postings.service';
import { Posting } from './dto/postings.dto'; 


@Patch(':id')
  updatePosting(@Param('id',ParseIntPipe)id: number,@Body() posting:Posting){
    return this.postingsService.updatePosting(id,posting)
  }
  • @Patch(':id')
    여기는 params 값으로 id를 받을 예정이니 url :id 를 추가하기 위해서 ()안에 넣어줬다고 생각하면 된다.

  • @Param('id',ParseIntPipe)id: number
    여기는 실제 params값을 받깅 위해 세팅하는 부분으로 params값은 문자형으로밖에 받지 못하는데, id: number 에서 숫자형으로 선언해서 알듯이,숫자형인 id 값을 받기위해서 ParseIntPipe라는 매서드? 를 사용해서 숫자형으로 받을 id값을 문자형으로 변환해주는 부분이다.

  • @Body() posting:Posting
    body 값을 받기위해서 작성된 부분이며 바디값으로 posting 라는 값을 받으며, 이 posting의 타입은 미리 만들어둔 dto 파일에서 import한 Posting 의 값으로 설정하겠다는 부분이다

dto 파일

export interface Posting {
    "title" : string;
    "content": string;
}
  • this.postingsService.updatePosting(id,posting)
    컨트롤러에서 처리한 params 값과 body 값을 서비스부분에서도 사용할수 있도록 인자로 보내주도록 처리한 부분이다.

service

import { Injectable, InternalServerErrorException } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { Posting } from './dto/postings.dto'; 


async updatePosting(id:number,posting:Posting) {
    const{title,content} = posting
    const updatedPosting = await this.prismaService.posting.update({
      where : {
        id
      },
      include: {
        pharmacist: {
          select: { userName: true, pharmacyName: true, pharmacyAddress: true },
        },
      },
      data : {
        title,content
      }
    })
  • async updatePosting(id:number,posting:Posting)
    컨트롤러에서 넘겨주던 인자를 서비스부분에서 받기위해 한번 더 코드로 작성된 부분이다.

  • prismaService.posting.update({ where : { id },
    서비스부분의 시작으로 특정한 내용을 바꾸되 그 기준이 params로 받은 id 값을 기준으로 한다고 말해주는 부분이다.

  • include: { pharmacist: { select: { userName: true, pharmacyName: true, pharmacyAddress: true }, }, },

    이번 글의 핵심부분인 include 부분이다.
    코르들 해석하자면 pharmacist 테이블에서
    select 해서 가져올건데, 가져오는건
    { userName: true, pharmacyName: true, pharmacyAddress: true }
    유저네임(약사이름)과 약국이름 그리고 약국주소 정도를 가져오겠다고 명시하는 부분이다.

    참고로 여기서

     include: {
           pharmacist: true
     }

    라고 적었다면 pharmacist 테이블의 모든 값을 가져온다는 의미이다

profile
삽질도 100번 하면 요령이 생긴다. 부족한 건 경험으로 채우는 백엔드 개발자

0개의 댓글