Controller란 클라이언트(HTTP 요청 등)로부터 들어오는 요청을 받아 해당 요청을 처리할 Service로 전달하고, 그 결과를 클라이언트에 응답하는 역할을 한다.
Node.js에서 아래와 같이 Controller를 만들어본 바가 있다.
const Hashtag = require("../models/hashtag");
const Post = require("../models/post");
exports.afterUploadImage = (req, res) => {
console.log(req.file);
const originalUrl = req.file.location;
const url = originalUrl.replace(/\/original\//, '/thumb/');
res.json({ url, originalUrl });
}
exports.uploadPost = async (req ,res ,next) => {
try {
const post = await Post.create({
content: req.body.content,
img: req.body.url,
UserId: req.user.id
});
const hashtags = req.body.content.match(/#[^\s#]*/g);
if(hashtags) {
const result = await Promise.all(hashtags.map((tag) => {
return Hashtag.findOrCreate({
where: { title: tag.slice(1).toLowerCase() }
});
}));
console.log('result', result);
await post.addHashtags(result.map(r => r[0]));
}
res.redirect('/');
} catch (error) {
console.error(error);
next(error);
}
}
controllers 라는 폴더를 임의로 만들고, 그 안에 'post.js'를 만든 후 로직에서 exports 하는 하나의 컨트롤러를 만드는 방식이었다.
NestJS의 Controller 만들기
1. nest g resource
명령어창에 'nest g resource' 를 입력한다.
2. 생성할 컨트롤러 이름 작성
What name would you like to use for this resource (plural, e.g., "users")?
라고 묻는다면 본인이 원하는 컨트롤러 이름으로 작성한다.
참고로 해당 이름이 곧 컨트롤러의 폴더이름이 된다.
3. 트랜스포트 레이어 선택
What transport layer do you user?
REST API, Graph QL .. 등등의 선택지 중 선택하면 된다.
4. generate CRUD entry points 생성 여부
기본적으로 생성되는 CRUD entry points를 선택한다.
완료되면 위와 같이 src 폴더내에 posts 라는 폴더가 생성되며 기본적으로 생성되는 모듈들을 볼 수 있다.
import { Controller, Get } from '@nestjs/common';
import { PostsService } from './posts.service';
interface Post {
author: string;
title: string;
content: string;
likeCount: number;
commentCount: number;
}
@Controller('posts')
export class PostsController {
constructor(private readonly postsService: PostsService) {}
@Get()
getPost(): Post {
return {
author: 'tester',
title: '타이틀',
content: '컨텐츠',
likeCount: 999,
commentCount: 111,
};
}
}
posts.controller.ts 에 위와 같이 코드를 작성한 후
'localhost:3000/posts' 경로로 접속하면, getPost의 값들이 가져오는 것을 볼 수 있다.
'NestJS' 카테고리의 다른 글
Docker 이론 (0) | 2025.02.24 |
---|---|
NestJS - 제어의 역전과 의존성 주입 (0) | 2025.02.20 |
NestJS - 서비스 및 컨트롤러 (0) | 2025.02.20 |
NestJS - Postman 사용하기 (0) | 2025.02.19 |
NestJS 라이프사이클 (0) | 2025.02.19 |