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
Binary file modified .DS_Store
Binary file not shown.
8 changes: 8 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"dependencies": {
"jsonwebtoken": "^8.5.1"
},
"devDependencies": {
"@types/jsonwebtoken": "^8.5.9"
}
}
3 changes: 3 additions & 0 deletions seminar4/.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 seminar4/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"
}
27 changes: 27 additions & 0 deletions seminar4/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "seminar4",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"dev": "nodemon",
"build": "tsc && node dist",
"db:pull": "npx prisma db pull",
"db:push": "npx prisma db push",
"generate": "npx prisma generate"
},
"devDependencies": {
"@types/bcryptjs": "^2.4.2",
"@types/express": "^4.17.14",
"@types/express-validator": "^3.0.0",
"@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",
"prisma": "^4.5.0"
}
}
37 changes: 37 additions & 0 deletions seminar4/prisma/schema.prisma
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
generator client {
provider = "prisma-client-js"
}

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

model User {
userId Int @id @default(autoincrement())
userName String @db.VarChar(30)
profileImage String?
payMoney Int
cash Int
reviewCount Int
likeCount Int
recentSeeCount Int
}

model Product {
productId Int @id @unique
productName String @db.VarChar(100)
productImage String
discount Int
originalPrice Int
discountedPrice Int
reviewCount Int
}

model User_Seminar {
id Int @id(map: "user_seminar_pk") @unique(map: "user_seminar_id_uindex") @default(autoincrement())
userName String @db.VarChar(100)
age Int?
email String @db.VarChar(400)
password String @db.VarChar(400)
}
3 changes: 3 additions & 0 deletions seminar4/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export { default as rm } from "./responseMessage";
export { default as sc } from "./statusCode";
export { default as tokenType } from "./tokenType";
16 changes: 16 additions & 0 deletions seminar4/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,
};
};
34 changes: 34 additions & 0 deletions seminar4/src/constants/responseMessage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
export default {
NULL_VALUE: "필요한 값이 없습니다.",
OUT_OF_VALUE: "파라미터 값이 잘못되었습니다.",
NOT_FOUND: "잘못된 경로입니다.",
BAD_REQUEST: "잘못된 요청입니다.",

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

// 유저
READ_USER_SUCCESS: "유저 조회 성공",
READ_ALL_USERS_SUCCESS: "모든 유저 조회 성공",
UPDATE_USER_SUCCESS: "유저 수정 성공",
UPDATE_USER_FAIL: "유저 수정 실패",
DELETE_USER_SUCCESS: "유저 탈퇴 성공",
DELETE_USER_FAIL: "유저 탈퇴 실패",
NO_USER: "탈퇴했거나 가입하지 않은 유저입니다.",
INVALID_PASSWORD: "잘못된 비밀번호입니다.",

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

// 서버 내 오류
INTERNAL_SERVER_ERROR: "서버 내 오류",
};
15 changes: 15 additions & 0 deletions seminar4/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 seminar4/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,
};
1 change: 1 addition & 0 deletions seminar4/src/controller/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as userController } from "./userController";
133 changes: 133 additions & 0 deletions seminar4/src/controller/userController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
import { Request, Response } from "express";
import { validationResult } from "express-validator";
import { rm, sc } from "../constants";
import { fail, success } from "../constants/response";
import { UserSignInDTO } from "../interfaces/common/user/UserSignInDTO";
import { UserCreateDTO } from "../interfaces/common/UserCreateDTO";
import jwtHandler from "../modules/jwtHandler";
import { userService } from "../service";

//* 유저 생성
const createUser = async (req: Request, res: Response) => {

//? validation의 결과를 바탕으로 분기 처리
//* 유효성 검증의 에러메시지를 받을 수 있음
const error = validationResult(req);
if (!error.isEmpty()) {
return res.status(sc.BAD_REQUEST).send(fail(sc.BAD_REQUEST, rm.BAD_REQUEST))
}

//? 기존 비구조화 할당 방식 -> DTO의 형태
const userCreateDto: UserCreateDTO = req.body;
const data = await userService.createUser(userCreateDto);

if (!data) {
return res.status(sc.BAD_REQUEST).send(fail(sc.BAD_REQUEST, rm.SIGNUP_FAIL))
}

//? 아까 만든 jwtHandler 내 sign 함수를 이용해 accessToken 생성
const accessToken = jwtHandler.sign(data.id);

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

return res.status(sc.CREATED).send(success(sc.CREATED, rm.SIGNUP_SUCCESS, result))
};

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

const userSignInDto: UserSignInDTO = req.body;

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

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

//* 새로 발급
const accessToken = jwtHandler.sign(userId);

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

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

//* 유저 전체 조회
const getAllUser = async (req: Request, res: Response) => {
const data = await userService.getAllUser();

return res.status(sc.OK).json({ status: sc.OK, message: rm.READ_ALL_USERS_SUCCESS, data });
};

//* 유저 정보 업데이트
const updateUser = async (req: Request, res: Response) => {
const { userName } = req.body;
const { userId } = req.params;

if (!userId) return res.status(sc.NOT_FOUND).send(fail(sc.NOT_FOUND, rm.NOT_FOUND));
if (!userName) return res.status(sc.BAD_REQUEST).json({ status: sc.BAD_REQUEST, message: rm.UPDATE_USER_FAIL });

const data = await userService.updateUser(+userId, userName);
if (!data) return res.status(sc.BAD_REQUEST).json({ status: sc.BAD_REQUEST, message: rm.UPDATE_USER_FAIL });

return res.status(sc.OK).json({ status: sc.OK, message: rm.UPDATE_USER_SUCCESS, data });
};

//* 유저 삭제
const deleteUser = async (req: Request, res: Response) => {
const { userId } = req.params;

if (!userId) return res.status(sc.NOT_FOUND).send(fail(sc.NOT_FOUND, rm.NOT_FOUND));
Copy link
Member

Choose a reason for hiding this comment

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

잘 작성해주셨는데 PR에 작성해주신 코멘트에 대한 답변을 여기에 달아보자면 !
path 내에서 userId가 존재하지 않는다면 404 Not Found 를, userId가 db 내에 존재하지 않는 자원이라면 400 Bad Request 처리를 해주는 것이 좋아보입니다!
404 Not Found는 서버가 요청받은 리소스를 찾을 수 없다는 것을 의미인데 여기서 ‘리소스’는 DB 자원보다 API URI 요청 경로를 의미하는 바가 더 큰 것 같더라구요!
Bad Request를 던져주게 된다면 디테일한 메세지를 전달해주는 것이 중요해보입니다:)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

오 제가 궁금한 부분에 대해 정확한 답변을 해주셨네요! 역시 최고👍

try {
await userService.deleteUser(+userId);

res.status(sc.OK).json({ status: sc.OK, message: rm.DELETE_USER_SUCCESS });
}catch(error) {
//* 사용자가 가입하지 않은 userId를 보낸 경우 -> 이렇게 처리하는 게 맞는지?
res.status(sc.BAD_REQUEST).send(fail(sc.BAD_REQUEST, rm.DELETE_USER_FAIL));
}
};

//* controller -> 문지기, 서비스(비즈니스) 로직 포함x
const getUserById = async (req: Request, res: Response) => {
const { userId } = req.params;

if (!userId) return res.status(sc.NOT_FOUND).send(fail(sc.NOT_FOUND, rm.NOT_FOUND));

//* params: string , userId: int
//* Number() 형변환 대신 +userId 하면 타입변환됨
const data = await userService.getUserById(+userId);

if (!data) {
return res.status(sc.NOT_FOUND).json({ status: sc.NOT_FOUND, message: rm.NOT_FOUND });
}
return res.status(sc.OK).json({ status: sc.OK, message: rm.READ_USER_SUCCESS, data });
};

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

export default userController;
24 changes: 24 additions & 0 deletions seminar4/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import express, { NextFunction, Request, Response } from "express";
import router from "./router";

const app = express(); // express 객체 받아옴
const PORT = 3000; // 사용할 port를 3000번으로 설정

app.use(express.json()); // express 에서 request body를 json 으로 받아오겠다.

app.use("/api", router); // use -> 모든 요청
// localhost:8000/api -> api 폴더
// localhost:8000/api/user -> user.ts

//* HTTP method - GET
app.get("/", (req: Request, res: Response, next: NextFunction) => {
res.send("마! 이게 서버다!!!!!!!!!!!!!!!!!!!!");
});

app.listen(PORT, () => {
console.log(`
#############################################
🛡️ Server listening on port: ${PORT} 🛡️
#############################################
`);
}); // 8000 번 포트에서 서버를 실행하겠다!
6 changes: 6 additions & 0 deletions seminar4/src/interfaces/common/UserCreateDTO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface UserCreateDTO {
name: string;
age: number;
email: string;
password: string;
}
4 changes: 4 additions & 0 deletions seminar4/src/interfaces/common/user/UserSignInDTO.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface UserSignInDTO {
email: string;
password: string;
}
36 changes: 36 additions & 0 deletions seminar4/src/middlewares/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { NextFunction, Request, Response } from "express";
import { JwtPayload } from "jsonwebtoken";
import { rm, sc } from "../constants";
import { fail } from "../constants/response";
import tokenType from "../constants/tokenType";
import jwtHandler from "../modules/jwtHandler";

//* next 있으니까 middleware
export default async (req: Request, res: Response, next: NextFunction) => {
//* <autorization: Bearer 토큰값> -> split & reverse -> 토큰값 Bearer -> 0번 가져오면 토큰값
const token = req.headers.authorization?.split(" ").reverse()[0]; //? Bearer ~~ 에서 토큰만 파싱
if (!token) return res.status(sc.UNAUTHORIZED).send(fail(sc.UNAUTHORIZED, rm.EMPTY_TOKEN));

try {
const decoded = jwtHandler.verify(token); //? jwtHandler에서 만들어둔 verify로 토큰 검사

//? 토큰 에러 분기 처리
//* === : 엄격한 비교(타입까지 같아야 함)
if (decoded === tokenType.TOKEN_EXPIRED)
return res.status(sc.UNAUTHORIZED).send(fail(sc.UNAUTHORIZED, rm.EXPIRED_TOKEN));
if (decoded === tokenType.TOKEN_INVALID)
return res.status(sc.UNAUTHORIZED).send(fail(sc.UNAUTHORIZED, rm.INVALID_TOKEN));

//? decode한 후 담겨있는 userId를 꺼내옴
//* as 타입 단언 JwtPayload
const userId: number = (decoded as JwtPayload).userId;
if (!userId) return res.status(sc.UNAUTHORIZED).send(fail(sc.UNAUTHORIZED, rm.INVALID_TOKEN));

//? 얻어낸 userId 를 Request Body 내 userId 필드에 담고, 다음 미들웨어로 넘김( next() )
req.body.userId = userId;
next();
} catch (error) {
console.log(error);
res.status(sc.INTERNAL_SERVER_ERROR).send(fail(sc.INTERNAL_SERVER_ERROR, rm.INTERNAL_SERVER_ERROR));
}
};
1 change: 1 addition & 0 deletions seminar4/src/middlewares/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default as auth } from "./auth";
Loading