Wecode -기업협업 인턴 (부트캠프)/기업협업 인턴(프로젝트)

기업협업 2번째 프로젝트- 4일차 shorturl 생성 기능 api 작성 (service 추가,repository)+ 에러 모음

JBS 12 2023. 11. 9. 17:48

 

 

생각해보니,

[칼럼에 Unique 제약 조건을 추가]

 ALTER TABLE dblog ADD CONSTRAINT unique_shortUrl UNIQUE (shortUrl);

terminal 말고 dBeaver에서도 바로 수정 가능했다. 
변경하고 싶은 거를 직접 표에다 하고 'Save' 누르면 아래 창이 뜬다.

Persist 하면 반영 된다. mysql에 쳐봐도 반영됨.

 

 


각종 오류 모음

TypeScript에서는 늘 타입을 지정해주는지 알았는데,
받아올 때만 형태를 지정해주고, 사용할 때에는 필요 없다.

 

 

 

alnum을 alum으로 스펠링 오류

너가 스펠링이 틀려서 그래... ㅎ alum이 아니라 alnum이잖아

 

희한해서 찾아본.

 

 

shortUrl을 shrotUrl
urlEntity를 UrlEntity ...... 이런 실수들로 에러들이 많이 난다. 
return을 하지 않아서 난 오류 

 

--> "function generateUniqueShortUrl(length: number): string {에 대해서, 다음과 같은 에러가 떴어. A function whose declared type is neither 'undefined', 'void', nor 'any' must return a value."

(늘 그렇듯, 관련 없는 메세지가 뜸. return 해주니 말끔히 해결됨" )

 

 

 

데코레이터를 사용하기 위해 NestJS의 @nestjs/common 모듈에서 import하지 않아서 난 에러 

--> "Unable to resolve signature of property decorator when called as an expression. The runtime will invoke the decorator with 2 arguments, but the decorator expects 1."  

--> 해결법 :

import { Body, Controller, Get, Param, Post, Redirect } from '@nestjs/common';

 

 

await 뒤에 점(.)을 사용해서 난 오류 

--> " Expression expected."

 


 

service 추가 

 

 여기에서 generateUniqueShortUrl은 어디에서 만드니? 절대 중복되지 않는 영문 대소문자와 가끔 포함되는 숫자 하나로 



중복되지 않는 영문 대소문자와 가끔 포함되는 숫자를 생성하는 로직을 service, repo중 어디에서 구현하니

--> 중복되지 않는 영문 대소문자와 가끔 포함되는 숫자를 생성하는 로직은 일반적으로 서비스(Service)나 독립적인 유틸리티 함수에서 구현.
이러한 로직은 데이터베이스와 직접적으로 관련이 없기 때문에 Repository에 구현하는 것은 부적절



"간단하게 바꿀 수 있는 다른 방법"을 물어보면, 새로운 걸 알려준다! (이렇게 새로운 것을 배우는 방법!) 
----> 영어표현도 마찬가지

 
아래의 경우, npm install alum 
모듈 설치 여부 확인: 프로젝트에 필요한 패키지 또는 모듈이 설치되어 있는지 확인. 필요한 모듈이 설치되어 있지 않다면 해당 모듈을 설치

npm install alum

 

 

 

 

short url 생성 시에, localhost:3000/ 뒤에 위치에, 도메인을 제외하고 생성하도록할 건데, 이러한 로직이 구현되어있니?

그리고 이건 service, repo 중에 어디에 존재해야 하니? 

 


NestJs Exception Filters

 

service 파일 

 

NotFoundException으로 throw하면,

프론트에게 ‘NotFound’는 404이다.

 

근데 ‘NotFoundException’의

에러 메세지는 'Short URL 변환 횟수가 제한을 초과하였습니다’이니, 변경해야 한다.

 

 

controller 

 

잘려서 아래와 같이 다시

 

import { ExceptionFilter, Catch, NotFoundException, ArgumentsHost, HttpStatus } from '@nestjs/common';
import { Response } from 'express';

@Catch(NotFoundException)
export class NotFoundExceptionFilter implements ExceptionFilter {
  catch(exception: NotFoundException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus() || HttpStatus.NOT_FOUND;

    response.status(status).json({
      statusCode: status,
      message: exception.message,
    });
  }
}

잘려서 아래와 같이 다시

 

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { NotFoundExceptionFilter } from './exception-filters/not-found-exception.filter';

@Module({
  providers: [
    {
      provide: APP_FILTER,
      useClass: NotFoundExceptionFilter,
    },
  ],
})
export class AppModule {}


repository  

service파일에서 바로 데이터베이스에 저장하는 (repository사용하지 않고)

 

5일 차인 내일은, service 에서 repository 로 나누는 것을 해보아야겠다. 


 DTO(Data Transfer Object)를 사용하지 않는다면, 직접 엔티티를 사용하여 데이터를 저장하고 가져올 것 

 

 

내가 쓴 코드랑 비교하기 어려워서, 

 

코드를 제대로 알고 싶다면, "내 테이블 이름은 000 야, 여기에 맞게 다시 짜줘 " 하면, 
비교 분석할 필요가 없다.