라우팅 작업을 하다보면 늘어나기 마련이다. 한 곳에 코드 양이 너무 많이 있으면 관리하기가 힘들어진다. 이 때 같은 라우터끼리 분리해서 관리하면 관리가 효율적이다.
라우터 분리를 해보자.
너무 길어서 코드 관리가 쉽지 않다.
import express from "express";
import cors from "cors";
import helmet from "helmet";
const app = express();
// 미들웨어
app.use(
cors({
origin: "*",
})
);
app.use(helmet());
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: "700mb" }));
// GET Method
// 유저 정보가져오기
// 성공 status 200
app.get("/users", (req, res) => {
res.status(200).json({ users });
});
// POST Method
// 유저생성
// 성공 status 201
app.post("/users", (req, res) => {
const { name, age } = req.body;
console.log(req.body);
users.push({
id: new Date().getTime(),
name,
age,
});
res.status(201).json({ users });
});
// PATCH Method
// 유저 수정
// 성공 status 204
// request.params.id
app.patch("/users/:id", (req, res) => {
const { id } = req.params;
const { name, age } = req.body;
console.log(req.params);
const targetUserIdx = users.findIndex((user) => user.id === Number(id));
users[targetUserIdx] = {
id: users[targetUserIdx].id,
name: name ?? users[targetUserIdx].name,
age: age ?? users[targetUserIdx].age,
};
res.status(204).json({});
});
// DELETE Method
// 유저 삭제
// 성공 status 204
app.delete("/users/:id", (req, res) => {
const { id } = req.params;
const deletedUsers = users.filter((user) => user.id !== Number(id));
users = deletedUsers;
res.status(204).json({});
});
// req : 요청 => Request
// res : 응답 => Response
app.get("/", (req, res) => {
res.send("Express");
});
app.listen(8000, () => {
console.log("서버가 시작되었습니다.");
});
import express from "express";
import cors from "cors";
import helmet from "helmet";
import Controllers from "./controllers";
const app = express();
// 미들웨어
app.use(
cors({
origin: "*",
})
);
app.use(helmet());
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: "700mb" }));
Controllers.forEach((controller) => {
app.use(controller.path, controller.router);
});
확실히 짧아진 것을 볼 수 있다.
import userController from "./users";
import userPosts from "./posts";
export default [userController, userPosts];
// 클래스를 사용한 방법
import { Router } from "express";
class UserController {
router;
path = "/users";
users = [
{
id: 1,
name: "junseok",
age: 10,
},
];
constructor() {
this.router = Router();
this.init();
}
init() {
this.router.get("/", this.getUsers.bind(this));
this.router.get("/detail/:id", this.getUser.bind(this));
this.router.post("/", this.createUser.bind(this));
this.router.patch("/:id", this.updateUser.bind(this));
this.router.delete("/:id", this.deleteUser.bind(this));
}
getUsers(req, res) {
res.status(200).json({ users: this.users });
}
getUser(req, res) {
const { id } = req.params;
const user = this.users.find((user) => user.id === Number(id));
res.status(200).json({ user });
}
createUser(req, res) {
const { name, age } = req.body;
this.users.push({
id: new Date().getTime(),
name,
age,
});
res.status(201).json({ users: this.users });
}
updateUser(req, res) {
const { id } = req.params;
const { age, name } = req.body;
const targetUserIdx = this.users.findIndex((user) => user.id === Number(id));
this.users[targetUserIdx] = {
id: this.users[targetUserIdx].id,
name: name ?? this.users[targetUserIdx].name,
age: age ?? this.users[targetUserIdx].age,
};
res.status(204).json({});
}
deleteUser(req, res) {
const { id } = req.params;
const deletedUsers = this.users.filter((user) => user.id !== Number(id));
this.users = deletedUsers;
res.status(204).json({});
}
}
const userController = new UserController();
export default userController;
// class를 쓰지 않은 방법
import { Router } from "express";
const router = Router();
const path = "/posts";
const posts = [
{
id: 1,
title: "ㄴㅇㅁㄴㅇ",
content: "안녕하세요, 프론트엔드 개발자가 백엔드도 배웁니다.",
},
];
const getPosts = (req, res) => {
res.status(200).json({ posts });
};
const createPost = (req, res) => {
const { title, content } = req.body;
posts.push({
id: new Date().getTime(),
title,
content,
});
res.status(201).json({ posts });
};
router.get("/", getPosts);
router.post("/", createPost);
export default { router, path };