Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[chore]: bull.js 사용을 위한 환경 설정 #103

Merged
merged 10 commits into from
Mar 30, 2022
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class FavoriteSummonerApiController {
async createFollow(
@CurrentUser() userDto: UserReq,
@Body() favoriteSummonerDto: FavoriteSummonerReq,
) {
): Promise<ResponseEntity<string>> {
try {
await this.favoriteSummonerApiService.createFavoriteSummoner(
userDto,
Expand Down Expand Up @@ -138,7 +138,7 @@ export class FavoriteSummonerApiController {
async deleteFollow(
@CurrentUser() userDto: UserReq,
@Body() favoriteSummonerIdDto: FavoriteSummonerIdReq,
) {
): Promise<ResponseEntity<string>> {
try {
await this.favoriteSummonerApiService.deleteFavoriteSummoner(
userDto,
Expand Down Expand Up @@ -180,7 +180,9 @@ export class FavoriteSummonerApiController {
@ApiBearerAuth('Authorization')
@UseGuards(JwtAuthGuard)
@Get()
async getFollow(@CurrentUser() userDto: UserReq) {
async getFollow(
@CurrentUser() userDto: UserReq,
): Promise<ResponseEntity<FavoriteSummonerRes[] | string>> {
try {
const data: FavoriteSummonerRes[] =
await this.favoriteSummonerApiService.getFavoriteSummoner(
Expand Down
29 changes: 29 additions & 0 deletions apps/push/src/PushAppModule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { PushApiModule } from './push/PushApiModule';
import { getBullModule } from '../../../libs/entity/getBullModule';
import { HealthCheckController } from './health-check/HealthCheckController';
import { getTypeOrmModule } from '../../../libs/entity/getTypeOrmModule';
import { LoggingModule } from '@app/common-config/logging/logging.module';
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { TerminusModule } from '@nestjs/terminus';
import { HttpModule } from '@nestjs/axios';

import { AuthConfig, ValidationSchema } from '@app/common-config/config';

@Module({
imports: [
ConfigModule.forRoot({
load: [AuthConfig],
isGlobal: true,
validationSchema: ValidationSchema,
}),
getTypeOrmModule(),
getBullModule(),
LoggingModule,
TerminusModule,
HttpModule,
PushApiModule,
],
controllers: [HealthCheckController],
})
export class PushAppModule {}
25 changes: 25 additions & 0 deletions apps/push/src/health-check/HealthCheckController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Controller, Get } from '@nestjs/common';
import {
HealthCheckService,
HttpHealthIndicator,
TypeOrmHealthIndicator,
HealthCheck,
} from '@nestjs/terminus';

@Controller('health-check')
export class HealthCheckController {
constructor(
private health: HealthCheckService,
// private http: HttpHealthIndicator,
private db: TypeOrmHealthIndicator,
) {}

@Get()
@HealthCheck()
check() {
return this.health.check([
// () => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
() => this.db.pingCheck('database'),
]);
}
}
64 changes: 64 additions & 0 deletions apps/push/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { NestFactory } from '@nestjs/core';
import * as winston from 'winston';
import {
utilities as nestWinstonModuleUtilities,
WinstonModule,
} from 'nest-winston';
import { PushAppModule } from './PushAppModule';
import { NestExpressApplication } from '@nestjs/platform-express';
import { Logger } from '@nestjs/common';
import { SetNestApp } from '@app/common-config/setNestApp';

class Application {
private logger = new Logger(Application.name);
private PORT: string;
private DEV_MODE: boolean;

constructor(private server: NestExpressApplication) {
this.server = server;
this.PORT = process.env.PUSH_PORT;
this.DEV_MODE = process.env.NODE_ENV === 'production' ? false : true;
}

async bootstrap() {
SetNestApp(this.server);
await this.server.listen(this.PORT);
}

startLog() {
if (this.DEV_MODE) {
this.logger.log(`✅ Server on http://localhost:${this.PORT}`);
} else {
this.logger.log(`✅ Server on port ${this.PORT}...`);
}
}
}

async function bootstrap(): Promise<void> {
const server = await NestFactory.create<NestExpressApplication>(
PushAppModule,
{
logger: WinstonModule.createLogger({
transports: [
new winston.transports.Console({
level: process.env.NODE_ENV === 'production' ? 'info' : 'silly',
format: winston.format.combine(
winston.format.timestamp(),
nestWinstonModuleUtilities.format.nestLike('PushApp', {
prettyPrint: true,
}),
),
}),
],
}),
},
);

const app = new Application(server);
await app.bootstrap();
app.startLog();
}

bootstrap().catch(error => {
new Logger('init').error(error);
});
13 changes: 13 additions & 0 deletions apps/push/src/push/PushApiConsumer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Process, Processor } from '@nestjs/bull';
import { Logger } from '@nestjs/common';
import { Job } from 'bull';

@Processor('testQueue')
export class PushApiConsumer {
private readonly logger = new Logger(PushApiConsumer.name);

@Process('task')
getMessageQueue(job: Job) {
this.logger.log(`${job.id} 번 작업을 수신했습니다.`);
}
}
24 changes: 24 additions & 0 deletions apps/push/src/push/PushApiController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { ResponseEntity } from '@app/common-config/response/ResponseEntity';
import { Body, Controller, Inject, Post } from '@nestjs/common';
import { WINSTON_MODULE_NEST_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
import { PushApiService } from './PushApiService';

@Controller()
export class PushApiController {
constructor(
private readonly pushApiService: PushApiService,
@Inject(WINSTON_MODULE_NEST_PROVIDER) private readonly logger: Logger,
) {}

@Post('queue')
async addMessage(@Body() data: number): Promise<ResponseEntity<string>> {
try {
await this.pushApiService.addMessageQueue(data);
return ResponseEntity.OK_WITH('메시지 전송에 성공했습니다.');
} catch (error) {
this.logger.error(`dto = ${JSON.stringify(data)}`, error);
return ResponseEntity.ERROR_WITH('메시지 전송에 실패했습니다.');
}
}
}
18 changes: 18 additions & 0 deletions apps/push/src/push/PushApiModule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Module } from '@nestjs/common';
import { WinstonModule } from 'nest-winston';
import { getWinstonLogger } from '@app/common-config/getWinstonLogger';
import { PushApiController } from './PushApiController';
import { PushApiService } from './PushApiService';
import { getBullQueue } from '../../../../libs/entity/queue/getBullQueue';
import { PushApiConsumer } from './PushApiConsumer';

@Module({
imports: [
WinstonModule.forRoot(getWinstonLogger(process.env.NODE_ENV, 'push')),
getBullQueue(),
],
controllers: [PushApiController],
providers: [PushApiService, PushApiConsumer],
exports: [getBullQueue()],
})
export class PushApiModule {}
23 changes: 23 additions & 0 deletions apps/push/src/push/PushApiService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { InjectQueue } from '@nestjs/bull';
import { Injectable } from '@nestjs/common';
import { Queue, Job } from 'bull';

@Injectable()
export class PushApiService {
constructor(
@InjectQueue('testQueue')
private testQueue: Queue,
) {}

async addMessageQueue(data: number): Promise<Job> {
const job = await this.testQueue.add(
'task',
{
dataId: data,
},
{ delay: 3000 },
);

return job;
}
}
9 changes: 9 additions & 0 deletions apps/push/tsconfig.app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"declaration": false,
"outDir": "../../dist/apps/push"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}
3 changes: 0 additions & 3 deletions libs/common-config/src/config/index 2.ts

This file was deleted.

1 change: 1 addition & 0 deletions libs/common-config/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './authConfig';
export * from './validationSchema';
export * from './databaseConfig';
10 changes: 10 additions & 0 deletions libs/common-config/src/config/validationSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import * as Joi from 'joi';

export const ValidationSchema = Joi.object({
PORT: Joi.string().required(),
PUSH_PORT: Joi.string().required(),

DB_HOST: Joi.string().required(),
DB_PORT: Joi.string().required(),
DB_NAME: Joi.string().required(),
Expand All @@ -18,5 +20,13 @@ export const ValidationSchema = Joi.object({
TEST_LOGGING: Joi.string().required(),
TEST_SYNCHRONIZE: Joi.string().required(),

REDIS_HOST: Joi.string().required(),
REDIS_PORT: Joi.string().required(),

REDIS_TEST_HOST: Joi.string().required(),
REDIS_TEST_PORT: Joi.string().required(),

API_KEY: Joi.string().required(),

JWT_SECRET_KEY: Joi.string().required(),
});
File renamed without changes.
15 changes: 15 additions & 0 deletions libs/entity/config/redisConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import * as dotenv from 'dotenv';
import { QueueOptions } from 'bull';

dotenv.config();

const [host, port] =
process.env.NODE_ENV === 'production'
? [process.env.REDIS_HOST, process.env.REDIS_PORT]
: [process.env.REDIS_TEST_HOST, process.env.REDIS_TEST_PORT];

const RedisConfig: QueueOptions = {
redis: { host, port: Number(port) },
};

export = RedisConfig;
File renamed without changes.
6 changes: 6 additions & 0 deletions libs/entity/getBullModule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { BullModule } from '@nestjs/bull';
import * as RedisConfig from './config/redisConfig';

export function getBullModule() {
return BullModule.forRoot(RedisConfig);
}
2 changes: 1 addition & 1 deletion libs/entity/getTypeOrmModule.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TypeOrmModule } from '@nestjs/typeorm';
import * as ormConfig from './ormConfig';
import * as ormConfig from './config/ormConfig';

export function getTypeOrmModule() {
return TypeOrmModule.forRoot(ormConfig);
Expand Down
7 changes: 7 additions & 0 deletions libs/entity/queue/getBullQueue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { BullModule } from '@nestjs/bull';

export function getBullQueue() {
return BullModule.registerQueue({
name: 'testQueue',
});
}
12 changes: 11 additions & 1 deletion nest-cli.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"collection": "@nestjs/schematics",
"sourceRoot": "apps/api/src",
"sourceRoot": "apps/push/src",
"monorepo": true,
"projects": {
"entity": {
"type": "library",
Expand All @@ -20,6 +21,15 @@
"tsConfigPath": "apps/api/tsconfig.app.json"
}
},
"push": {
"type": "application",
"root": "apps/push",
"entryFile": "main",
"sourceRoot": "apps/push/src",
"compilerOptions": {
"tsConfigPath": "apps/push/tsconfig.app.json"
}
},
"common-config": {
"type": "library",
"root": "libs/common-config",
Expand Down
Loading