Nestjs + Graphql + Typeorm

박주홍·2022년 5월 5일
0
post-thumbnail

Nestjs, Graphql, Typeorm을 같이 쓰기위해 개발환경세팅을 하기위한 분들께 필요한 글이 되었으면 좋겠다.

nestjs에서 graphql을 사용할 수 있도록 먼저 연결한 후 데이터베이스를 이용할 수 있는 typeorm을 연결하도록 하겠다.

Nestjs

nestjs란 nodejs기반에서 돌아가는 프레임워크이며, 모듈이란 단위로 요청에 따른 라우팅을 처리하는 방식으로 프레임워크자체가 구조화가 되어있어서 개발을 할때에 편리하다. (처음배울때는 지옥이였다..)

Nestjs 프로젝트 생성 커맨드 명령어

npm i -g @nestjs/cli
nest new <project-name>

graphql 관련 라이브러리 설치

npm install @nestjs/graphql apollo-server-express graphql-tools type-graphql graphql

typeorm 관련 라이브러리 설치

npm install @nestjs/typeorm typeorm mysql mysql2




프로젝트 생성하고, 관련라이브러리를 설치했다면 다음과 같이 차례대로 따라해보자.

처음 알아둘 것

nestjs는 보통 하나의 모듈에 controller(라우팅해주는), service(라우팅된 요청을 응답해줄 비지니스 로직)으로 구성되어 있는데 graphql은 controller대신 resolver를 사용한다. 그래서 url라우팅대신 query, mutation 라우팅으로 사용한다.



1. nestjs 모듈만들기

nest generate module user
nest generate service user
nest generate resolver user


2. 엔티티 생성

// /server/user/user.entity.ts
import { Entity, BaseEntity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()
export class User extends BaseEntity {
    @PrimaryGeneratedColumn()
    id!: number;
    @Column('varchar', { length: 30 })
    name!: string;
    
    @Column()
    email!: string;
}

3. User모듈에 User 엔티티 참조

// /server/product/product.module.ts
import { TypeOrmModule } from '@nestjs/typeorm';
...
@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [ProductService, ProductResolver],
...

4. App 모듈에 ORM 엔티티 연결 설정 및 GraphQLModule, TypeOrmModule 설정

// /server/app.module.ts
import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { UserModule } from './user/user.module';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user/user.entity';

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mysql', //Database 설정
      host: '127.0.0.1', // localhost 혹은 127.0.0.1
      port: 3306,
      username: 'root',
      password: "",
      database: 'hinest',
      entities: [User], // Entity 연결
      synchronize: true,
    }),
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      debug: false,
      playground: false,
      autoSchemaFile: 'schema.gpl'
    }),
    UserModule,
    TypeOrmModule.forFeature([User])
  ],
  controllers: [],
  providers: [],
})
export class AppModule { }

...

5. 타입 생성

Graphql 출력 타입으로 사용할 데이터 오브젝트를 하나 생성한다.

// /server/product/product.dto.ts
import { ObjectType, Field, Int } from "@nestjs/graphql";
@ObjectType()
export class User {
    @Field()
    readonly id?: number;
    @Field()
    readonly name!: string;
    @Field(() => Int)
    readonly email!: string;
}

6. 서비스 생성

import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';

@Injectable()
export class UserService {
    constructor(
        @InjectRepository(User)
        private userRepository: Repository<User>
    ) { }

    async getHello(): Promise<any> {
        console.log("this.userRepository.find() : ", await this.userRepository.find()[0]);
        const result = await this.userRepository.find();
        return result[1];
    }
}

7. resolver 생성

import { Query, Mutation, Resolver, Args } from '@nestjs/graphql';
import { UserService } from './user.service';
import { User } from './user.model'

@Resolver()
export class UserResolver {
    constructor(private readonly userService : UserService){}

    @Query(result => User)
    async getUser(): Promise<any>{
        return this.userService.getHello();
    }

    @Query(result => String)
    async test(): Promise<string>{
        return '테스트가 잘 될까요?';
    }
    
}

이제 서버 구동 후 http://localhost:3000/graphql 에서 요청 응답을 보내고 받을 수 있고, 스키마 파일은 schema.gql에 생성 된다.



참고자료
https://medium.com/@feedbotstar/nest-js-graphql-%EC%8B%9C%EC%9E%91%ED%95%98%EA%B8%B0-f38adf767fa8

profile
고통없는 성장은 없다고 할 수 있겠다....

0개의 댓글