Skip to content

Commit

Permalink
Feature/#341 알림 수 200개 제한 해제, join column 이름 다시 롤백 (#356)
Browse files Browse the repository at this point in the history
* 🐛 fix: join column에 user_id 이름 추가

* 🐛 fix: websocketclient에러 수정

* 🐛 fix: join column 롤백

* ♻️ refactor: 알림 수 200개 제한 해제

* 💄 style: 테스트 코드 삭제

* 📝 docs: request volum + e

* 📝 docs: apiresponse status 201 정상화
  • Loading branch information
swkim12345 authored Dec 4, 2024
1 parent 830dcd1 commit 2a6d07a
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 29 deletions.
13 changes: 10 additions & 3 deletions packages/backend/src/alarm/alarm.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@ import {
Delete,
UseGuards,
} from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiParam } from '@nestjs/swagger';
import {
ApiOkResponse,
ApiOperation,
ApiParam,
ApiResponse,
} from '@nestjs/swagger';
import { AlarmService } from './alarm.service';
import { AlarmRequest } from './dto/alarm.request';
import { AlarmResponse, AlarmSuccessResponse } from './dto/alarm.response';
Expand All @@ -25,7 +30,8 @@ export class AlarmController {
summary: '알림 생성',
description: '각 정보에 맞는 알림을 생성한다.',
})
@ApiOkResponse({
@ApiResponse({
status: 201,
description: '알림 생성 완료',
type: AlarmResponse,
})
Expand Down Expand Up @@ -64,7 +70,8 @@ export class AlarmController {
summary: '등록된 알림 업데이트',
description: '알림 아이디 기준으로 업데이트를 할 수 있다.',
})
@ApiOkResponse({
@ApiResponse({
status: 201,
description: '아이디와 동일한 알림 업데이트',
type: AlarmResponse,
})
Expand Down
2 changes: 1 addition & 1 deletion packages/backend/src/alarm/dto/alarm.request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class AlarmRequest {
example: 1000,
required: false,
})
targetVolum?: number;
targetVolume?: number;

@ApiProperty({
description: '알림 종료 날짜',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class OpenapiMinuteData {
private readonly entity = StockMinutely;
private readonly url: string =
'/uapi/domestic-stock/v1/quotations/inquire-time-itemchartprice';
private readonly STOCK_LIMITS: number = 200;

constructor(
private readonly datasource: DataSource,
private readonly openapiQueue: OpenapiQueue,
Expand All @@ -41,10 +41,7 @@ export class OpenapiMinuteData {
.createQueryBuilder('alarm')
.leftJoin('alarm.stock', 'stock')
.select('stock.id', 'stockId')
.addSelect('COUNT(alarm.id)', 'alarmCount')
.groupBy('stock.id')
.orderBy('alarmCount', 'DESC')
.limit(this.STOCK_LIMITS)
.execute();
for (const alarm of alarms) {
const time = getCurrentTime();
Expand Down
4 changes: 0 additions & 4 deletions packages/backend/src/scraper/openapi/liveData.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,6 @@ export class LiveData {
}
this.connect();
});
this.subscribe('005930');
this.subscribe('000660');
this.subscribe('000150');
this.subscribe('000020');
}

private async openapiSubscribe(stockId: string) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,68 +1,68 @@
import { Inject, Injectable } from '@nestjs/common';
import { Logger } from 'winston';
import { RawData, WebSocket } from 'ws';

@Injectable()
export class WebsocketClient {
static url = process.env.WS_URL ?? 'ws://ops.koreainvestment.com:21000';
private client: WebSocket;
//현재 factory 패턴을 이용해 할당하면 socket이 열리기 전에 message가 가는 문제가 있음.
// 소켓이 할당되기 전에(client에 소켓이 없을 때) message를 보내려 시도함.
private messageQueue: string[] = [];

constructor(@Inject('winston') private readonly logger: Logger) {
this.client = new WebSocket(WebsocketClient.url);
this.initOpen(() => this.flushQueue());
this.initError((error) => this.logger.error('WebSocket error', error));
}

static websocketFactory(logger: Logger) {
const websocket = new WebsocketClient(logger);
return websocket;
return new WebsocketClient(logger);
}

subscribe(message: string) {
this.sendMessage(message);
}

unsubscribe(message: string) {
this.sendMessage(message);
}

private initOpen(fn: () => void) {
this.client.on('open', fn);
}

private initMessage(fn: (data: RawData) => void) {
this.client.on('message', fn);
}

private initDisconnect(initCloseCallback: () => void) {
this.client.on('close', initCloseCallback);
}

private initError(initErrorCallback: (error: unknown) => void) {
this.client.on('error', initErrorCallback);
}

connectFacade(
initOpenCallback: (fn: (message: string) => void) => () => void,
initMessageCallback: (client: WebSocket) => (data: RawData) => void,
initCloseCallback: () => void,
initErrorCallback: (error: unknown) => void,
) {
this.initOpen(initOpenCallback(this.sendMessage));
this.initOpen(initOpenCallback(this.sendMessage.bind(this)));
this.initMessage(initMessageCallback(this.client));
this.initDisconnect(initCloseCallback);
this.initError(initErrorCallback);
}

private sendMessage(message: string) {
if (!this.client || !this.client.readyState) {
this.logger.warn('WebSocket is not open. Message not sent. ');
return;
}
if (this.client.readyState === WebSocket.OPEN) {
this.client.send(message);
this.logger.info(`Sent message: ${message}`);
} else {
this.logger.warn('WebSocket is not open. Message not sent. ');
this.logger.warn('WebSocket not open. Queueing message.');
this.messageQueue.push(message); // 큐에 메시지를 추가
}
}

private flushQueue() {
while (this.messageQueue.length > 0) {
const message = this.messageQueue.shift();
if (message) {
this.sendMessage(message);
}
}
}
}

0 comments on commit 2a6d07a

Please sign in to comment.