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

[7주차] 기본/도전 과제 제출 #6

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
6 changes: 6 additions & 0 deletions seminar7/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"
}
32 changes: 32 additions & 0 deletions seminar7/advanced/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"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/multer": "^1.4.7",
"@types/multer-s3": "^3.0.0",
"@types/node": "^18.11.9",
"nodemon": "^2.0.20"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.216.0",
"@prisma/client": "^4.5.0",
"bcryptjs": "^2.4.3",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"express-validator": "^6.14.2",
"jsonwebtoken": "^8.5.1",
"multer": "^1.4.5-lts.1",
"multer-s3": "^3.0.1",
"prisma": "^4.5.0"
}
}
47 changes: 47 additions & 0 deletions seminar7/advanced/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
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?
image String[] @db.VarChar(800)
episode Episode[]
likeContent LikeContent[]

createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}

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")
}
26 changes: 26 additions & 0 deletions seminar7/advanced/src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import dotenv from "dotenv";

// Set the NODE_ENV to 'development' by default
process.env.NODE_ENV = process.env.NODE_ENV || "development";

const envFound = dotenv.config();

if (envFound.error) {
throw new Error("⚠️ Couldn't find .env file ⚠️");
}

export default {
port: parseInt(process.env.PORT as string, 10) as number,

//? 데이터베이스
database: process.env.DATABASE_URL as string,

//? JWT
jwtSecret: process.env.JWT_SECRET as string,
jwtAlgo: process.env.JWT_ALGO as string,

//? AWS
s3AccessKey: process.env.S3_ACCESS_KEY as string,
s3SecretKey: process.env.S3_SECRET_KEY as string,
bucketName: process.env.S3_BUCKET as string,
};
12 changes: 12 additions & 0 deletions seminar7/advanced/src/config/s3Config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { S3Client } from "@aws-sdk/client-s3";
import config from ".";

const s3: S3Client = new S3Client({
region: "ap-northeast-2",
credentials: {
accessKeyId: config.s3AccessKey,
secretAccessKey: config.s3SecretKey,
},
});

export default s3;
4 changes: 4 additions & 0 deletions seminar7/advanced/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export { default as message } from "./responseMessage";
export { default as statusCode } from "./statusCode";
export { default as tokenType } from "./tokenType";

16 changes: 16 additions & 0 deletions seminar7/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,
};
};
55 changes: 55 additions & 0 deletions seminar7/advanced/src/constants/responseMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
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: "탈퇴했거나 가입하지 않은 유저입니다.",
SEARCH_USER_SUCCESS: "유저 검색 성공",
SEARCH_USER_FAIL : "유저 검색 실패",

// 이미지
CREATE_IMAGE_SUCCESS: "이미지 생성 성공",
CREATE_IMAGE_FAIL: "이미지 생성 실패",
NO_IMAGE: "이미지가 없습니다.",

// 콘텐츠
CREATE_CONTENT_SUCCESS: "콘텐츠 생성 성공",
CREATE_CONTENT_FAIL: "콘텐츠 생성 실패",
READ_CONTENT_SUCCESS: "콘텐츠 정보 조회 성공",
READ_ALL_CONTENTS_SUCCESS: "콘텐츠 전체 정보 조회 성공",
CREATE_LIKE_CONTENT_SUCCESS: "찜한 콘텐츠 생성 성공",
READ_LIKE_CONTENT_SUCCESS: "찜한 콘텐츠 정보 조회 성공",
DELETE_LIKE_CONTENT_SUCCESS: "찜한 콘텐츠 삭제 성공",
SEARCH_CONTENT_SUCCESS: "콘텐츠 검색 조회 성공",
SEARCH_CONTENT_FAIL: "콘텐츠 검색 조회 실패",


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

// 서버 내 오류
INTERNAL_SERVER_ERROR: "서버 내 오류",
};
15 changes: 15 additions & 0 deletions seminar7/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 seminar7/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,
};
150 changes: 150 additions & 0 deletions seminar7/advanced/src/controller/contentController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { ContentCreateDto } from './../interfaces/Content/ContentCreateDto';
import { LikeContentCreateDto } from "./../interfaces/Content/LikeContentCreateDto";
import { Request, Response } from "express";
import { message, statusCode } from "../constants";
import { success, fail } from "../constants/response";
import { contentService } from "../service";

//* 콘텐츠 생성
const createContent = async (req: Request, res: Response) => {
const images: Express.MulterS3.File[] = req.files as Express.MulterS3.File[];
const imageList = images.map((image: Express.MulterS3.File) => {
return image.location;
})
Comment on lines +10 to +13
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이미지 여러 개를 올릴 때는 [] 하면 되는군요!!👍


const contentCreateDto: ContentCreateDto = {
contentName: req.body.contentName,
genre: req.body.genre,
ageLimit: +(req.body.ageLimit),
imageList: imageList,
}

if (!contentCreateDto) {
res.status(statusCode.BAD_REQUEST).send(fail(statusCode.BAD_REQUEST, message.CREATE_CONTENT_FAIL));
}
const data = await contentService.createContent(contentCreateDto);

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

return res
.status(statusCode.CREATED)
.send(success(statusCode.CREATED, message.CREATE_CONTENT_SUCCESS, data));
}

//* 콘텐츠 정보 조회
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,
Number(episode),
);

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 getAllContents = async (req: Request, res: Response) => {
const { page, limit } = req.query;
const data = await contentService.getAllContents(Number(page),Number(limit));
return res.status(statusCode.OK).send(success(statusCode.OK, message.READ_ALL_CONTENTS_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 searchContentByName = async (req: Request, res: Response) => {
const { keyword } = req.query;

const data = await contentService.searchContentByName( keyword as string );

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

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

const contentController = {
createContent,
getContent,
getAllContents,
createLikeContent,
getLikeContents,
deleteLikeContent,
searchContentByName,
};

export default contentController;
Loading