From 93d1c3a2da86c62b2430ce00ebd7f75b74fd899a Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 25 Jul 2023 01:25:08 +0900 Subject: [PATCH] =?UTF-8?q?=EC=9D=B5=EC=85=89=EC=85=98=20=ED=95=84?= =?UTF-8?q?=ED=84=B0=EB=A7=81=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/http-exception.filter.ts | 9 ------- .../counseling/api/counseling.controller.ts | 11 ++++++--- src/module/counseling/data/counseling.db.ts | 24 +++++++++++++------ .../domain/counseling.repository.ts | 2 +- .../counseling/domain/counseling.service.ts | 14 +++++++---- src/response.ts | 18 ++++++++++++++ 6 files changed, 53 insertions(+), 25 deletions(-) create mode 100644 src/response.ts diff --git a/src/http-exception.filter.ts b/src/http-exception.filter.ts index 24253df..af4bb43 100644 --- a/src/http-exception.filter.ts +++ b/src/http-exception.filter.ts @@ -17,23 +17,14 @@ export class HttpExceptionFilter implements ExceptionFilter { const error = exception.getResponse() as | string | { error: string; statusCode: number; message: string | string[] }; - console.log( - 'exception.getResponse()', - exception.getResponse(), - 'typeof error:', - typeof error, - ); if (typeof error === 'string') { response.status(status).json({ - success: false, - statusCode: status, timestamp: moment().format('YYYY-MM-DD HH:mm:ss'), path: request.url, error: error, }); } else { response.status(status).json({ - success: false, timestamp: moment().format('YYYY-MM-DD HH:mm:ss'), path: request.url, ...error, diff --git a/src/module/counseling/api/counseling.controller.ts b/src/module/counseling/api/counseling.controller.ts index 551f423..e7111b6 100644 --- a/src/module/counseling/api/counseling.controller.ts +++ b/src/module/counseling/api/counseling.controller.ts @@ -22,11 +22,14 @@ import { counselingDataBaseError, } from './../counseling.error'; import { HttpExceptionFilter } from './../../../http-exception.filter'; +import { Response } from './../../../response'; @Controller('counseling') export class CounselingController { + private response: Response; constructor(private readonly counselingService: CounselingService) { this.mapper = new CounselingMapper(); + this.response = new Response(); } private mapper: CounselingMapper; @@ -37,10 +40,12 @@ export class CounselingController { async registerCounseling(@Body() counselingData: CreateCounselingDto) { try { const counselingInfo = this.mapper.mapCreateDtoToDomain(counselingData); - return await this.counselingService.registerCounseling(counselingInfo); + const result = await this.counselingService.registerCounseling( + counselingInfo, + ); + return this.response.success(result); } catch (error) { - throw new HttpException(error, 401); - //return { message: error.message }; + throw error; } } diff --git a/src/module/counseling/data/counseling.db.ts b/src/module/counseling/data/counseling.db.ts index a39d97b..c187468 100644 --- a/src/module/counseling/data/counseling.db.ts +++ b/src/module/counseling/data/counseling.db.ts @@ -1,4 +1,8 @@ -import { Injectable } from '@nestjs/common'; +import { + Injectable, + BadRequestException, + InternalServerErrorException, +} from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository, Between } from 'typeorm'; import { @@ -16,6 +20,8 @@ import { import { CounselingMapper } from '../counseling.mapper'; import { DoctorEntity } from '../../doctor/data/doctor.entity'; import { PetEntity } from '../../pet/data/pet.entity'; +import Logger from './../../../logger'; +const logger = new Logger('counseling.db'); //Injectable이 이걸 다른곳에 주입할수있단거 같음. // Repository !== TypeOrm.Repsository => 완전한 Decoupling 을 달성할 수 있음 ! = > 이게 개발적으로 제가 생각하는 최적의 구조다. by 허재 @@ -36,21 +42,19 @@ export class CounselingRepositoryImpl implements CounselingRepository { private mapper: CounselingMapper; - async registerCounselingHistory( - info: CounselingCreateInfo, - ): Promise { + async registerCounseling(info: CounselingCreateInfo): Promise { // User 정보도 가져와야 함 ( 왜 ? Counseling 도메인은 그 상담내역의 대상자 주인 이름이 들어가기 때문 id가 아니라 ) // pet 이 있는지 + 그 user 가 주인이 맞는지 ? const pet = await this.PetDB.findOne({ where: { id: info.petId }, }); - if (pet === null) throw new InvalidCounselingInfoError('애완동물'); + if (pet === null) throw new BadRequestException('잘못된 반려동물입니다.'); // doctor 가 있는지 ? const doctor = await this.DoctorDB.findOne({ where: { id: info.doctorId }, }); - if (doctor === null) throw new InvalidCounselingInfoError('의사'); + if (doctor === null) throw new BadRequestException('잘못된 의사입니다.'); // // CounselingEntity 만들어서 저장 // const entity = this.CounselingDB.create({ @@ -69,7 +73,13 @@ export class CounselingRepositoryImpl implements CounselingRepository { update : 수정 ( id 찾아보고 없으면 터짐 ) save : 조회해보고 생성 or 수정 ( 터지진 않음 ) */ - const result = await this.CounselingDB.insert(entity); + let result; + try { + result = await this.CounselingDB.insert(entity); + } catch (error) { + logger.error('registerCounseling - database error'); + throw new InternalServerErrorException(); + } return await this.getOneCounseling(result.identifiers[0].id); } diff --git a/src/module/counseling/domain/counseling.repository.ts b/src/module/counseling/domain/counseling.repository.ts index 1224921..1872691 100644 --- a/src/module/counseling/domain/counseling.repository.ts +++ b/src/module/counseling/domain/counseling.repository.ts @@ -14,7 +14,7 @@ export const COUNSELING_REPOSITORY = 'Counseling Repository'; export interface CounselingRepository { // 진료내역을 저장하고, 성공했는지 반환함 - registerCounselingHistory(info: CounselingCreateInfo): Promise; + registerCounseling(info: CounselingCreateInfo): Promise; // start ~ end 사이의 히스토리를 반환함 getCounselingHistories(startDate: Date, endDate: Date): Promise; //예약이나 진료 하나를 반환함 diff --git a/src/module/counseling/domain/counseling.service.ts b/src/module/counseling/domain/counseling.service.ts index 84bb97b..d26c7fa 100644 --- a/src/module/counseling/domain/counseling.service.ts +++ b/src/module/counseling/domain/counseling.service.ts @@ -1,4 +1,9 @@ -import { Inject, Injectable } from '@nestjs/common'; +import { + Inject, + Injectable, + BadRequestException, + HttpException, +} from '@nestjs/common'; import { Counseling, CounselingCreateInfo, @@ -30,15 +35,14 @@ export class CounselingService { //this.validateRequestInfo(info); // 1. 등록날짜는 현재 시각보단 작으면 안됨 if (new Date(info.dateTime).getTime() <= Date.now()) { - throw new InvalidCounselingInfoError('날짜'); + throw new BadRequestException('잘못된 날짜입니다.'); } let result: Counseling; try { - result = await this.repository.registerCounselingHistory(info); + result = await this.repository.registerCounseling(info); } catch (error) { - logger.error('registerCounseling - database error'); - return null; + throw error; } // 서비스에서 nest.js 에 의존성을 물고 있는 오류가 있을까 ? diff --git a/src/response.ts b/src/response.ts new file mode 100644 index 0000000..e8802c9 --- /dev/null +++ b/src/response.ts @@ -0,0 +1,18 @@ +import moment from 'moment'; + +// export type BaseResponse = { +// statusCode: number; +// timestamp: String; +// message: String; +// }; + +export class Response { + success(result?: any) { + return { + statusCode: 200, + timestamp: moment().format('YYYY-MM-DD HH:mm:ss'), + message: '성공', + result: result, + }; + } +}