Skip to content

Commit

Permalink
refactoring: ejs 로 마이그레이션
Browse files Browse the repository at this point in the history
  • Loading branch information
JangHwanPark committed Jun 23, 2024
1 parent d3e74be commit dfa854b
Show file tree
Hide file tree
Showing 9 changed files with 217 additions and 107 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"ejs": "^3.1.10",
"express": "^4.19.2",
"express-session": "^1.18.0",
"jsonwebtoken": "^9.0.2",
Expand Down Expand Up @@ -51,4 +52,4 @@
"keywords": [],
"license": "ISC",
"description": ""
}
}
File renamed without changes.
File renamed without changes.
39 changes: 31 additions & 8 deletions src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,39 @@ dotenv.config(); // 환경변수 읽어오기
app.use(cors()); // 모든 프론트 서버 허용
app.use(express.json()); // JSON 형식의 요청 본문을 파싱

// ejs 를 사용자 뷰 엔진으로 설정
app.set('view engine', 'ejs');

// 뷰 파일의 디렉토리 설정
app.set('views', path.join(__dirname, 'views'));

// 정적파일 적용 - 정적 파일을 서빙할 디렉토리 설정
app.use(express.static(path.join(__dirname, 'public')));

// Index page
app.get("/", (req, res) => {
const indexPath = path.join(__dirname, "view", "index.html");
res.sendFile(indexPath, (err) => {
if (err) res.status(500).send(err);
});
const data = {
title: "학술",
message: "MOCK",
endpoints: [
{ method: "GET", url: "http://34.197.44.20/admin/users", description: "전체 유저 조회", id: "user-count" },
{ method: "GET", url: "http://34.197.44.20/books/books", description: "전체 책 조회", id: "book-count" },
{ method: "GET", url: "http://34.197.44.20/coupang_products/all", description: "전체 쿠팡 제품 조회", id: "coupang-count" }
],
specificEndpoints: [
{ method: "GET", url: "http://34.197.44.20/admin/user/000043c2-b919-4281-9dab-f2a5b446973b", description: "특정 유저 조회" },
{ method: "GET", url: "http://34.197.44.20/books/info/1", description: "특정 책 조회" },
{ method: "GET", url: "http://34.197.44.20/coupang_products/product/1", description: "특정 제품 조회" },
{ method: "GET", url: "http://34.197.44.20/coupang_products/food", description: "특정 카테고리 조회" }
],
inputSections: [
{ type: "users", label: "/admin/user/", placeholder: "유저의 ID를 입력하세요" },
{ type: "books", label: "/books/info/", placeholder: "책의 ID를 입력하세요" },
{ type: "products", label: "/coupang_products/product/", placeholder: "제품의 ID를 입력하세요" }
]
};

res.render("index", data);
});

// Router
Expand All @@ -40,10 +67,6 @@ app.use("/coupang-products", coupangRouter);
app.use(timeoutMiddleware);
app.use(retryMiddleware);

// 정적파일 적용
app.use(express.static(path.join(__dirname, "view")));
app.set('view engine', 'ejs');

// Start Server
app.listen(process.env.PORT, () => {
console.log(`서버 시작 Port: ${process.env.PORT}`)
Expand Down
95 changes: 0 additions & 95 deletions src/view/index.html

This file was deleted.

2 changes: 1 addition & 1 deletion src/view/guide/index.html → src/views/guide/index.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</head>
<body>
<header class="main_header">
<a href="../index.html">
<a href="../index.ejs">
<h1>MOCK</h1>
</a>
<nav class="main_nav">
Expand Down
File renamed without changes.
145 changes: 145 additions & 0 deletions src/views/index.ejs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><%= title %></title>
<link rel="stylesheet" href="../styles.css">
</head>
<body>
<header class="main_header">
<a href="/">
<h1><%= message %></h1>
</a>
<nav class="main_nav">
<a href="guide/index.ejs" class="modal-button">Guide</a>
</nav>
</header>

<section class="guide">
<h1>API란?</h1>
<div>API(Application Programming Interface)는 응용 프로그램이 서로 통신하고 데이터를 주고받을 수 있도록 하는 인터페이스입니다.</div>
</section>

<section class="guide">
<h1>어떨때 사용하나요?</h1>
<div>MOCK은 가짜 데이터가 필요할 때마다 사용할 수 있는 안산대학교 컴퓨터 공학과의 무료 REST API입니다.</div>
</section>

<section class="endpoint">
<h1>데이터 전체 조회 API</h1>
<div class="data_container">
<% endpoints.forEach(endpoint => { %>
<div>
<p><%= endpoint.method %></p>
<a href="<%= endpoint.url %>" target="_blank"><%= endpoint.description %></a>
<span id="<%= endpoint.id %>"></span>
</div>
<% }) %>
</div>
</section>

<section class="endpoint">
<h1>특정 조건의 데이터 조회 API</h1>
<div class="data_container">
<% specificEndpoints.forEach(endpoint => { %>
<div>
<p><%= endpoint.method %></p>
<a href="<%= endpoint.url %>" target="_blank"><%= endpoint.description %></a>
</div>
<% }) %>
</div>
</section>

<section class="endpoint">
<h1>API TEST (GET)</h1>
<nav class="sub_nav">
<ul>
<% inputSections.forEach(section => { %>
<li><a href="#" onclick="showInput('<%= section.type %>'); return false;">특정 <%= section.type %> 조회</a></li>
<% }) %>
</ul>
</nav>
<div id="input-container">
<% inputSections.forEach(section => { %>
<div class="input-section <%= section.type %>">
<label for="input-id-<%= section.type %>"><%= section.label %></label>
<input type="text" id="input-id-<%= section.type %>" placeholder="<%= section.placeholder %>">
<button class="run-button" onclick="fetchSpecificData('<%= section.type %>')">Run</button>
</div>
<% }) %>
</div>

<pre id="result">{}</pre>
</section>

<script>
document.addEventListener('DOMContentLoaded', function() {
// 기본적으로 특정 유저 조회 입력 창만 보이도록 설정
const inputSections = document.querySelectorAll('.input-section');
inputSections.forEach(section => {
if (section.classList.contains('users')) {
section.style.display = 'flex'; // 또는 'block' 등으로 설정
} else {
section.style.display = 'none';
}
});
fetchData();
});
function fetchData() {
const endpoints = [
<% endpoints.forEach(endpoint => { %>
{ id: '<%= endpoint.id %>', url: '<%= endpoint.url %>' },
<% }) %>
];
endpoints.forEach(endpoint => {
fetch(endpoint.url)
.then(response => response.json())
.then(data => {
document.getElementById(endpoint.id).textContent = `전체 ${endpoint.id.split('-')[0]} ${data.count}개 조회`;
})
.catch(error => {
console.error('데이터 가져오기 실패:', error);
});
});
}
function fetchSpecificData(type) {
const input = document.getElementById(`input-id-${type}`).value;
let url = '';
if (type === 'users') {
url = `http://34.197.44.20/admin/user/${input}`;
} else if (type === 'books') {
url = `http://34.197.44.20/books/info/${input}`;
} else if (type === 'products') {
url = `http://34.197.44.20/coupang_products/product/${input}`;
}
fetch(url)
.then(response => response.json())
.then(data => {
document.getElementById('result').textContent = JSON.stringify(data, null, 2);
})
.catch(error => {
console.error('데이터 가져오기 실패:', error);
});
}
function showInput(section) {
// 모든 입력 섹션을 숨김
const inputSections = document.querySelectorAll('.input-section');
inputSections.forEach(sec => {
sec.style.display = 'none';
});
// 선택한 섹션만 보이도록 함
const selectedInput = document.querySelector(`.input-section.${section}`);
if (selectedInput) {
selectedInput.style.display = 'flex';
}
}
</script>
</body>
</html>
Loading

0 comments on commit dfa854b

Please sign in to comment.