2023. 6. 25. 20:25ㆍBackend Development/NestJS
회원가입은 대부분의 애플리케이션에서 핵심 기능 중 하나입니다. 이 글에서는 NestJS를 사용하여 간단한 회원가입 기능을 단계별로 구현하는 방법을 다룹니다. 프로젝트 설정부터 서비스 로직, 데이터베이스 연결까지 모든 과정을 상세히 설명합니다.
1. 프로젝트 초기화 및 설정
먼저, NestJS 프로젝트를 초기화합니다.
1.1. 프로젝트 생성
nest new signup-project
cd signup-project
1.2. 필요한 패키지 설치
회원 정보를 저장하기 위해 데이터베이스와 TypeORM을 사용합니다. MySQL을 예로 들면 다음 명령어를 실행합니다:
npm install @nestjs/typeorm typeorm mysql2
2. User 모듈 생성
NestJS CLI를 사용하여 User 모듈, 서비스, 컨트롤러를 생성합니다.
nest g mo user
nest g s user
nest g co user
위 명령어를 실행하면 user.module.ts
, user.service.ts
, user.controller.ts
파일이 생성됩니다.
3. 데이터베이스 설정 및 엔터티 정의
3.1. 데이터베이스 연결 설정
src/app.module.ts
파일에 다음과 같이 데이터베이스 연결 설정을 추가합니다:
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'user_db',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}),
],
})
export class AppModule {}
3.2. 엔터티 정의
회원 정보를 저장하기 위해 information
테이블을 엔터티로 정의합니다. src/user/entity/information.entity.ts
파일을 생성하고 다음 코드를 추가합니다:
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn } from 'typeorm';
@Entity('information')
export class Information {
@PrimaryGeneratedColumn()
id: number;
@Column({ length: 30 })
name: string;
@Column({ unique: true })
username: string;
@Column()
password: string;
@Column({ type: 'varchar', length: 15 })
phoneNumber: string;
@Column({ type: 'enum', enum: ['male', 'female'] })
sex: 'male' | 'female';
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
4. 회원가입 서비스 로직 작성
src/user/user.service.ts
파일에서 회원가입 로직을 구현합니다.
import { Injectable, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Information } from './entity/information.entity';
import * as crypto from 'crypto';
@Injectable()
export class UserService {
constructor(
@InjectRepository(Information)
private readonly userRepository: Repository<Information>,
) {}
async signUp(userData: Partial<Information>): Promise<Information> {
const existingUser = await this.userRepository.findOne({ username: userData.username });
if (existingUser) {
throw new ConflictException('이미 존재하는 사용자 이름입니다.');
}
const hashedPassword = crypto.createHash('sha512').update(userData.password).digest('hex');
const newUser = this.userRepository.create({ ...userData, password: hashedPassword });
return this.userRepository.save(newUser);
}
}
5. 컨트롤러 설정
src/user/user.controller.ts
파일에서 회원가입 엔드포인트를 정의합니다.
import { Controller, Post, Body } from '@nestjs/common';
import { UserService } from './user.service';
import { Information } from './entity/information.entity';
@Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
@Post('signup')
async signUp(@Body() userData: Partial<Information>) {
return this.userService.signUp(userData);
}
}
6. 모듈 구성
src/user/user.module.ts
파일에서 엔터티와 서비스를 등록합니다.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserService } from './user.service';
import { UserController } from './user.controller';
import { Information } from './entity/information.entity';
@Module({
imports: [TypeOrmModule.forFeature([Information])],
providers: [UserService],
controllers: [UserController],
})
export class UserModule {}
7. 전역 모듈에 추가
마지막으로 src/app.module.ts
파일에 User 모듈을 등록합니다.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './user/user.module';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: 'password',
database: 'user_db',
entities: [__dirname + '/**/*.entity{.ts,.js}'],
synchronize: true,
}),
UserModule,
],
})
export class AppModule {}
8. 테스트 및 실행
애플리케이션을 실행하여 회원가입 API가 제대로 동작하는지 확인합니다.
npm run start
Postman 또는 다른 HTTP 클라이언트를 사용하여 POST 요청을 보내 테스트합니다.
요청 예시:
- URL:
http://localhost:3000/user/signup
- 요청 본문:
{ "name": "John Doe", "username": "johndoe", "password": "123456", "phoneNumber": "01012345678", "sex": "male" }
응답 예시:
{
"id": 1,
"name": "John Doe",
"username": "johndoe",
"phoneNumber": "01012345678",
"sex": "male",
"createdAt": "2025-01-24T10:00:00.000Z",
"updatedAt": "2025-01-24T10:00:00.000Z"
}
마무리
이 글에서는 NestJS를 사용하여 간단한 회원가입 기능을 구현하는 방법을 설명했습니다. 위 과정을 통해 NestJS의 구조화된 개발 방식과 데이터베이스 통합의 장점을 경험해 보세요. 더 복잡한 검증, 인증 등의 기능은 이 코드를 확장하여 구현할 수 있습니다.
궁금한 점이 있다면 댓글로 남겨주세요! 😊
'Backend Development > NestJS' 카테고리의 다른 글
NestJS 11 출시: 주요 변경 사항과 마이그레이션 가이드 (0) | 2025.01.24 |
---|---|
NestJS 에서 class-validator 를 활용한 데이터 검증 방법 (0) | 2023.06.26 |
NestJS에서 @typescript-eslint/no-unused-vars 오류 해결 방법 (0) | 2022.12.15 |
NestJS Interceptor로 효율적인 로깅 시스템 구축하기 (2) | 2022.12.14 |