2. REST API

수원 개발자·2023년 11월 23일
0

NestJS

목록 보기
4/15

[GET] http://localhost:3000/posts

다수의 post를 가져온다.

[GET] http://localhost:3000/posts/11

이 경우에는 11이라는 ID를 가지고 있는 Post를 하나 가져온다.

[POST] http://localhost:3000/posts

새로운 Post를 생성한다.

[PATCT] http://localhost:3000/posts/8

8이라는 ID를 가지고 있는 Post를 부분 변경한다.

[PUT] http://localhost:3000/posts/8

8이라는 ID를 가지고 있는 Post를 변경하거나 생성한다.

[DELETE] http://localhost:3000/posts/3

3이라는 ID를 가지고 있는 Post를 삭제한다.

이런 식으로 url을 구성해서 작업을 진행 할 것이다.

interface PostModel {
  id: number;
  author: string;
  title: string;
  content: string;
  likeCount: number;
  commentCount: number;
}

let posts: PostModel[] = [
  {
    id: 1,
    author: "newjeans_official",
    title: "뉴진스 민지",
    content: "메이크업 고치고 있는 민지",
    likeCount: 100000000,
    commentCount: 9999
  },

  {
    id: 2,
    author: "newjeans_official",
    title: "뉴진스 해린",
    content: "노래 연습하는 해린",
    likeCount: 100000000,
    commentCount: 9999
  },

  {
    id: 3,
    author: "blackpink_official",
    title: "블랙핑크 로제",
    content: "릴스 찍고 있는 로제",
    likeCount: 100000000,
    commentCount: 9999
  }
];

데이터를 받는 변수를 설정해주고 인터페이스에 id를 추가해주고 Model로 명칭을 바꿨다.

@Controller("posts")
export class PostsController {
  constructor(private readonly postsService: PostsService) {
  }

  // 1) GET /posts
  // 모든 post를 가져온다

  @Get()
  getPosts() {
    return posts;
}

그리고 이렇게 모든 posts를 가져오도록 컨트롤러를 구성했다.

// 2) GET /posts/:id
// id에 해당되는 post를 가져온다

  @Get(':id')
  getPost(@Param('id') id: string) {
    return posts.find((post) => post.id === +id);
  }

param id를 사용해서 /posts/:id도 구성해줬다.
@Get(':id')에서 :id 부분에 /posts/123과 같이 숫자인 ID가 들어온다면, 이것은 id라는 변수에 문자열 형태로 전달된다. 그래서 이 코드에서의 id 변수는 게시물의 ID를 나타내는 값으로 사용될 것이다.

return posts.find((post) => post.id === +id);는 posts 배열에서 해당 id와 일치하는 게시물을 찾는 역할을 한다. 여기서 post는 배열 내 개별 요소를 가리키는 변수이며 이 코드는 id와 일치하는 게시물 객체를 찾아 반환하는 데 사용된다.

하지만 이 때는 :id가 해당되는 값이 없으면 undefined를 던져준다.
그렇게 하지 않고 에러 메세지를 띄워주기 위해 조건문을 사용해줬다.

@Get(':id')
  getPost(@Param('id') id: string) {
    const post = posts.find((post) => post.id === +id);

    if (!post) {
      throw new NotFoundException();
    }

    return post;
  }

이렇게 처리하면 잘 작동한다.

// 3) POST /posts
  // post를 생성한다

  @Post()
  postPosts(
    @Body('author') author: string,
    @Body('title') title: string,
    @Body('content') content: string,
  ) {
    const post = {
      id: posts[posts.length - 1].id + 1,
      author,
      title,
      content,
      likeCount: 0,
      commentCount: 0,
    };

    posts = [...posts, post];

    return post;
  }

@Post를 사용해서 post 요청을 하도록 했다.
author, title, content를 받고 이를 통해 post를 생성했다.

// 4) PUT /posts/:id
  // id에 해당되는 post를 변경한다
  @Put(':id')
  putPost(
    @Param('id') id: string,
    @Param('author') author?: string,
    @Param('title') title?: string,
    @Param('content') content?: string,
  ) {
    const post = posts.find((post) => post.id === +id);

    if (!post) {
      throw new NotFoundException();
    }

    if (author) {
      post.author = author;
    }

    if (title) {
      post.title = title;
    }

    if (content) {
      post.content = content;
    }

    posts = posts.map((prevPost) => (prevPost.id === +id ? post : prevPost));

    return post;
  }

수정을 할 수 있는 put 요청을 해보았다.
author, title, content를 각자 수정 처리 할 수 있도록 로직을 짰고 수정을 하면 적용이 되게끔 코드를 짰다.

// 5) DELETE /posts/:id
  // id에 해당되는 post를 삭제한다
  @Delete(':id')
  deletePost(
    @Param('id') id: string,
  ){
    const post = posts.find((post) => post.id === +id);

    if (!post) {
      throw new NotFoundException();
    }

    posts = posts.filter((post) => post.id !== +id);

    return id;
  }
}

마지막으로 id에 해당되는 post를 삭제할 수 있게 delete를 했다.
여기서 posts.filter(post => post.id !== +id);는 posts 배열에서 특정 ID와 일치하지 않는 게시물들만 남기는 것이다. 즉, 해당 ID에 해당하는 게시물을 삭제하는 것이다.

0개의 댓글

관련 채용 정보