Controller, Service, Repository

유석현(SeokHyun Yu)·2022년 12월 7일
0

Node.js

목록 보기
18/29
post-thumbnail

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";

const tweetController = express.Router();

// 전체 조회
tweetController.get("/", tweetService.getTweets);

// 상세 조회
tweetController.get("/:id", tweetService.getTweet);

// 트윗 생성
tweetController.post("/", tweetService.createTweet);

// 트윗 수정
tweetController.put("/:id", tweetService.updateTweet);

// 트윗 삭제
tweetController.delete("/:id", tweetService.deleteTweet);

export default tweetController;

Service

import * as tweetRepository from "./tweet.repository.js";

// 전체 조회
export const getTweets = async (req, res) => {
    const { username } = req.query;
    const tempTweets = username
        ? await tweetRepository.getAllTweetsByUsername(username)
        : await tweetRepository.getAllTweets();

    res.status(200).json(tempTweets);
};

// 상세 조회
export const getTweet = async (req, res) => {
    const { id } = req.params;
    const tweet = await tweetRepository.getTweetById(id);

    if (tweet) {
        res.status(200).json(tweet);
    } else {
        res.status(404).json({ status: 404, message: `id ${id} NOT FOUND` });
    }
};

// 트윗 생성
export const createTweet = async (req, res) => {
    await tweetRepository.createTweet(req.body);

    res.sendStatus(201);
};

// 트윗 수정
export const updateTweet = async (req, res) => {
    const { id } = req.params;
    const { text } = req.body;
    const tweet = await tweetRepository.updateTweet(id, text);

    if (tweet) {
        tweet.text = text;

        res.status(200).json(tweet);
    } else {
        res.status(404).json({ status: 404, message: `id ${id} NOT FOUND` });
    }
};

// 트윗 삭제
export const deleteTweet = async (req, res) => {
    const { id } = req.params;
    const deleteResult = await tweetRepository.deleteTweet(id);

    if (deleteResult) {
        res.sendStatus(204);
    } else {
        res.status(404).json({ status: 404, message: `id ${id} NOT FOUND` });
    }
};

Repository

let tweets = [
    {
        id: 1,
        createdAt: new Date().toLocaleString(),
        name: "SeokHyun Yu",
        username: "ysh",
        text: "Hello",
    },
];

export const getAllTweets = async () => {
    return tweets;
};

export const getAllTweetsByUsername = async (username) => {
    return tweets.filter((tweet) => tweet.username === username);
};

export const getTweetById = async (id) => {
    return tweets.find((tweet) => `${tweet.id}` === id);
};

export const createTweet = async ({ name, username, text }) => {
    const newTweet = {
        id: (tweets[0]?.id || 0) + 1,
        createdAt: Date.now().toLocaleString(),
        name,
        username,
        text,
    };

    tweets = [newTweet, ...tweets];

    return tweets;
};

export const updateTweet = async (id, text) => {
    const tweet = tweets.find((tweet) => `${tweet.id}` === id);

    if (tweet) {
        tweet.text = text;
    }

    return tweet;
};

export const deleteTweet = async (id) => {
    const prevLength = tweets.length;

    tweets = tweets.filter((tweet) => `${tweet.id}` !== id);

    return prevLength !== tweets.length;
};

GET: http://localhost:8000/tweet (200)


GET: http://localhost:8000/tweet?username=ysh (200)


GET: http://localhost:8000/tweet/1 (200)


POST: http://localhost:8000/tweet (201)


PUT: http://localhost:8000/tweet/1 (200)


DELETE: http://localhost:8000/tweet/1 (204)

profile
Backend Engineer

0개의 댓글