app.js
import express from "express";
import helmet from "helmet";
import morgan from "morgan";
import cors from "cors";
import tweetController from "./tweet/tweet.controller.js";
const app = express();
app.use(express.json());
app.use(morgan("dev"));
app.use(helmet());
app.use(cors());
app.use("/tweet", tweetController);
app.use((req, res, next) => {
res.sendStatus(404);
});
app.use((err, req, res, next) => {
res.sendStatus(500);
});
app.listen(8000);
Controller
import express from "express";
import * as tweetService from "./tweet.service.js";
import { body } from "express-validator";
import { validate } from "../middleware/validator.js";
const tweetController = express.Router();
const textValidator = [
body("text")
.trim()
.isLength({ min: 5 })
.withMessage("text를 최소 5 글자 이상 입력해주세요."),
validate,
];
tweetController.get("/", tweetService.getTweets);
tweetController.get("/:id", tweetService.getTweet);
tweetController.post("/", textValidator, tweetService.createTweet);
tweetController.put("/:id", textValidator, tweetService.updateTweet);
tweetController.delete("/:id", tweetService.deleteTweet);
export default tweetController;
validator.js
import { validationResult } from "express-validator";
export const validate = (req, res, next) => {
const errors = validationResult(req);
if (errors.isEmpty()) {
next();
} else {
res
.status(400)
.json({ error: errors.array().map((error) => ({ message: error.msg })) });
}
};
"text"
가 5글자 미만일 경우
"text"
가 5글자 이상일 경우
"text"
가 5글자 미만일 경우
"text"
가 5글자 이상일 경우