Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[6주차] 기본 과제 제출 #16

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions 6th-week-task/advanced/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
node_modules
.env
dist
.vscode
.DS_Store
6 changes: 6 additions & 0 deletions 6th-week-task/advanced/nodemon.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"watch": ["src", ".env"],
"ext": "js,ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node --transpile-only ./src/index.ts"
}
21 changes: 21 additions & 0 deletions 6th-week-task/advanced/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "seminar3",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "nodemon",
"build": "tsc && node dist"
},
"dependencies": {
"@prisma/client": "^4.6.0",
"express": "^4.18.2",
"prisma": "^4.6.0",
"typescript-rest": "^3.0.4"
},
"devDependencies": {
"@types/express": "^4.17.14",
"@types/node": "^18.11.0",
"nodemon": "^2.0.20"
}
}
40 changes: 40 additions & 0 deletions 6th-week-task/advanced/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
generator client {
provider = "prisma-client-js"
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model Content {
id Int @id @default(autoincrement())
contentName String? @db.VarChar(100)
Episode Episode[]
LikedContent LikedContent[]
}

model Episode {
id Int @id @default(autoincrement())
contentID Int
episodeID Int
description String? @db.VarChar(500)
runningTime Int
Content Content @relation(fields: [contentID], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "episode_content_id_fk")
}

model User {
id Int @id @default(autoincrement())
username String @db.VarChar(100)
email String @db.VarChar(200)
age Int
LikedContent LikedContent[]
}

model LikedContent {
id Int @id @default(autoincrement())
userID Int
contentID Int
Content Content @relation(fields: [contentID], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "likedcontent_content_id_fk")
User User @relation(fields: [userID], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "likedcontent_user_id_fk")
}
77 changes: 77 additions & 0 deletions 6th-week-task/advanced/src/controller/contentControll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { Request, Response } from "express";
import { contentService } from "../service";

//* content 전체 조회

const getAllContents = async (req: Request, res: Response) => {
const data = await contentService.getAllContents();
if (!data){
return res.status(204).json({status: 200, message: "No contents available"});
}
return res.status(200).json({ status: 200, message: "Contents 전체 조회 성공", data });
};

//* content 조회
const getContent = async (req: Request, res: Response) => {
const { contentID } = req.params;
const { episodeID } = req.query;
const data = await contentService.getContent(+contentID, +(episodeID as string));

if (!data){
return res.status(404).json({status: 404, message: "Can't get content"});
}

return res.status(200).json({status: 200, message: `${data[0].contentName} 조회 성공`, data});

};

//* liked content 생성

const createLikedContent = async (req: Request, res: Response) => {
const { userID } = req.params;
const { contentID } = req.body;

if (!userID) {
return res.status(400).json({status:400, message: "userID do not exist"});
}

if (!contentID) {
return res.status(400).json({status:400, message: "contentID missing"});
}

const data = await contentService.createLikedContent(+userID, +contentID);

return res.status(200).json({status: 200, message: `liked ${contentID}`, data});
}

//* liked content 조회

const getLikedContent = async (req: Request, res: Response) => {
const { userID } = req.params;
const data = await contentService.getLikedContents(+userID);

if (!data){
return res.status(404).json({status: 404, message: "Can't get liked contents"});
}

return res.status(200).json({status: 200, message: `liked contents 조회 성공`, data});

};

//* liked content 삭제

const deleteLikedContent = async (req: Request, res: Response) => {
const { likedContentID } = req.params;
const data = await contentService.deleteLikedContent(+likedContentID);

return res.status(200).json({status: 200, message: `liked contents ${likedContentID} 삭제 성공`});

};

export default{
getAllContents,
getContent,
createLikedContent,
getLikedContent,
deleteLikedContent
}
4 changes: 4 additions & 0 deletions 6th-week-task/advanced/src/controller/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import contentControll from "./contentControll";
import userController from "./userController";

export { contentControll, userController };
70 changes: 70 additions & 0 deletions 6th-week-task/advanced/src/controller/userController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { Request, Response } from "express";
import { userService } from "../service";

//* 유저 생성

const createUser = async (req: Request, res: Response) => {
const { username, email, age } = req.body; // json data의 key와 생성할 변수명이 같을 때
if (!username || !email || !age) {
return res.status(400).json({ status: 400, message: "유저 생성 실패" });
}

const data = await userService.createUser(username, email, age);

if (!data){
return res.status(400).json({ status: 400, message: "유저 생성 실패" });
}
return res.status(200).json({ status: 200, message: "유저 생성 성공", data });
};

//* 유저 전체 조회

const getAllUser = async (req: Request, res: Response) => {
const data = await userService.getAllUser();
return res.status(200).json({ status: 200, message: "유저 전체 조회 성공", data });
};


//* 유저 정보 업데이트

const updateUser = async (req: Request, res: Response) => {
const { username } = req.body;
const { userId } = req.params;
if (!username) return res.status(400).json({ status: 400, message: "유저 정보 업데이트 실패" });

const updateUser = await userService.updateUser(+userId, username);
return res.status(200).json({ status: 200, message: "유저 정보 업데이트 성공", updateUser });

};


//* 유저 삭제

const deleteUser = async (req: Request, res: Response) => {
const { userId } = req.params;
await userService.deleteUser(+userId);
return res.status(200).json({ status: 200, message: "유저 삭제 성공"});

};

//* 유저 조회
const getUserById = async (req: Request, res: Response) => {
const { userId } = req.params;

const data = await userService.getUserById(+userId);

if (!data) {
return res.status(404).json({ status: 404, message: "NOT_FOUND" });
}
return res.status(200).json({ status: 200, message: "유저 조회 성공", data });
};

const userController = {
createUser,
getAllUser,
getUserById,
updateUser,
deleteUser
};

export default userController;
54 changes: 54 additions & 0 deletions 6th-week-task/advanced/src/data/content.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
{
"1": {
"title": "수리남",
"contentId": 1,
"actor": ["하정우", "황정민", "박혜수"],
"genre": ["범죄 시리즈", "한국 드라마", "스릴러 시리즈"],
"addition": {
"year": 2022,
"age": 18,
"episodeNum": 6
},
"time": {
"runningTime": 62,
"watchTime": 57
},
"image": "",
"1": {
"episodeId": 1,
"contents": "새로운 사업을 위해 공장을 알아보러 간 강민구. 하지만 졸지에 세력 싸움에 휘말리고 만다. 이때, 현지의 목사가 인구를 돕겠다고 나선다.",
"runningTime": 62,
"image": ""
},
"2": {
"episodeId": 2,
"contents": "변호사 선임을 망설이던 인구는 비밀 요원의 제안을 고려한다. 이후 인구는 전직 보디가드를 속이기 위해 감옥 내 영향력을 키우고자 하는데.",
"runningTime": 60,
"image": ""
},
"3": {
"episodeId": 3,
"contents": "전요환과 구상만 사이의 파트너십을 중재하는 인구. 요환은 거래에 동의하기에 앞서 철저하게 조사를 진행한다.",
"runningTime": 66,
"image": ""
},
"4": {
"episodeId": 4,
"contents": "국경에서 충돌이 발생하고, 요환 측근들 사이의 기류가 변화한다. 상만은 한국으로 향하는 다른 경로를 제안한다.",
"runningTime": 51,
"image": ""
},
"5": {
"episodeId": 5,
"contents": "경로를 변경하도록 요환을 설득하는 데 실해판 인구. 결국 임기응변을 발휘해 새로운 계획을 설계한다. 데이빗 홀리오 박은 패키지 전달을 준비한다.",
"runningTime": 68,
"image": ""
},
"6": {
"episodeId": 6,
"contents": "요환의 갑작스러운 돌발 행동으로 인구의 신변을 보호하기 위한 계획에 차질이 생긴다. 요환의 마약제국을 무너뜨리기 위한 작전이 시작되고, 그 사이 이상준이 공항에 도착한다.",
"runningTime": 62,
"image": ""
}
}
}
18 changes: 18 additions & 0 deletions 6th-week-task/advanced/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import express, { application, NextFunction, Request, Response } from 'express';
const app = express();
const PORT = 8000;

app.use(express.json());
app.use("/api", require("./router"));

app.get("/", (req: Request, res: Response, next: NextFunction) => {
res.send("main")
});

app.listen(PORT, () => {
console.log(`
#############################################
🛡️ Server listening on port: ${PORT} 🛡️
#############################################
`);
});
21 changes: 21 additions & 0 deletions 6th-week-task/advanced/src/router/contentRouter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import express, { Router } from 'express';
import { contentControll } from '../controller';

const router: Router = express.Router();

//* 전체 content 조회 ( GET api/content )
router.get("/", contentControll.getAllContents);

//* content 조회 GET api/content/:contentID
router.get('/:contentID', contentControll.getContent);

//* liked content 생성 POST api/content/like/:userID
router.post("/like/:userID", contentControll.createLikedContent);

//* liked content 조회 GET api/content/like/:userID
router.get("/like/:userID", contentControll.getLikedContent);

//* liked content 삭제 DELETE api/content/like/:likedContentID
router.delete("/like/:likedContentID", contentControll.deleteLikedContent);

export default router;
10 changes: 10 additions & 0 deletions 6th-week-task/advanced/src/router/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import express, { Router } from "express";
import contentRouter from "./contentRouter";
import userRouter from "./userRouter";

const router: Router = express.Router();

router.use("/content", contentRouter);
router.use("/user", userRouter);

module.exports = router;
20 changes: 20 additions & 0 deletions 6th-week-task/advanced/src/router/userRouter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Router } from "express";
import { userController } from "../controller";

const router: Router = Router();

router.get("/:userId", userController.getUserById);

//* 유저 생성 ( POST api/user )
router.post("/", userController.createUser);

//* 전체 유저 조회 ( GET api/user )
router.get("/", userController.getAllUser);

//* 유저 정보 업데이트 ( PATCH api/user/:userId )
router.patch("/:userId", userController.updateUser);

//* 유저 삭제 ( DELETE api/user/:userId )
router.delete("/:userId", userController.deleteUser);

export default router;
Loading