first commit

This commit is contained in:
2026-06-11 18:19:26 +09:00
commit eaa30192cf
291 changed files with 47278 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
# compiled output
/dist
/node_modules
/build
# Logs
logs
*.log
npm-debug.log*
pnpm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# OS
.DS_Store
# Tests
/coverage
/.nyc_output
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
.env.development
.env.production
# temp directory
.temp
.tmp
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
+4
View File
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}
+40
View File
@@ -0,0 +1,40 @@
FROM node:20-alpine AS builder
WORKDIR /app
# 이벤트 등 외부 페이지 크롤링에 필요 (Node TLS 지문이 차단되어 시스템 curl 사용)
# dev(docker-compose.dev.yml)는 이 builder 스테이지로 실행되므로 여기에도 설치한다.
RUN apk add --no-cache curl
# 호스트의 npm 11 이 작성한 package-lock.json 형식과 호환되도록 npm 을 11 로 업그레이드
RUN npm install -g npm@11
# 재현 가능한 빌드를 위해 npm ci 사용 (lockfile 기반)
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS production
WORKDIR /app
ENV NODE_ENV=production
# 이벤트 등 외부 페이지 크롤링에 필요 (Node TLS 지문이 차단되어 시스템 curl 사용)
RUN apk add --no-cache curl
# 운영 stage 도 동일 npm 버전 사용
RUN npm install -g npm@11
# 운영용 의존성만 설치
COPY package*.json ./
RUN npm ci --omit=dev && npm cache clean --force
COPY --from=builder /app/dist ./dist
EXPOSE 3000
# 비-root 실행 (보안 규칙)
USER node
CMD ["node", "dist/main"]
+98
View File
@@ -0,0 +1,98 @@
<p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="120" alt="Nest Logo" /></a>
</p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg" alt="Donate us"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow" alt="Follow us on Twitter"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Project setup
```bash
$ npm install
```
## Compile and run the project
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Run tests
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Deployment
When you're ready to deploy your NestJS application to production, there are some key steps you can take to ensure it runs as efficiently as possible. Check out the [deployment documentation](https://docs.nestjs.com/deployment) for more information.
If you are looking for a cloud-based platform to deploy your NestJS application, check out [Mau](https://mau.nestjs.com), our official platform for deploying NestJS applications on AWS. Mau makes deployment straightforward and fast, requiring just a few simple steps:
```bash
$ npm install -g @nestjs/mau
$ mau deploy
```
With Mau, you can deploy your application in just a few clicks, allowing you to focus on building features rather than managing infrastructure.
## Resources
Check out a few resources that may come in handy when working with NestJS:
- Visit the [NestJS Documentation](https://docs.nestjs.com) to learn more about the framework.
- For questions and support, please visit our [Discord channel](https://discord.gg/G7Qnnhy).
- To dive deeper and get more hands-on experience, check out our official video [courses](https://courses.nestjs.com/).
- Deploy your application to AWS with the help of [NestJS Mau](https://mau.nestjs.com) in just a few clicks.
- Visualize your application graph and interact with the NestJS application in real-time using [NestJS Devtools](https://devtools.nestjs.com).
- Need help with your project (part-time to full-time)? Check out our official [enterprise support](https://enterprise.nestjs.com).
- To stay in the loop and get updates, follow us on [X](https://x.com/nestframework) and [LinkedIn](https://linkedin.com/company/nestjs).
- Looking for a job, or have a job to offer? Check out our official [Jobs board](https://jobs.nestjs.com).
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://twitter.com/kammysliwiec)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](https://github.com/nestjs/nest/blob/master/LICENSE).
+35
View File
@@ -0,0 +1,35 @@
// @ts-check
import eslint from '@eslint/js';
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
import globals from 'globals';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{
ignores: ['eslint.config.mjs'],
},
eslint.configs.recommended,
...tseslint.configs.recommendedTypeChecked,
eslintPluginPrettierRecommended,
{
languageOptions: {
globals: {
...globals.node,
...globals.jest,
},
sourceType: 'commonjs',
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
rules: {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-floating-promises': 'warn',
'@typescript-eslint/no-unsafe-argument': 'warn',
"prettier/prettier": ["error", { endOfLine: "auto" }],
},
},
);
+10
View File
@@ -0,0 +1,10 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true,
"builder": "swc",
"typeCheck": true
}
}
+13977
View File
File diff suppressed because it is too large Load Diff
+92
View File
@@ -0,0 +1,92 @@
{
"name": "backend",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs/axios": "^4.0.1",
"@nestjs/cache-manager": "^3.0.1",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.3",
"@nestjs/core": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"@nestjs/schedule": "^6.1.1",
"@nestjs/swagger": "^11.2.6",
"@nestjs/terminus": "^11.0.0",
"@nestjs/throttler": "^6.4.0",
"@nestjs/typeorm": "^11.0.1",
"axios": "^1.17.0",
"cache-manager": "^6.4.0",
"cheerio": "^1.2.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.4",
"express-rate-limit": "^8.3.2",
"helmet": "^8.1.0",
"nest-winston": "^1.10.0",
"pg": "^8.20.0",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"typeorm": "^0.3.28",
"winston": "^3.17.0"
},
"devDependencies": {
"@eslint/eslintrc": "^3.2.0",
"@eslint/js": "^9.18.0",
"@nestjs/cli": "^11.0.0",
"@nestjs/schematics": "^11.0.0",
"@nestjs/testing": "^11.0.1",
"@swc/cli": "^0.8.1",
"@swc/core": "^1.15.24",
"@types/express": "^5.0.0",
"@types/jest": "^30.0.0",
"@types/node": "^22.10.7",
"@types/supertest": "^6.0.2",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^16.0.0",
"jest": "^30.0.0",
"prettier": "^3.4.2",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-loader": "^9.5.2",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.7.3",
"typescript-eslint": "^8.20.0"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
+22
View File
@@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});
+16
View File
@@ -0,0 +1,16 @@
import { Controller, Get } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { AppService } from './app.service';
// 루트 컨트롤러 — 헬스체크/디버그 용 단순 엔드포인트
@ApiTags('App')
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get('hello')
@ApiOperation({ summary: '동작 확인용 Hello World' })
getHello(): string {
return this.appService.getHello();
}
}
+74
View File
@@ -0,0 +1,74 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ConfigModule } from '@nestjs/config';
import { ScheduleModule } from '@nestjs/schedule';
import { ThrottlerGuard, ThrottlerModule } from '@nestjs/throttler';
import { CacheModule } from '@nestjs/cache-manager';
import { APP_GUARD } from '@nestjs/core';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { HealthModule } from './modules/health/health.module';
import { UserModule } from './modules/user/user.module';
import { EventsModule } from './modules/events/events.module';
@Module({
imports: [
ScheduleModule.forRoot(),
ConfigModule.forRoot({
isGlobal: true,
envFilePath: `.env.${process.env.NODE_ENV || 'development'}`,
}),
// 전역 캐시 매니저 — Redis 도입 시 store 옵션을 redisStore 로 변경
CacheModule.register({
isGlobal: true,
ttl: 60_000, // 60초 기본 TTL
}),
// 전역 Rate Limiter — main.ts 의 express-rate-limit 와 별개로 라우트 단위 제어 가능
ThrottlerModule.forRoot([
{
ttl: 60_000,
limit: 100,
},
]),
TypeOrmModule.forRootAsync({
useFactory: () => {
const isProduction = process.env.NODE_ENV === 'production';
return {
type: 'postgres',
host: process.env.DB_HOST || 'db',
port: parseInt(process.env.DB_PORT || '5432', 10),
username:
process.env.DB_USER || process.env.DB_USERNAME || 'postgres',
password: process.env.DB_PASSWORD || 'password',
database:
process.env.DB_NAME || process.env.DB_DATABASE || 'project_db',
autoLoadEntities: true,
// 운영 환경에서는 절대 synchronize 사용 금지 (스키마 자동 변경 → 데이터 손실 위험)
synchronize: !isProduction,
migrationsRun: isProduction,
logging: !isProduction,
extra: {
max: 100,
connectionTimeoutMillis: 5000,
idleTimeoutMillis: 30000,
},
entities: [__dirname + '/**/*.entity{.ts,.js}'],
migrations: [__dirname + '/migrations/*{.ts,.js}'],
};
},
}),
HealthModule,
UserModule,
EventsModule,
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
],
})
export class AppModule {}
+8
View File
@@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}
@@ -0,0 +1,72 @@
import {
ArgumentsHost,
Catch,
ExceptionFilter,
HttpException,
HttpStatus,
Logger,
} from '@nestjs/common';
import { Response } from 'express';
// 전역 Exception Filter — CLAUDE.md 에러 코드 맵에 따라 표준 응답으로 변환
@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
private readonly logger = new Logger(HttpExceptionFilter.name);
catch(exception: unknown, host: ArgumentsHost): void {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
let status: number = HttpStatus.INTERNAL_SERVER_ERROR;
let code = 'SYS_001';
let message = '일시적인 시스템 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.';
if (exception instanceof HttpException) {
status = exception.getStatus();
const exceptionResponse = exception.getResponse();
if (status === HttpStatus.UNAUTHORIZED) {
code = 'AUTH_001';
message = '로그인이 필요한 서비스입니다. 로그인 후 이용해 주세요.';
} else if (status === HttpStatus.FORBIDDEN) {
code = 'AUTH_003';
message = '해당 메뉴나 기능에 접근할 수 있는 권한이 없습니다.';
} else if (status === HttpStatus.NOT_FOUND) {
code = 'RES_001';
message = '요청하신 정보나 페이지를 찾을 수 없습니다.';
} else if (
status === HttpStatus.BAD_REQUEST ||
status === HttpStatus.UNPROCESSABLE_ENTITY
) {
code = 'VAL_001';
message = '입력하신 정보를 다시 확인해 주세요. (필수값 누락 또는 형식 오류)';
} else {
code = 'BIZ_001';
message = '요청하신 작업을 완료하지 못했습니다. 다시 시도해 주세요.';
// 비즈니스 예외에서는 사용자에게 보일 메시지를 재정의 가능
if (
typeof exceptionResponse === 'object' &&
exceptionResponse !== null &&
'message' in exceptionResponse
) {
const responseMessage = (exceptionResponse as { message: unknown }).message;
if (typeof responseMessage === 'string') {
message = responseMessage;
}
}
}
} else {
// 정의되지 않은 예외 → 운영팀이 추적 가능하도록 로그 + SYS_001 응답 유지
this.logger.error('Unhandled Exception', exception as Error);
}
response.status(status).json({
success: false,
error: {
code,
message,
},
});
}
}
@@ -0,0 +1,31 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
export interface StandardResponse<T> {
success: boolean;
data: T;
}
@Injectable()
export class TransformInterceptor<T>
implements NestInterceptor<T, StandardResponse<T>>
{
intercept(
_context: ExecutionContext,
next: CallHandler,
): Observable<StandardResponse<T>> {
// 이미 Http 응답객체인 경우 등 예외처리가 필요할 수 있으나 기본적으로 data 래핑
return next.handle().pipe(
map((data) => ({
success: true,
data: data !== undefined ? data : null,
})),
);
}
}
+103
View File
@@ -0,0 +1,103 @@
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Logger, RequestMethod, ValidationPipe } from '@nestjs/common';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { WinstonModule } from 'nest-winston';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import type { Request as ExpressRequest, Response as ExpressResponse } from 'express';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { winstonConfig } from './shared/logger/winston.config';
async function bootstrap() {
const app = await NestFactory.create(AppModule, {
logger: WinstonModule.createLogger(winstonConfig),
});
// 리버스 프록시(Nginx, Docker 배포 환경 등) 뒤에서 올바른 클라이언트 IP 식별 지원을 위해 설정합니다.
const expressApp = app.getHttpAdapter().getInstance();
expressApp.set('trust proxy', 1);
// 글로벌 prefix — 모든 라우트가 /api/* 로 정규화됨 (Flutter, Web 양쪽 baseURL과 일치)
app.setGlobalPrefix('api', {
// 헬스체크 / 루트 상태 엔드포인트는 prefix 미적용
exclude: [{ path: '/', method: RequestMethod.GET }],
});
// 기본 주소('/') 접속 시 상태 확인용 텍스트 응답 추가
expressApp.get('/', (_req: ExpressRequest, res: ExpressResponse) => {
res.send('Backend API Server is running 정상 구동 중입니다.');
});
// 1. 보안 헤더 (Helmet) - XSS 방지 및 기본 웹 보안
app.use(helmet());
// 2. 화이트리스트 기반 CORS 정책
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:5173';
const corsOriginEnv = process.env.CORS_ORIGIN;
app.enableCors({
origin: (
origin: string | undefined,
callback: (err: Error | null, allow?: boolean) => void,
) => {
// 서버간의 통신(origin이 undefined)이거나 명시된 리스트일 때만 허용
const whitelist = [frontendUrl, 'http://localhost:3000'];
if (corsOriginEnv) whitelist.push(corsOriginEnv);
if (!origin || whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
// 클라이언트에는 403 금지 에러로 리턴됨
callback(new Error('CORS 정책에 의해 차단된 도메인입니다.'));
}
},
credentials: true, // 쿠키 교환 허용
});
// 3. 글로벌 Rate Limiting 적용 (DDoS, 브루트포스 예방)
app.use(
rateLimit({
windowMs: 15 * 60 * 1000, // 15분
max: 150, // 15분 IP당 최대 150개 요청
message: {
success: false,
error: {
code: 'SYS_001',
message: '일시적인 시스템 오류가 발생했습니다. (요청 한도 초과) 잠시 후 다시 시도해 주세요.', // 글로벌 통합 에러 포맷
}
},
}),
);
// 4. 전역 DTO 유효성 파이프 (강력한 검증 단계)
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // DTO에 불필요한 값이 오면 삭제
forbidNonWhitelisted: true, // DTO에 없는 필드가 주입되면 400 에러 발생
transform: true, // 네트워크 데이터를 DTO나 기본 타입으로 자동 변환
}),
);
// 5. 프론트엔드 연동을 위한 규격화된 에러 & 성공 페이로드 인터셉터 적용
app.useGlobalFilters(new HttpExceptionFilter());
app.useGlobalInterceptors(new TransformInterceptor());
// 6. Swagger API 문서 설정
const config = new DocumentBuilder()
.setTitle('Backend API Documentation')
.setDescription('The API documentation conforming to the global guidelines')
.setVersion('1.0')
.addBearerAuth()
.build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api-docs', app, document);
const port = Number(process.env.PORT ?? 3000);
await app.listen(port, '0.0.0.0');
Logger.log(`🚀 Backend running on http://localhost:${port}/api`, 'Bootstrap');
Logger.log(`📘 Swagger docs at http://localhost:${port}/api-docs`, 'Bootstrap');
}
bootstrap();
@@ -0,0 +1,43 @@
import { ApiProperty } from '@nestjs/swagger';
// 진행중 이벤트 응답 DTO (sa.nexon.com 이벤트 목록 크롤링 결과)
export class OngoingEventDto {
@ApiProperty({ description: '이벤트 제목', example: '다이너마트 오픈!' })
title!: string;
@ApiProperty({
description: '이벤트 요약 설명',
example: '정채연, 웬디 캐릭터 영구제와 프라임 치어리더II 획득의 기회!',
})
sub!: string;
@ApiProperty({
description: '이벤트 배너 이미지 URL',
example: 'https://img-sa-file.nexon.com/event/20260611072536.jpg',
})
image!: string;
@ApiProperty({
description: '이벤트 기간',
example: '2026.06.11 ~ 2026.06.25',
})
period!: string;
@ApiProperty({
description: '원문 상세 페이지 링크',
example: 'https://sa.nexon.com/news/events/view.aspx?n4ArticleSN=2095',
})
link!: string;
@ApiProperty({
description: '종료까지 남은 일수 (예: D-14, D-DAY)',
example: 'D-14',
})
dday!: string;
@ApiProperty({
description: '분류 태그 (이벤트 / 업데이트)',
example: '이벤트',
})
tag!: string;
}
@@ -0,0 +1,39 @@
import {
Column,
Entity,
PrimaryGeneratedColumn,
UpdateDateColumn,
} from 'typeorm';
// 진행중 이벤트 저장 테이블 (주 1회 크롤링 결과를 영속화)
// ※ D-day 는 기간(period)에 따라 조회 시점마다 달라지므로 저장하지 않고 읽을 때 계산한다.
@Entity('sa_events')
export class SaEventEntity {
@PrimaryGeneratedColumn()
id!: number;
@Column({ type: 'varchar', length: 300 })
title!: string;
@Column({ type: 'varchar', length: 500, default: '' })
sub!: string;
@Column({ type: 'varchar', length: 1000, default: '' })
image!: string;
@Column({ type: 'varchar', length: 100, default: '' })
period!: string;
@Column({ type: 'varchar', length: 1000, default: '' })
link!: string;
@Column({ type: 'varchar', length: 20, default: '이벤트' })
tag!: string;
// 크롤링 순서(사이트 노출 순서) 유지용
@Column({ type: 'int', default: 0 })
sortOrder!: number;
@UpdateDateColumn()
updatedAt!: Date;
}
@@ -0,0 +1,26 @@
import { Controller, Get } from '@nestjs/common';
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { EventsService } from './events.service';
import { OngoingEventDto } from './dto/ongoing-event.dto';
@ApiTags('Events')
@Controller('events')
export class EventsController {
constructor(private readonly eventsService: EventsService) {}
@Get('ongoing')
@ApiOperation({
summary: '진행중 이벤트 목록 조회',
description:
'DB에 저장된 진행중 이벤트를 반환합니다. 원본 데이터는 매주 목요일 10:01(KST) 1회 크롤링으로 갱신됩니다. (방문마다 크롤링하지 않음)',
})
@ApiResponse({
status: 200,
description: '진행중 이벤트 목록 (없으면 빈 배열)',
type: [OngoingEventDto],
})
getOngoing(): Promise<OngoingEventDto[]> {
return this.eventsService.getOngoing();
}
}
@@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { EventsController } from './events.controller';
import { EventsService } from './events.service';
import { SaEventEntity } from './entities/sa-event.entity';
// 진행중 이벤트 모듈 — 주 1회 크롤링(스케줄) + DB 영속
@Module({
imports: [TypeOrmModule.forFeature([SaEventEntity])],
controllers: [EventsController],
providers: [EventsService],
exports: [EventsService],
})
export class EventsModule {}
@@ -0,0 +1,194 @@
import { Injectable, Logger, OnModuleInit } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { load } from 'cheerio';
import { curlFetchHtml } from '../../shared/utils/curl-fetch';
import { OngoingEventDto } from './dto/ongoing-event.dto';
import { SaEventEntity } from './entities/sa-event.entity';
// ────────────────────────────────────────────────────────────
// 서든어택 진행중 이벤트 — 주 1회 크롤링 후 DB 영속, 유저에겐 DB에서 서빙.
// 출처: https://sa.nexon.com/news/events/list.aspx (서버렌더 HTML)
// 갱신 시점: 매주 목요일 10:01(KST) — 정기점검 종료 직후. (방문마다 크롤링 X)
// ────────────────────────────────────────────────────────────
@Injectable()
export class EventsService implements OnModuleInit {
private readonly logger = new Logger(EventsService.name);
private static readonly SOURCE_URL =
'https://sa.nexon.com/news/events/list.aspx';
private static readonly REFERER = 'https://sa.nexon.com/';
private static readonly MAX_PAGES = 10; // 페이지네이션 안전 상한 (무한루프 방지)
constructor(
@InjectRepository(SaEventEntity)
private readonly repo: Repository<SaEventEntity>,
) {}
// 최초 기동 시 데이터가 비어 있으면 1회 시드 크롤링 (부팅을 막지 않도록 백그라운드 실행)
onModuleInit(): void {
void this.seedIfEmpty();
}
private async seedIfEmpty(): Promise<void> {
try {
const count = await this.repo.count();
if (count > 0) return;
this.logger.log('이벤트 데이터가 없어 초기 크롤링을 수행합니다.');
await this.refresh();
} catch (error) {
this.logger.warn(`초기 이벤트 시드 실패: ${(error as Error).message}`);
}
}
// 매주 목요일 10:01 (KST) — 정기점검 종료 후 이벤트 갱신
@Cron('1 10 * * 4', { name: 'weekly-events-refresh', timeZone: 'Asia/Seoul' })
async handleWeeklyRefresh(): Promise<void> {
this.logger.log('주간 이벤트 갱신(목 10:01 KST) 시작');
await this.refresh();
}
/** 크롤링 → 성공·비어있지 않을 때만 DB 전체 교체. 실패/빈 결과 시 기존 데이터 유지. */
async refresh(): Promise<number> {
let events: OngoingEventDto[];
try {
events = await this.crawlAllPages();
} catch (error) {
this.logger.warn(
`이벤트 크롤링 실패(기존 데이터 유지): ${(error as Error).message}`,
);
return 0;
}
if (!events.length) {
this.logger.warn(
'크롤링 결과가 비어 있어 갱신을 건너뜁니다(기존 데이터 유지).',
);
return 0;
}
// 전체 교체 (트랜잭션) — 부분 갱신으로 인한 불일치 방지
await this.repo.manager.transaction(async (m) => {
await m.clear(SaEventEntity);
const rows = events.map((e, i) =>
m.create(SaEventEntity, {
title: e.title,
sub: e.sub,
image: e.image,
period: e.period,
link: e.link,
tag: e.tag,
sortOrder: i,
}),
);
await m.save(rows);
});
this.logger.log(`이벤트 ${events.length}건 갱신 완료`);
return events.length;
}
/** DB에서 진행중 이벤트 조회 (D-day는 조회 시점 기준 재계산). 크롤링하지 않음. */
async getOngoing(): Promise<OngoingEventDto[]> {
const rows = await this.repo.find({ order: { sortOrder: 'ASC' } });
return rows.map((r) => ({
title: r.title,
sub: r.sub,
image: r.image,
period: r.period,
link: r.link,
tag: r.tag,
dday: this.computeDday(r.period),
}));
}
/**
* 진행중 이벤트는 `?n4PageNo=N` 으로 페이지네이션된다.
* 빈 페이지(등록된 글 없음)거나 새 항목이 없을 때까지 순차 수집한다.
*/
private async crawlAllPages(): Promise<OngoingEventDto[]> {
const all: OngoingEventDto[] = [];
const seen = new Set<string>();
for (let page = 1; page <= EventsService.MAX_PAGES; page++) {
const url = `${EventsService.SOURCE_URL}?n4PageNo=${page}`;
const html = await curlFetchHtml(url, { referer: EventsService.REFERER });
const pageEvents = this.parse(html);
if (!pageEvents.length) break; // 빈 페이지 → 마지막 도달
// 페이지 번호 클램핑(같은 페이지 반복) 대비: 신규 항목만 누적, 신규 없으면 종료
let added = 0;
for (const ev of pageEvents) {
const key = `${ev.title}|${ev.period}`;
if (seen.has(key)) continue;
seen.add(key);
all.push(ev);
added++;
}
if (added === 0) break;
}
return all;
}
/** 이벤트 목록 페이지 HTML → DTO 배열 파싱 */
private parse(html: string): OngoingEventDto[] {
const $ = load(html);
const out: OngoingEventDto[] = [];
// 진행중 이벤트 영역: .boardEventList > ul > li
$('.boardEventList ul li').each((_, li) => {
const el = $(li);
const title = el.find('.data .subject').text().trim();
if (!title) return; // 광고/구분용 빈 항목 스킵
const sub = el.find('.data .txt').text().trim();
const image = el.find('.thumb img').attr('src')?.trim() ?? '';
const link = el.find('.data .subject a').attr('href')?.trim() ?? '';
// 기간: '<span>기간</span> 2026.06.11 ~ 2026.06.25' 형태에서 라벨 제거
let period = '';
el.find('.data .icon.info').each((__, info) => {
if ($(info).find('span').first().text().trim() === '기간') {
period = $(info).text().replace('기간', '').trim();
}
});
out.push({
title,
sub,
image,
period,
link: this.normalizeLink(link),
dday: this.computeDday(period),
tag: link.includes('/news/update/') ? '업데이트' : '이벤트',
});
});
return out;
}
/** http → https 정규화 (혼합 콘텐츠 방지) */
private normalizeLink(link: string): string {
return link.replace(/^http:\/\//i, 'https://');
}
/** 기간 문자열의 종료일로 D-day 계산 (예: 'D-14', 'D-DAY') */
private computeDday(period: string): string {
const end = period.split('~')[1]?.trim();
if (!end) return '';
const m = end.match(/(\d{4})[.-](\d{1,2})[.-](\d{1,2})/);
if (!m) return '';
const endDate = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
const now = new Date();
const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
const diffDays = Math.ceil(
(endDate.getTime() - today.getTime()) / 86_400_000,
);
if (diffDays < 0) return '종료';
if (diffDays === 0) return 'D-DAY';
return `D-${diffDays}`;
}
}
@@ -0,0 +1,24 @@
import { Controller, Get } from '@nestjs/common';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import {
HealthCheck,
HealthCheckService,
TypeOrmHealthIndicator,
} from '@nestjs/terminus';
// 헬스체크 엔드포인트 — Docker healthcheck, 모니터링 시스템에서 사용
@ApiTags('Health')
@Controller('health')
export class HealthController {
constructor(
private readonly health: HealthCheckService,
private readonly db: TypeOrmHealthIndicator,
) {}
@Get()
@HealthCheck()
@ApiOperation({ summary: '애플리케이션 상태 확인' })
check() {
return this.health.check([() => this.db.pingCheck('database')]);
}
}
@@ -0,0 +1,9 @@
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller';
@Module({
imports: [TerminusModule],
controllers: [HealthController],
})
export class HealthModule {}
@@ -0,0 +1,20 @@
import { IsEmail, IsNotEmpty, IsString, MinLength } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';
// 사용자 생성 DTO 샘플 — 모든 검증 메시지는 한국어, Swagger 메타 필수
export class CreateUserDto {
@ApiProperty({ description: '사용자 이메일', example: 'user@example.com' })
@IsEmail({}, { message: '올바른 이메일 형식을 입력해 주세요.' })
@IsNotEmpty({ message: '이메일은 필수 입력 항목입니다.' })
email!: string;
@ApiProperty({ description: '비밀번호 (최소 8자)', example: 'password123' })
@IsString()
@MinLength(8, { message: '비밀번호는 최소 8자 이상이어야 합니다.' })
password!: string;
@ApiProperty({ description: '사용자 이름', example: '홍길동' })
@IsString()
@IsNotEmpty({ message: '이름은 필수 입력 항목입니다.' })
name!: string;
}
@@ -0,0 +1,28 @@
import { Body, Controller, Get, Param, ParseIntPipe, Post } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { UserService } from './user.service';
import { CreateUserDto } from './dto/create-user.dto';
// 사용자 도메인 컨트롤러 샘플 — 라우팅과 입출력만 담당, 비즈니스 로직은 모두 service 위임
@ApiTags('User')
@ApiBearerAuth()
@Controller('users')
export class UserController {
constructor(private readonly userService: UserService) {}
@Get(':id')
@ApiOperation({ summary: '사용자 단건 조회' })
@ApiResponse({ status: 200, description: '사용자 조회 성공' })
@ApiResponse({ status: 404, description: '사용자를 찾을 수 없음 (RES_001)' })
findOne(@Param('id', ParseIntPipe) id: number) {
return this.userService.findOne(id);
}
@Post()
@ApiOperation({ summary: '사용자 생성' })
@ApiResponse({ status: 201, description: '사용자 생성 성공' })
@ApiResponse({ status: 400, description: '입력값 검증 실패 (VAL_001)' })
create(@Body() dto: CreateUserDto) {
return this.userService.create(dto);
}
}
+10
View File
@@ -0,0 +1,10 @@
import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
@Module({
controllers: [UserController],
providers: [UserService],
exports: [UserService],
})
export class UserModule {}
+25
View File
@@ -0,0 +1,25 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
// 비즈니스 로직 계층 샘플 — 실제 구현 시 Repository 주입하여 데이터 접근
@Injectable()
export class UserService {
// 임시 인메모리 저장소 — Repository 도입 시 교체
private readonly users = new Map<number, { id: number; email: string; name: string }>();
findOne(id: number) {
const user = this.users.get(id);
if (!user) {
// 404 → 전역 필터에서 RES_001 로 변환됨
throw new NotFoundException();
}
return user;
}
create(dto: CreateUserDto) {
const id = this.users.size + 1;
const user = { id, email: dto.email, name: dto.name };
this.users.set(id, user);
return user;
}
}
@@ -0,0 +1,20 @@
import { utilities as nestWinstonUtilities } from 'nest-winston';
import * as winston from 'winston';
// 표준 로거 설정 — console.log 대체용
// 운영 환경에서는 파일 로테이션 또는 외부 로그 수집기(예: Loki, ELK) 추가 권장
export const winstonConfig: winston.LoggerOptions = {
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.timestamp(),
winston.format.ms(),
nestWinstonUtilities.format.nestLike('App', {
colors: process.env.NODE_ENV !== 'production',
prettyPrint: true,
}),
),
}),
],
};
+93
View File
@@ -0,0 +1,93 @@
import { execFile } from 'node:child_process';
// ────────────────────────────────────────────────────────────
// curl 기반 HTML fetch 유틸
// 넥슨 SA 사이트는 Node 의 TLS 지문(JA3)을 차단하므로(axios/native https → 403),
// 시스템 curl 바이너리를 통해 요청한다. URL 은 호출부의 상수이며 사용자 입력이
// 아니고, execFile(쉘 미경유)을 사용하므로 커맨드 인젝션 위험이 없다.
// ※ 배포(Docker) 이미지에 curl 패키지가 설치되어 있어야 한다.
// ────────────────────────────────────────────────────────────
const DEFAULT_UA =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36';
export interface CurlFetchOptions {
/** Referer 헤더 (안티봇 우회에 필요한 경우) */
referer?: string;
/** 타임아웃(초) — 기본 12초 */
timeoutSec?: number;
/** 최대 응답 버퍼(MB) — 기본 10MB */
maxBufferMb?: number;
}
/** curl 로 URL 을 GET 하여 본문(HTML/텍스트)을 문자열로 반환 */
export function curlFetchHtml(
url: string,
opts: CurlFetchOptions = {},
): Promise<string> {
const { referer, timeoutSec = 12, maxBufferMb = 10 } = opts;
// 넥슨 WAF 우회 핵심: 반드시 HTTP/2(--http2)로 요청하고, 브라우저(Chrome) 헤더를
// 함께 보낸다. 단 `--compressed`(Accept-Encoding: gzip,deflate,br,zstd)는 차단을
// 유발하므로 사용하지 않는다(서버는 압축 없이 평문 HTML 반환).
const args = [
'-sSL', // silent + 에러 표시 + 리다이렉트 추적
'--http2', // HTTP/2 강제 — 미적용 시 403
'--max-time',
String(timeoutSec),
'-A',
DEFAULT_UA,
'-H',
'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
'-H',
'Accept-Language: ko-KR,ko;q=0.9',
'-H',
'sec-ch-ua: "Chromium";v="126", "Not.A/Brand";v="24"',
'-H',
'sec-ch-ua-mobile: ?0',
'-H',
'sec-ch-ua-platform: "Windows"',
'-H',
'Sec-Fetch-Dest: document',
'-H',
'Sec-Fetch-Mode: navigate',
'-H',
'Sec-Fetch-Site: none',
'-H',
'Sec-Fetch-User: ?1',
'-H',
'Upgrade-Insecure-Requests: 1',
];
if (referer) {
args.push('-H', `Referer: ${referer}`);
}
args.push(url);
return new Promise<string>((resolve, reject) => {
execFile(
'curl',
args,
{
maxBuffer: maxBufferMb * 1024 * 1024,
windowsHide: true,
encoding: 'utf8',
},
(err, stdout, stderr) => {
if (err) {
reject(
new Error(
`curl 요청 실패: ${stderr?.toString().trim() || err.message}`,
),
);
return;
}
const body = stdout?.toString() ?? '';
if (!body) {
reject(new Error('curl 응답 본문이 비어 있습니다.'));
return;
}
resolve(body);
},
);
});
}
+13
View File
@@ -0,0 +1,13 @@
// 공통 포맷터 — 부수효과 없는 순수 함수만 작성
/**
* Date 또는 ISO 문자열을 'YYYY-MM-DD' 형식으로 변환
*/
export function formatDate(input: Date | string): string {
const date = typeof input === 'string' ? new Date(input) : input;
if (Number.isNaN(date.getTime())) return '';
const yyyy = date.getFullYear();
const mm = String(date.getMonth() + 1).padStart(2, '0');
const dd = String(date.getDate()).padStart(2, '0');
return `${yyyy}-${mm}-${dd}`;
}
+25
View File
@@ -0,0 +1,25 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import request from 'supertest';
import { App } from 'supertest/types';
import { AppModule } from './../src/app.module';
describe('AppController (e2e)', () => {
let app: INestApplication<App>;
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
});
+9
View File
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "./tsconfig.json",
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
}
+33
View File
@@ -0,0 +1,33 @@
{
"compilerOptions": {
"module": "nodenext",
"moduleResolution": "nodenext",
"resolvePackageJsonExports": true,
"esModuleInterop": true,
"isolatedModules": true,
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strict": true,
"strictNullChecks": true,
"noImplicitAny": true,
"strictBindCallApply": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"watchOptions": {
"watchFile": "priorityPollingInterval",
"watchDirectory": "dynamicPriorityPolling",
"fallbackPolling": "dynamicPriority"
}
}