NestJS 게시판 CRUD API 만들기

SSAD·2023년 2월 19일
0

BackEnd

목록 보기
36/44
post-thumbnail
post-custom-banner

보일러 플레이트

board.resolver.ts 수정


import { Query, Resolver, Mutation } from '@nestjs/graphql';
import { BoardService } from './board.service';

@Resolver()
export class BoardResolver {
  constructor(private readonly boardService: BoardService) {}

  @Query(() => String)
  fetchBoards(){
    return this.boardService.findAll();
  }

  @Mutation(() => String)
  createBoard(){
    return this.boardService.create();
  }
}

board.service.ts 수정

import { Injectable } from '@nestjs/common';

@Injectable()
export class BoardService {
  findAll(){
	// 로직
    return '전체조회';
  }

	create() {
    // 로직
    return '등록';
}

fetchBoards에서 ObjectType 내보내기

게시판 객체를 보내기 위해 ObjectType으로 변경할 것

  • 작성한 Entity 형식에 맞게 반환하는 API로 수정

board.entity.ts 파일 수정


import { Field, Int, ObjectType } from '@nestjs/graphql';
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
@ObjectType()
export class Board {
  @PrimaryGeneratedColumn('increment')
  @Field(() => Int)
  number: number;

  @Column()
  @Field(() => String)
  writer: string;

  @Column()
  @Field(() => String)
  title: string;

  @Column()
  @Field(() => String)
  contents: string;
}

@ObjectType : 객체 형태의 GraphQL 타입으로 변경
@Field : GraphQL Field임을 알리고, 타입을 지정

resolver.ts 수정


import { Resolver, Query, Mutation } from '@nestjs/graphql';
import { BoardService } from './board.service';
import { Board } from './entities/board.entity';

@Resolver()
export class BoardResolver {
  constructor(private readonly boardService: BoardService) {}

  @Query(() => [Board]) // 리스트안에 객체로 변경
  fetchBoards(){
    return this.boardService.findAll();
  }

  @Mutation(() => String)
  createBoard(){
    return this.boardService.create();
  }
}

service.ts 수정

// board.service.ts

import { Injectable } from '@nestjs/common';
import { Board } from './entities/board.entity';

@Injectable()
export class BoardService {
  findAll(){
    const result = [
      {
        number: 1,
        writer: '철수',
        title: '제목입니다~~',
        contents: '내용입니다!!!',
      },
      {
        number: 2,
        writer: '철수',
        title: '제목입니다~~',
        contents: '내용입니다!!!',
      },
      {
        number: 3,
        writer: '철수',
        title: '제목입니다~~',
        contents: '내용입니다!!!',
      },
    ];


    return result;
	}

	create() {

    return '등록에 성공하였습니다.';
  }
}

타입 자동 생성 확인


createBoard에서 Args 개별로 받기

resolver.ts 수정


import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { BoardService } from './board.service';
import { Board } from './entities/board.entity';

@Resolver()
export class BoardResolver {
  constructor(private readonly boardService: BoardService) {}

  @Query(() => [Board]) 
  fetchBoards(){
    return this.boardService.findAll();
  }

  @Mutation(() => String)
  createBoard(
    @Args('writer') writer: string, 
    @Args('title') title: string,
    @Args('contents') contents: string,
  ){
    return this.boardService.create({ writer, title, contents });
  }
}

@Args : 객체 value 값의 타입을 지정

  • (안) : gql 타입
  • 밖 : typescript 타입

service.ts 수정

//board.service.ts

import { Injectable } from '@nestjs/common';
import { Board } from './entities/board.entity';

@Injectable()
export class BoardService {
    const result = [
      {
        number: 1,
        writer: '철수',
        title: '제목입니다~~',
        contents: '내용입니다!!!',
      },
      {
        number: 2,
        writer: '철수',
        title: '제목입니다~~',
        contents: '내용입니다!!!',
      },
      {
        number: 3,
        writer: '철수',
        title: '제목입니다~~',
        contents: '내용입니다!!!',
      },
    ];

    return result;
	}


  create(args){
    console.log(args);

    return '등록에 성공하였습니다.';
  }
}

createBoard에서 InputType dto로 묶어서 받기

dto(data transfer object)

  • 데이터 전송 객체
  • 네트워크 간 데이터를 어떤 식으로 보낼지를 정의한 객체

createBoard.input.ts 생성

// createBoard.input.ts

import { InputType, Field } from '@nestjs/graphql';

@InputType()
export class CreateBoardInput {
  @Field(() => String)
  writer: string;

  @Field(() => String)
  title: string;

  @Field(() => String)
  contents: string;
}

@InputType : gql InputType 임을 알림

resolver.ts 수정

//board.resolver.ts

import { Query, Resolver, Mutation, Args } from '@nestjs/graphql';
import { BoardService } from './board.service';
import { CreateBoardInput } from './dto/createBoard.input';
import { Board } from './entities/board.entity';

@Resolver()
export class BoardResolver {
  constructor(private readonly boardService: BoardService) {}

  @Query(() => [Board])
  fetchBoards(){
    return this.boardService.findAll();
  }

  @Mutation(() => String)
  createBoard(
    @Args('writer') writer: string,
    @Args('title') title: string,
    @Args('contents') contents: string,
    @Args('createBoardInput') createBoardInput: CreateBoardInput,
  ){
    return this.boardService.create({
      writer,
      title,
      contents,
      createBoardInput,
    });
  }
}

schema 확인

profile
learn !
post-custom-banner

0개의 댓글