-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
51 lines (40 loc) · 1.31 KB
/
server.js
File metadata and controls
51 lines (40 loc) · 1.31 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
const jsonServer = require("json-server");
const data = require("./db.json");
const Hangul = require("hangul-js");
const cors = require("cors");
const server = jsonServer.create();
const router = jsonServer.router("db.json");
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.use(cors());
// Custom API endpoint
server.get("/search", (req, res) => {
const { key } = req.query;
if (!key) {
return res.status(400).send("검색어를 입력해주세요.");
}
const initialsResult = data.products.filter((product) => {
const words = product.split(" ");
const initials = words.map((word) =>
Hangul.disassemble(word)
.map((char) => Hangul.assemble(char.charAt(0)))
.join("")
);
const searchInitial = Hangul.disassemble(key)
.map((char) => Hangul.assemble(char.charAt(0)))
.join("");
return initials.some((initial) => initial.startsWith(searchInitial));
});
const wordsResult = data.products.filter((product) => {
return product.includes(key);
});
const result = [...new Set([...initialsResult, ...wordsResult])];
if (result.length === 0) {
return res.status(404).send("검색 결과가 없습니다.");
}
return res.json(result);
});
server.use(router);
server.listen(3000, () => {
console.log("JSON Server is running");
});