본문 바로가기
nest.js

TypeORM(GraphQL)을 활용한 API 구체적으로 만들기

by goblin- 2024. 6. 3.

1. 엔티티 정의

먼저, Board 엔티티를 정의합니다. 이는 데이터베이스 테이블 구조를 나타냅니다.

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity() // 클래스를 데이터베이스 테이블로 변환
export class Board {
  @PrimaryGeneratedColumn() // 자동 증가하는 프라이머리 키
  number: number;

  @Column() // 일반 컬럼
  writer: string;

  @Column() // 일반 컬럼
  title: string;

  @Column() // 일반 컬럼
  contents: string;
}

 

 

2. GraphQL 타입 정의

TypeScript에서는 Board 클래스를 타입으로 사용할 수 있지만, GraphQL에서는 별도의 타입 정의가 필요합니다. 이를 위해 @ObjectType() 데코레이터를 사용합니다.

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

@ObjectType() // GraphQL 타입으로 변환
export class BoardType {
  @Field(() => Int) // GraphQL 스키마에 Int 타입으로 지정
  number: number;

  @Field(() => String) // GraphQL 스키마에 String 타입으로 지정
  writer: string;

  @Field(() => String) // GraphQL 스키마에 String 타입으로 지정
  title: string;

  @Field(() => String) // GraphQL 스키마에 String 타입으로 지정
  contents: string;
}

 

3. DTO (Data Transfer Object)

데이터 전송 객체를 정의합니다. 입력값으로 들어오는 타입은 @InputType()을 사용하여 정의합니다.

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

@InputType() // 입력 타입으로 지정
export class CreateBoardInput {
  @Field(() => String) // GraphQL 스키마에 String 타입으로 지정
  writer: string;

  @Field(() => String) // GraphQL 스키마에 String 타입으로 지정
  title: string;

  @Field(() => String) // GraphQL 스키마에 String 타입으로 지정
  contents: string;
}

 

 

4. Service

서비스 클래스에서 비즈니스 로직을 처리합니다.

import { Injectable } from '@nestjs/common';
import { CreateBoardInput } from './dto/create-board.input';

@Injectable()
export class BoardsService {
  create({ createBoardInput }: { createBoardInput: CreateBoardInput }): string {
    // createBoardInput의 각 필드를 로그로 출력
    console.log(createBoardInput.writer);
    console.log(createBoardInput.title);
    console.log(createBoardInput.contents);
    
    // 비즈니스 로직 처리 후 반환값
    return '게시물 등록에 성공하였습니다.';
  }
}

 

 

5. Resolver

리졸버 클래스에서 GraphQL 쿼리와 뮤테이션을 처리합니다.

import { Resolver, Mutation, Args } from '@nestjs/graphql';
import { BoardsService } from './boards.service';
import { CreateBoardInput } from './dto/create-board.input';
import { BoardType } from './board.type';

@Resolver(() => BoardType)
export class BoardsResolver {
  constructor(private readonly boardsService: BoardsService) {}

  @Mutation(() => String)
  createBoard(
    @Args('createBoardInput') createBoardInput: CreateBoardInput,
  ): string {
    // 서비스 호출하여 게시물 생성
    return this.boardsService.create({ createBoardInput });
  }
}

 

설명

  1. 엔티티 정의
    • Board 클래스는 데이터베이스 테이블을 나타냅니다.
    • @Entity() 데코레이터는 클래스를 데이터베이스 테이블로 변환합니다.
    • @PrimaryGeneratedColumn() 데코레이터는 자동 증가하는 프라이머리 키를 정의합니다.
    • @Column() 데코레이터는 일반 컬럼을 정의합니다.
  2. GraphQL 타입 정의
    • BoardType 클래스는 GraphQL 타입을 나타냅니다.
    • @ObjectType() 데코레이터는 클래스를 GraphQL 타입으로 변환합니다.
    • @Field() 데코레이터는 필드를 GraphQL 스키마에 추가합니다.
  3. DTO
    • CreateBoardInput 클래스는 입력값을 나타냅니다.
    • @InputType() 데코레이터는 클래스를 GraphQL 입력 타입으로 변환합니다.
    • @Field() 데코레이터는 필드를 GraphQL 스키마에 추가합니다.
  4. Service
    • BoardsService 클래스는 비즈니스 로직을 처리합니다.
    • create() 메서드는 CreateBoardInput을 받아서 로그로 출력하고 메시지를 반환합니다.
  5. Resolver
    • BoardsResolver 클래스는 GraphQL 쿼리와 뮤테이션을 처리합니다.
    • @Resolver(() => BoardType) 데코레이터는 리졸버를 GraphQL 타입에 연결합니다.
    • @Mutation(() => String) 데코레이터는 뮤테이션을 정의합니다.
    • createBoard() 메서드는 CreateBoardInput을 받아서 서비스 메서드를 호출합니다.