-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbreadcrumbs.js
More file actions
291 lines (249 loc) · 7.71 KB
/
breadcrumbs.js
File metadata and controls
291 lines (249 loc) · 7.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// const mysql = require("mysql2");
// const express = require("express");
// const app = express();
// const port = 3000;
// const connection = mysql.createConnection({
// host: "127.0.0.1",
// user: "root",
// password: "1234",
// database: "breadcrumbs",
// });
// connection.connect();
// app.get("/page/:id", (req, res) => {
// try {
// const pageId = parseInt(req.params.id);
// const query = `
// SELECT
// p1.id AS id, p1.title AS title, p1.content AS content, p1.path AS pagePath,
// p2.id AS subPageId, p2.title AS subPageTitle
// FROM
// pages p1
// LEFT JOIN
// pages p2 ON p1.id = p2.parentId
// WHERE
// p1.id = ?
// `;
// connection.query(query, [pageId], (error, results) => {
// if (error) {
// return res.status(400).json({ error: error.message });
// }
// if (results.length === 0) {
// return res.status(404).json({ error: "Page not found" });
// }
// console.log(results, "results");
// /**[
// {
// id: 4,
// title: '부모',
// content: '모',
// pagePath: [],
// subPageId: 7,
// subPageTitle: '자식1'
// },
// {
// id: 4,
// title: '부모',
// content: '모',
// pagePath: [],
// subPageId: 13,
// subPageTitle: '자식11'
// }
// ] results 의 값*/
// const { id, title, content, pagePath } = results[0];
// const subPages = results
// .map((item) => ({
// subPageId: item.subPageId,
// title: item.subPageTitle,
// }))
// .filter((subPage) => subPage.subPageId !== null);
// const pathQuery = `SELECT title FROM pages WHERE id IN (?)`;
// // console.log(typeof pagePath, "ㅁㄴㅇㄹ");
// // console.log(pagePath, "ㅁㄴㅇㄹ");
// if (pagePath.length === 0) {
// const response = {
// pageId: id,
// title: title,
// content: content,
// subPages,
// breadcrumbs: [],
// };
// return res.status(200).json(response);
// }
// connection.query(pathQuery, [pagePath], (error, pathResults) => {
// if (error) {
// return res.status(400).json({ error: error.message });
// }
// console.log(pathResults, "pathResults");
// /**[ { title: '부모' }, { title: '자식1' }, { title: '자식2' } ] pathResults의 값 */
// const breadcrumbs = pathResults.map((item) => item.title);
// const response = {
// pageId: id,
// title: title,
// content: content,
// subPages,
// breadcrumbs,
// };
// res.status(200).json(response);
// });
// });
// } catch (error) {
// console.log(error, "error log");
// res.status(500).json({ error: "Internal server error" });
// }
// });
// app.listen(port, () => {
// console.log(`Server running at http://localhost:${port}/`);
// });
/**
* mysql 로컬 db 접속 후 아래 순서대로 진행
* *
* database 만들기
* create database breadcrumbs
* *
* 테이블 만들기
* CREATE TABLE pages (
id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
content TEXT,
parentId INT,
path JSON,
FOREIGN KEY (parentId) REFERENCES pages(id)
);
* *
* 데이터 넣기
* -- 최상위 부모 페이지 생성
INSERT INTO pages (title, content, parentId, path) VALUES ('부모', '부모', NULL, '[]');
-- 첫 번째 자식 페이지 생성.
INSERT INTO pages (title, content, parentId, path) VALUES ('자식1', '자식1', 1, '[1]');
-- 두 번째 자식 페이지 생성.
INSERT INTO pages (title, content, parentId, path) VALUES ('자식2', '자식2', 2, '[1,2]');
-- 세 번째 자식 페이지 생성.
INSERT INTO pages (title, content, parentId, path) VALUES ('자식3', '자식3', 3, '[1,2,3]');
*/
const mysql = require("mysql2");
const express = require("express");
const app = express();
const port = 3000;
app.use(express.json());
let connection;
async function initialize() {
connection = await mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "1234",
database: "breadcrumbs",
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
});
}
initialize();
app.get("/page/:id", async (req, res) => {
try {
const pageId = parseInt(req.params.id);
const query = `
SELECT
p1.id AS id, p1.title AS title, p1.content AS content, p1.path AS pagePath,
p2.id AS subPageId, p2.title AS subPageTitle
FROM
pages p1
LEFT JOIN
pages p2 ON p1.id = p2.parentId
WHERE
p1.id = ?
`;
const [results] = await connection.promise().query(query, [pageId]);
if (results.length === 0) {
return res.status(404).json({ error: "Page not found" });
}
const { id, title, content, pagePath } = results[0];
const subPages = results
.map((item) => ({
subPageId: item.subPageId,
title: item.subPageTitle,
}))
.filter((subPage) => subPage.subPageId !== null);
if (pagePath && pagePath.length === 0) {
const response = {
pageId: id,
title,
content,
subPages,
breadcrumbs: [],
};
return res.status(200).json(response);
}
const pathQuery = `SELECT title FROM pages WHERE id IN (?)`;
const [pathResults] = await connection
.promise()
.query(pathQuery, [pagePath]);
const breadcrumbs = pathResults.map((item) => item.title);
const response = {
pageId: id,
title,
content,
subPages,
breadcrumbs,
};
res.status(200).json(response);
} catch (error) {
console.log(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
app.put("/page/:id", async (req, res) => {
try {
const { parentId } = req.body;
const pageId = parseInt(req.params.id);
const [currentPageResults] = await connection
.promise()
.query(`SELECT * FROM pages WHERE id = ?`, [pageId]);
if (currentPageResults.length === 0) {
return res.status(404).json({ error: "Page not found" });
}
const currentParentId = currentPageResults[0].parentId;
const currentPath = currentPageResults[0].path;
if (currentParentId === parentId) {
return res.status(400).json({
error: "parentId not same currentParentId",
});
}
let newPath = [];
if (parentId !== null) {
const [newParentResults] = await connection
.promise()
.query(`SELECT * FROM pages WHERE id = ?`, [parentId]);
if (newParentResults.length === 0) {
return res.status(404).json({ error: "New parent not found" });
}
newPath = [...newParentResults[0].path, parentId];
}
await connection
.promise()
.query(`UPDATE pages SET parentId = ?, path = ? WHERE id = ?`, [
parentId,
JSON.stringify(newPath),
pageId,
]);
const updatePath = async (parentId, parentPath) => {
const [children] = await connection
.promise()
.query(`SELECT * FROM pages WHERE parentId = ?`, [parentId]);
for (const child of children) {
const newChildPath = [...parentPath, child.id];
await connection
.promise()
.query(`UPDATE pages SET path = ? WHERE id = ?`, [
JSON.stringify(newChildPath),
child.id,
]);
await updatePath(child.id, newChildPath);
}
};
await updatePath(pageId, newPath);
res.status(200).json({ message: "success" });
} catch (error) {
console.log(error);
res.status(500).json({ error: "Internal Server Error" });
}
});