constructor(private readonly postsService: PostsService) {}
Controller를 생성하면 위와같은 코드 한 줄이 생성된다.
postsServie: PostsService;
constructor(private readonly postsService: PostServcie){
this.postService = postService;
}
위 두 코드는 같은 개념이라 생각하면 된다.
Controller는 정확히 필요한 메서드에 HTTP 요청을 매핑해주는 것이 Controller의 역할
import { Body, Controller, Delete, Get, Param, Post, Put } from "@nestjs/common"
import { PostModel, PostsService } from "./posts.service"
//post 를 작성하게 되면, url의 path를 설정할 수 있다.
//모든 path의 prefix(접두어)를 만들 수 있다.
@Controller("posts")
export class PostsController {
constructor(private readonly postsService: PostsService) {}
//@Get() 데코레이터 안에도 직접 path 경로를 설정할 수 있다.
//http://localhost:3000/post/post를 입력해야 접근 가능해다
//모든 포스트를 가져온다
@Get()
getPosts(): PostModel[] {
return this.postsService.getAllPosts()
}
//특정 아이디에 해당하는 post를 가져온다
//@Param()안에 값을 집어넣게 되면, 특정 파라미터 id를 연결할 수 있다.
@Get(":id")
getPost(@Param("id") id: string) {
return this.postsService.getPostById(+id)
}
//Post를 생성한다.
//Post 호출시 저장된 body에서 값을 불러올 때는 @Body 데코레이터를 사용한다.
@Post()
postPosts(
@Body("author") author: string,
@Body("title") title: string,
@Body("content") content: string
) {
return this.postsService.createPost(author, title, content)
}
// id에 해당하는 데이터를 수정한다.
//받을 body의 값을 ?를 붙여주게 되면 null 값이 될 수 있다.
@Put(":id")
putPost(
@Param("id") id: string,
@Body("author") author?: string,
@Body("title") title?: string,
@Body("content") content?: string
) {
return this.postsService.updatePost(+id, author, title, content)
}
@Delete(":id")
deletePost(@Param("id") id: string) {
return this.postsService.deletePost(+id)
}
}
import { Injectable, NotFoundException } from "@nestjs/common"
/**
* author : string;
* title : string;
* content : string;
* likeCount : number;
* commentCount : number;
*/
export interface Post {
author: string
title: string
content: string
likeCount: number
commentCount: number
}
export 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: 1000000,
commentCount: 999999,
},
{
id: 2,
author: "newjeans_official",
title: "뉴진스 혜린",
content: "노래 연습 하고 있는 혜린",
likeCount: 1000000,
commentCount: 999999,
},
{
id: 3,
author: "blackpink_official",
title: "블랙핑크 리사",
content: "랩하는 리사",
likeCount: 1000000,
commentCount: 999999,
},
]
@Injectable()
export class PostsService {
getAllPosts(): PostModel[] {
return posts
}
getPostById(id: number) {
const post = posts.find((post) => post.id === +id)
if (!post) {
throw new NotFoundException() //post가 찾으려는 Id가 없는 경우 예외처리
}
return post
}
createPost(author: string, title: string, content: string) {
const post: PostModel = {
id: posts[posts.length - 1].id + 1,
author: author,
title,
content,
likeCount: 0,
commentCount: 0,
}
posts = [...posts, post]
return posts
}
updatePost(postId: number, author: string, title: string, content: string) {
const post = posts.find((post) => post.id === postId)
if (!post) {
throw new NotFoundException()
}
if (author) {
post.author = author
}
if (title) {
post.title = title
}
if (content) {
post.content = content
}
//현재 있는 게시물의 id가 같으면, 현재 수정하려고 저장한 값을 저장한다.
posts = posts.map((prevPost) => (prevPost.id === postId ? post : prevPost))
return posts
}
deletePost(postId: number) {
const post = posts.find((post) => post.id === postId)
if (!post) {
throw new NotFoundException() //post가 찾으려는 Id가 없는 경우 예외처리
}
posts = posts.filter((post) => post.id !== postId)
return postId
}
}
export interface Post {
author: string
title: string
content: string
likeCount: number
commentCount: number
}
export interface PostModel {
id: number
author: string
title: string
content: string
likeCount: number
commentCount: number
}
interface로 적용한 데이터 형식을 Service로 옮기게 되면서, Controller에서는 값을 찾을 수 없게 된다.
export 키워드를 활용해서 Controller에서 데이터 형식을 불러 올 수 있게 만들어준다.
import { PostModel, PostsService } from "./posts.service"
.
.
.
@Get()
getPosts(): PostModel[] {
return this.postsService.getAllPosts()
}
Controller에서는 위와 같이 post.service에서 생성하게된 interface를 불러와서 데이터 형식을 사용한다.
모든 내용은 강의 [코드팩토리][초급] NestJS REST API 백엔드 완전 정복 마스터 클래스를 수강하며 정리하는 내용들을 올린 글이다.