코딩캠프/내일배움캠프

[ TIL ] 02.20(월) 69일차

고랑E 2023. 2. 20. 21:00
728x90

TypeORM

 

3. 서비스 코드를 데이터베이스 기반으로 변경

 

 

 

- board.service.ts 1차 - getArticles 함수 코드 바꾸기!

더보기
async getArticles() {
    return await this.articleRepository.find({
      where: { deletedAt: null },
      select: ['author', 'title', 'createdAt'],
    });
  }


- board.service.ts 2차 - getArticleById 함수 코드 바꾸기!

더보기
async getArticleById(id: number) {
    return await this.articleRepository.findOne({
      where: { id, deletedAt: null },
      select: ['author', 'title', 'content', 'createdAt', 'updatedAt'],
    });
  }


- board.service.ts 3차 - createArticle 함수 코드 바꾸기!

더보기
createArticle(title: string, content: string, password: number) {
    this.articleRepository.insert({
      author: 'test',
      title,
      content,
      password: password.toString(),
    });
  }


- board.service.ts 4차 - updateArticle 함수 코드 바꾸기!

더보기
async updateArticle(
    id: number,
    title: string,
    content: string,
    password: number,
  ) {
    const article = await this.articleRepository.findOne({
      where: { id, deletedAt: null },
      select: ['password'],
    });

    if (_.isNil(article)) {
      throw new NotFoundException(`Article not found. id: ${id}`);
    }
    if (article.password !== password.toString()) {
      throw new UnauthorizedException(`Password is not corrected. id: ${id}`);
    }

    this.articleRepository.update(id, { title, content });
  }


- board.service.ts 5차 - deleteArticle 함수 코드 바꾸기!

더보기
async deleteArticle(id: number, password: number) {
    const article = await this.articleRepository.findOne({
      where: { id, deletedAt: null },
      select: ['password'],
    });

    if (_.isNil(article)) {
      throw new NotFoundException(`Article not found. id: ${id}`);
    }
    if (article.password !== password.toString()) {
      throw new UnauthorizedException(`Password is not corrected. id: ${id}`);
    }

    this.articleRepository.softDelete(id);
  }

 

 

- board.service.ts 최종 | updateArticledeleteArticle 의 중복 된 코드를 헬퍼 함수로 관리하기!

async updateArticle(
    id: number,
    title: string,
    content: string,
    password: number,
  ) {
    await this.verifyPassword(id, password);
    this.articleRepository.update(id, { title, content });
  }

  async deleteArticle(id: number, password: number) {
    await this.verifyPassword(id, password);
    this.articleRepository.softDelete(id);
  }

  private async verifyPassword(id: number, password: number) {
    const article = await this.articleRepository.findOne({
      where: { id, deletedAt: null },
      select: ['password'],
    });

    if (_.isNil(article)) {
      throw new NotFoundException(`Article not found. id: ${id}`);
    }
    if (article.password !== password.toString()) {
      throw new UnauthorizedException(`Password is not corrected. id: ${id}`);
    }
  }

private 함수로 외부에서 해당 함수를 호출할 수 없도록 해준다

수정과 삭제의 경우 민감한 정보(비밀번호)를 다루기 때문에 private 함수를 사용

 

 

 

4. 컨트롤러 코드 수정하기

서비스에서 데이터베이스 기반의 코드를 변경하면서

async-await 함수로 변경했다

따라서 컨트롤러도 같이 수정

 

board.controller.ts

import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
} from '@nestjs/common';
import { BoardService } from './board.service';
import { CreateArticleDto } from './dto/create-article.dto';
import { DeleteArticleDto } from './dto/delete-article.dto';
import { UpdateArticleDto } from './dto/update-article.dto';

@Controller('board')
export class BoardController {
  // 서비스 주입
  constructor(private readonly boardService: BoardService) {}

  //전체 게시글 가져오기
  @Get('/articles')
  async getArticles() {
    return await this.boardService.getArticles();
  }

  //게시글 상세보기
  @Get('/articles/:id')
  async getArticleById(@Param('id') articleId: number) {
    return await this.boardService.getArticleById(articleId);
  }

  // 게시글 작성
  @Post('/articles')
  createArticle(@Body() data: CreateArticleDto) {
    return this.boardService.createArticle(
      data.title,
      data.content,
      data.password,
    );
  }

  // 게시글 수정
  @Put('/articles/:id')
  async updateArticle(
    @Param('id') articleId: number,
    @Body() data: UpdateArticleDto,
  ) {
    return await this.boardService.updateArticle(
      articleId,
      data.title,
      data.content,
      data.password,
    );
  }

  // 게시글 삭제
  @Delete('/articles/:id')
  async deleteArticle(
    @Param('id') articleId: number,
    @Body() data: DeleteArticleDto,
  ) {
    return await this.boardService.deleteArticle(articleId, data.password);
  }
}

 

5. 테스트

 

테스트 도중 에러가 발생해서 해결했다..

 

 

ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '비밀번호';

위 명령어가 안되서 다음 명령어로 

mysql 패스워드 플러그인을 변경했다.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '비밀번호';

그리고 잘 바뀌었는지 확인

SELECT Host,User,plugin,authentication_string FROM mysql.user;

 

다시 테스트 하려는데 board 테이블을 생성안해서 오류가...

끝~~