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주차] 기본/도전 과제 제출 #5

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
3 changes: 3 additions & 0 deletions seminar6/advanced/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
# Keep environment variables out of version control
.env
6 changes: 6 additions & 0 deletions seminar6/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"
}
26 changes: 26 additions & 0 deletions seminar6/advanced/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "seminar4",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "nodemon",
"build": "tsc && node dist"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.14",
"@types/express-validator": "^3.0.0",
"@types/jsonwebtoken": "^8.5.9",
"@types/node": "^18.11.9",
"nodemon": "^2.0.20"
},
"dependencies": {
"@prisma/client": "^4.5.0",
"bcryptjs": "^2.4.3",
"express": "^4.18.2",
"express-validator": "^6.14.2",
"jsonwebtoken": "^8.5.1",
"prisma": "^4.5.0"
}
}
43 changes: 43 additions & 0 deletions seminar6/advanced/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
generator client {
provider = "prisma-client-js"
}

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

model User {
id Int @id @default(autoincrement())
userName String
age Int?
email String? @db.VarChar(400)
password String @db.VarChar(400)
LikeContent LikeContent[]
}

model Content {
id Int @id(map: "content_pkey") @default(autoincrement())
contentName String? @db.VarChar(100)
genre String? @db.VarChar(100)
ageLimit Int?
episode Episode[]
likeContent LikeContent[]
}

model LikeContent {
id Int @id(map: "FavoriteContent_pkey") @default(autoincrement())
userId Int?
contentId Int?
content Content? @relation(fields: [contentId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "likecontent_content_id_fk")
user User? @relation(fields: [userId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "likecontent_user_id_fk")
}

model Episode {
id Int @id @default(autoincrement())
contentId Int?
episodeNumber Int?
runningTime Int?
description String? @db.VarChar(500)
content Content? @relation(fields: [contentId], references: [id], onDelete: NoAction, onUpdate: NoAction, map: "episode_content_id_fk")
}
3 changes: 3 additions & 0 deletions seminar6/advanced/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { default as message } from "./responseMessage";
export { default as statusCode } from "./statusCode";
export { default as tokenType } from "./tokenType";
16 changes: 16 additions & 0 deletions seminar6/advanced/src/constants/response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const success = (status: number, message: string, data?: any) => {
return {
status,
success: true,
message,
data,
};
};

export const fail = (status: number, message: string) => {
return {
status,
success: false,
message,
};
};
42 changes: 42 additions & 0 deletions seminar6/advanced/src/constants/responseMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export default {
NULL_VALUE: "필요한 값이 없습니다.",
OUT_OF_VALUE: "파라미터 값이 잘못되었습니다.",
NOT_FOUND: "잘못된 경로입니다.",
BAD_REQUEST: "잘못된 요청입니다.",

// 회원가입 및 로그인
SIGNUP_SUCCESS: "회원 가입 성공",
SIGNUP_FAIL: "회원 가입 실패",
SIGNIN_SUCCESS: "로그인 성공",
SIGNIN_FAIL: "로그인 실패",
ALREADY_NICKNAME: "이미 사용중인 닉네임입니다.",
INVALID_PASSWORD: "잘못된 비밀번호입니다.",

// 유저
READ_USER_SUCCESS: "유저 조회 성공",
READ_USER_FAIL: "유저 조회 실패",
READ_ALL_USERS_SUCCESS: "모든 유저 조회 성공",
READ_ALL_USERS_FAIL: "모든 유저 조회 실패",
UPDATE_USER_SUCCESS: "유저 수정 성공",
UPDATE_USER_FAIL: "유저 수정 실패",
DELETE_USER_SUCCESS: "유저 탈퇴 성공",
DELETE_USER_FAIL: "유저 탈퇴 실패",
NO_USER: "탈퇴했거나 가입하지 않은 유저입니다.",

// 콘텐츠
READ_CONTENT_SUCCESS: "콘텐츠 정보 조회 성공",
CREATE_LIKE_CONTENT_SUCCESS: "찜한 콘텐츠 생성 성공",
READ_LIKE_CONTENT_SUCCESS: "찜한 콘텐츠 정보 조회 성공",
DELETE_LIKE_CONTENT_SUCCESS: "찜한 콘텐츠 삭제 성공",

// 토큰
CREATE_TOKEN_SUCCESS: "토큰 재발급 성공",
EXPIRED_TOKEN: "토큰이 만료되었습니다.",
EXPIRED_ALL_TOKEN: "모든 토큰이 만료되었습니다.",
INVALID_TOKEN: "유효하지 않은 토큰입니다.",
VALID_TOKEN: "유효한 토큰입니다.",
EMPTY_TOKEN: "토큰 값이 없습니다.",

// 서버 내 오류
INTERNAL_SERVER_ERROR: "서버 내 오류",
};
15 changes: 15 additions & 0 deletions seminar6/advanced/src/constants/statusCode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
export default {
OK: 200, // 목록, 상세, 수정 성공
CREATED: 201, // POST나 PUT으로 데이터 등록할 경우 사용
// 어떠한 생성 작업을 요청받아 생성 작업을 성공
ACCEPTED: 202, // 요청은 받았지만, 아직 동작을 수행하지 않은 상태로 요청이 적절함을 의미한다.
NO_CONTENT: 204, // 요청이 성공은 했지만 응답할 콘텐츠가 없을 경우를 뜻한다.
BAD_REQUEST: 400, // 클라이언트가 올바르지 못한 요청을 보내고 있음을 의미
UNAUTHORIZED: 401, // 로그인을 하지 않아 권한이 없음. 권한 인증 요구
FORBIDDEN: 403, // 요청이 서버에 의해 거부 되었음을 의미. 금지된 페이지
NOT_FOUND: 404, // 요청한 URL을 찾을 수 없음을 의미
CONFLICT: 409, // 클라이언트 요청에 대해 서버에서 충돌 요소가 발생 할수 있음을 의미
INTERNAL_SERVER_ERROR: 500, // 서버에 오류가 발생하여 응답 할 수 없음을 의미
SERVICE_UNAVAILABLE: 503, // 현재 서버가 유지보수 등의 이유로 일시적인 사용 불가함을 의미
DB_ERROR: 600,
};
4 changes: 4 additions & 0 deletions seminar6/advanced/src/constants/tokenType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default {
TOKEN_EXPIRED: -3,
TOKEN_INVALID: -2,
};
98 changes: 98 additions & 0 deletions seminar6/advanced/src/controller/contentController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { LikeContentCreateDto } from "./../interfaces/common/Content/LikeContentCreateDto";
import { Request, Response } from "express";
import { message, statusCode } from "../constants";
import { success, fail } from "../constants/response";
import { contentService } from "../service";

//* 콘텐츠 정보 조회
const getContent = async (req: Request, res: Response) => {
const { contentId } = req.params;
const { episode } = req.query;

let type: "episode" | null;
if (episode) {
type = "episode";
} else {
type = null;
}

if (!contentId) {
return res
.status(statusCode.BAD_REQUEST)
.send(fail(statusCode.BAD_REQUEST, message.BAD_REQUEST));
}
switch (type) {
case "episode": {
const data = await contentService.getContent(
+contentId,
+(episode as string)
);

return res
.status(statusCode.OK)
.send(success(statusCode.OK, message.READ_CONTENT_SUCCESS, data));
}
case null: {
const data = await contentService.getAllContentsInfo(+contentId);
return res
.status(statusCode.OK)
.send(success(statusCode.OK, message.READ_CONTENT_SUCCESS, data));
}
}
};

//* 찜한 콘텐츠 생성
const createLikeContent = async (req: Request, res: Response) => {
const { userId } = req.params;
const likeContentCreateDto: LikeContentCreateDto = req.body;

if (!likeContentCreateDto) {
return res
.status(statusCode.BAD_REQUEST)
.send(fail(statusCode.BAD_REQUEST, message.BAD_REQUEST));
}

const data = await contentService.createLikeContent(
+userId,
likeContentCreateDto
);
return res
.status(statusCode.OK)
.send(success(statusCode.OK, message.CREATE_LIKE_CONTENT_SUCCESS, data));
};

//* 찝한 콘텐츠 조회
const getLikeContents = async (req: Request, res: Response) => {
const { userId } = req.params;

if (!userId) {
return res
.status(statusCode.BAD_REQUEST)
.send(fail(statusCode.BAD_REQUEST, message.BAD_REQUEST));
}

const data = await contentService.getLikeContents(+userId);

return res
.status(statusCode.OK)
.send(success(statusCode.OK, message.READ_LIKE_CONTENT_SUCCESS, data));
};

//* 찜한 콘텐츠 삭제
const deleteLikeContent = async (req: Request, res: Response) => {
const { likeContentId } = req.params;

await contentService.deleteLikeContent(+likeContentId);
return res
.status(statusCode.OK)
.send(success(statusCode.OK, message.DELETE_LIKE_CONTENT_SUCCESS));
};

const contentController = {
getContent,
createLikeContent,
getLikeContents,
deleteLikeContent,
};

export default contentController;
4 changes: 4 additions & 0 deletions seminar6/advanced/src/controller/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import userController from "./userController";
import contentController from "./contentController";

export { userController, contentController };
105 changes: 105 additions & 0 deletions seminar6/advanced/src/controller/userController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { UserUpdateDTO } from "../interfaces/common/User/UserUpdateDto";
import { Request, Response } from "express";
import { validationResult } from "express-validator";
import { message, statusCode } from "../constants";
import { success, fail } from "../constants/response";
import { UserCreateDTO } from "../interfaces/common/User/UserCreateDto";
import userService from "../service/userService";
import jwtHandler from "../modules/jwtHandler";
import { UserSignInDTO } from "../interfaces/common/User/UserSignInDto";

//* 유저 생성
const createUser = async (req: Request, res: Response) => {
//? validation의 결과를 바탕으로 분기 처리
const error = validationResult(req);
if (!error.isEmpty()) {
return res
.status(statusCode.BAD_REQUEST)
.send(fail(statusCode.BAD_REQUEST, message.BAD_REQUEST));
}
//? 기존 비구조화 할당 방식 -> DTO의 형태
const userCreateDto: UserCreateDTO = req.body;
const data = await userService.createUser(userCreateDto);

if (!data) {
return res
.status(statusCode.BAD_REQUEST)
.send(fail(statusCode.BAD_REQUEST, message.SIGNUP_FAIL));
}

const accessToken = jwtHandler.sign(data.id);

const result = {
id: data.id,
name: data.userName,
accessToken,
};

return res
.status(statusCode.CREATED)
.send(success(statusCode.CREATED, message.SIGNUP_SUCCESS, result));
};

//* 유저 로그인
const signInUser = async (req: Request, res: Response) => {
const error = validationResult(req);
if (!error.isEmpty()) {
return res
.status(statusCode.BAD_REQUEST)
.send(fail(statusCode.BAD_REQUEST, message.BAD_REQUEST));
}

const userSignInDto: UserSignInDTO = req.body;

try {
const userId = await userService.signInUser(userSignInDto);

if (!userId)
return res
.status(statusCode.NOT_FOUND)
.send(fail(statusCode.NOT_FOUND, message.NOT_FOUND));
else if (userId === statusCode.UNAUTHORIZED)
return res
.status(statusCode.UNAUTHORIZED)
.send(fail(statusCode.UNAUTHORIZED, message.INVALID_PASSWORD));

const accessToken = jwtHandler.sign(userId);

const result = {
id: userId,
accessToken,
};

res
.status(statusCode.OK)
.send(success(statusCode.OK, message.SIGNIN_SUCCESS, result));
} catch (e) {
console.log(error);
//? 서버 내부에서 오류 발생
res
.status(statusCode.INTERNAL_SERVER_ERROR)
.send(
fail(statusCode.INTERNAL_SERVER_ERROR, message.INTERNAL_SERVER_ERROR)
);
}
};

//* 유저 정보(이름) 수정
const updateUser = async (req: Request, res: Response) => {
const userUpdateDto: UserUpdateDTO = req.body;
const { userId } = req.params;

if (!userUpdateDto) {
return res
.status(statusCode.BAD_REQUEST)
.send(fail(statusCode.BAD_REQUEST, message.BAD_REQUEST));
}
const updatedUser = await userService.updateUser(+userId, userUpdateDto);
return res
.status(statusCode.OK)
.send(success(statusCode.OK, message.UPDATE_USER_SUCCESS, updatedUser));
};

const userController = { createUser, signInUser, updateUser };

export default userController;
Loading