NestJS에서 @InjectRepository 데코레이터는 TypeORM과 함께 사용되어 특정 엔티티의 리포지토리를 서비스 클래스에 주입하기 위해 사용됩니다!
이 데코레이터는 의존성 주입을 통해 데이터베이스와의 상호작용을 보다 간편하게 관리할 수 있도록 도와줘요
이 예제에서는 MySQL 데이터베이스를 사용하여 사용자(User) 데이터를 저장하고, GraphQL을 통해 사용자 데이터를 조회하고 추가하는 API를 구축합니다.
@InjectRepository 데코레이터 사용 방법
// npm 설치
npm install @nestjs/typeorm typeorm mysql2
npm install @nestjs/graphql @nestjs/apollo graphql apollo-server-express
// yarn 설치
yarn add @nestjs/typeorm typeorm mysql2
yarn add @nestjs/graphql @nestjs/apollo graphql apollo-server-express
TypeORM 및 GraphQL 설정
'app.module.ts' 설정
TypeORM 및 GraphQL 모듈을 설정합니다.
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'test',
entities: [User],
synchronize: true,
}),
GraphQLModule.forRoot<ApolloDriverConfig>({
driver: ApolloDriver,
autoSchemaFile: 'src/commons/graphql/schema.gql',
}),
UserModule, // Reposityor라고 함 -> service의 constructor에서 받음
],
})
export class AppModule {}
User 엔티티 정의
user.entity.ts 파일 생성
User 엔티티를 정의합니다.
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column()
email: string;
}
UserService 정의
user.service.ts 파일 생성
UserService를 정의하여 데이터베이스 작업을 처리합니다.
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 readonly userRepository: Repository<User>,
) {}
async findAll(): Promise<User[]> {
return this.userRepository.find();
}
async findOne(id: number): Promise<User> {
return this.userRepository.findOne({ where: { id } });
}
async create(name: string, email: string): Promise<User> {
const user = this.userRepository.create({ name, email });
return this.userRepository.save(user);
}
async remove(id: number): Promise<void> {
await this.userRepository.delete(id);
}
}
UserResolver 정의
user.resolver.ts 파일 생성
UserResolver를 정의하여 GraphQL 쿼리와 뮤테이션을 처리합니다.
import { Resolver, Query, Mutation, Args } from '@nestjs/graphql';
import { UserService } from './user.service';
import { User } from './user.entity';
@Resolver(of => User)
export class UserResolver {
constructor(private readonly userService: UserService) {}
@Query(returns => [User])
async users(): Promise<User[]> {
return this.userService.findAll();
}
@Query(returns => User)
async user(@Args('id') id: number): Promise<User> {
return this.userService.findOne(id);
}
@Mutation(returns => User)
async createUser(
@Args('name') name: string,
@Args('email') email: string,
): Promise<User> {
return this.userService.create(name, email);
}
@Mutation(returns => Boolean)
async removeUser(@Args('id') id: number): Promise<boolean> {
await this.userService.remove(id);
return true;
}
}
UserModule 정의
user.module.ts 파일 생성
UserModule을 정의하여 UserService와 UserResolver를 모듈에 등록합니다.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { User } from './user.entity';
import { UserService } from './user.service';
import { UserResolver } from './user.resolver';
@Module({
imports: [TypeOrmModule.forFeature([User])],
providers: [UserService, UserResolver],
})
export class UserModule {}
GraphQL 스키마 정의
User 엔티티와 GraphQL 스키마를 연동하기 위해, @ObjectType과 @Field 데코레이터를 사용하여 엔티티를 수정합니다.
import { ObjectType, Field, Int } from '@nestjs/graphql';
import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';
@ObjectType()
@Entity()
export class User {
@Field(type => Int)
@PrimaryGeneratedColumn()
id: number;
@Field()
@Column()
name: string;
@Field()
@Column()
email: string;
}
요약
- 설치 및 설정: MySQL과 GraphQL 관련 패키지를 설치하고 TypeORM 및 GraphQL 모듈을 설정합니다.
- 엔티티 정의: User 엔티티를 정의합니다.
- 서비스 정의: UserService를 정의하여 데이터베이스 작업을 처리합니다.
- 리졸버 정의: UserResolver를 정의하여 GraphQL 쿼리와 뮤테이션을 처리합니다.
- 모듈 정의: UserModule을 정의하여 모듈에 서비스와 리졸버를 등록합니다.
- 애플리케이션 실행: 애플리케이션을 실행하여 MySQL 데이터베이스와 GraphQL API가 제대로 연동되었는지 확인합니다.
'Back > NestJS' 카테고리의 다른 글
페이지네이션(Pagenation) 구현하기 - (1) (0) | 2025.03.12 |
---|---|
[NextJS] 프로젝트 생성하기 with Yarn berry 4.4.0 (0) | 2025.01.26 |
[NestJS] JWT(JSON Web Token) - 로그인 API 구현과 암호화 (0) | 2024.08.10 |
[Node.js] 블로킹 / 논블로킹 (0) | 2023.03.28 |
[Node.js] 이벤트 루프 (event loop) (0) | 2023.03.28 |