JS/Nest.js

[Nest JS] 게시글생성 db / typeOrm 3.0 issued 해결 / @EntityRepository 해결

Mini_96 2024. 8. 17. 23:41

* service

async createBoard(createBoardDto : CreateBoardDto): Promise<Board>{
    const {title,description} = createBoardDto;

    //db생성시 .create 이용해야
    const board = this.boardRepository.create({
      // id : uuid(),  //자동으로 유니크한 값을 넣어줌
      title : title,
      description : description,
      status : BoardStatus.PUBLIC
    })

    await this.boardRepository.save(board);
    return board;
}

 

* controller

@Post()
@UsePipes(ValidationPipe)
createBoard(@Body() createBoardDto : CreateBoardDto) : Promise<Board> {
  return this.boardsService.createBoard(createBoardDto);
}

결과

 

* db 관련은 repository로 이동

controller에서 service 호출

service에서는 repository를 호출

@EntityRepository() //Board를 컨트롤하는 db임을 선언
export class BoardRepository extends Repository<Board>{
  async getBoardById(id): Promise <Board>{
    const found = await this.findOne(id);

    if(!found){
      throw new NotFoundException(`Can\`t find Board with id ${id}`);
    }
    return found;
  }

  async createBoard(createBoardDto : CreateBoardDto): Promise<Board>{
    const {title,description} = createBoardDto;

    //db생성시 .create 이용해야
    const board = this.create({
      // id : uuid(),  //자동으로 유니크한 값을 넣어줌
      title : title,
      description : description,
      status : BoardStatus.PUBLIC
    })

    await this.save(board);
    return board;
  }
}

 

*  typeOrm 3.0 issued

문제 : repository.create not found error

원인 : ?

해결 : 3.0으로 원복 && repository.ts에서 @entityrepository 대신 @ injectable 사용 && 생성자 명시

https://www.inflearn.com/community/questions/880715/%EB%A0%88%ED%8D%BC%EC%A7%80%ED%86%A0%EB%A6%AC-%EB%AC%B8%EC%A0%9C-%ED%95%B4%EA%B2%B0%ED%95%98%EC%8B%A0-%EB%B6%84-%EB%8F%84%EC%99%80%EC%A3%BC%EC%84%B8%EC%9A%94-%E3%85%A0%E3%85%A0

 

레퍼지토리 문제..해결하신 분 도와주세요 ㅠㅠ.. - 인프런 | 커뮤니티 질문&답변

누구나 함께하는 인프런 커뮤니티. 모르면 묻고, 해답을 찾아보세요.

www.inflearn.com

고침
get도 잘됨

 

* 인프런 복붙

boards.module.ts 파일의 providers에 BoardRepository를 추가해서
providers: [BoardsService, BoardRepository],
이렇게 한번 만들어 보시겠어요?

혹시 이렇게 해도 안되면,
1. typeORM 버전을 낮춘 것은 아닌지, 낮춘 게 맞다면 package.json 파일에서, dependencies의 typeorm 부분을 "typeorm": "^0.3.17",

이렇게 바꾸시고 npm install typeorm @nestjs/typeorm --save 로 다시 설치한 뒤,

2. boards.entity.ts 파일에서
@EntityRepository(Board) 부분을 지우고, 아래와 같이 @Injectable() 데코레이터와 컨스트럭터를 추가해 주세요.

//@EntityRepository(Board)
@Injectable()
export class BoardRepository extends Repository<Board> {
    constructor(dataSource: DataSource) {
        super(Board, dataSource.createEntityManager());
    }
  1. board.service.ts 파일에서 클래스의 컨스트럭터 부분을 아래와 같이 수정해 보세요.
  2. export class BoardsService { constructor(private boardRepository: BoardRepository) {}
답글

1

2023. 09. 03. 16:55

그리고 마지막으로
4. getBoardById 함수가 쓰고 있는 findOne을 아래와 같이 바꿔야 합니다.

const found = await this.boardRepository.findOne({
            where: { id: id }
        });