-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (75 loc) · 1.75 KB
/
index.js
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
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
app.use(express.json());
app.get("/", (req, res) => {
res.send(
"Welcome to the API! Use /api/desa/:kodedesa/:tahun to access data."
);
});
app.get(["/api", "/api/desa"], (req, res) => {
res.status(404).json({
status: 404,
error: true,
message: "API endpoint not found",
});
});
app.get("/api/desa/:kodedesa", (req, res) => {
const folderPath = path.join(
__dirname,
"public",
"desa",
req.params.kodedesa
);
if (!fs.existsSync(folderPath)) {
return res.status(400).json({
status: 400,
error: true,
message: "ID Desa tidak ditemukan",
});
}
res.status(400).json({
status: 400,
error: true,
message: "Tahun tidak ditemukan dalam permintaan",
});
});
app.get("/api/desa/:kodedesa/:tahun", (req, res) => {
const { kodedesa, tahun } = req.params;
const filePath = path.join(
__dirname,
"public",
"desa",
kodedesa,
tahun + ".json"
);
if (!fs.existsSync(path.join(__dirname, "public", "desa", kodedesa))) {
return res.status(400).json({
status: 400,
error: true,
message: "ID Desa tidak ditemukan",
});
}
if (!fs.existsSync(filePath)) {
return res.status(400).json({
status: 400,
error: true,
message: "Tahun tidak ditemukan",
});
}
fs.readFile(filePath, "utf8", (err, data) => {
if (err) {
return res.status(500).json({
status: 500,
error: true,
message: "Error reading the file",
});
}
res.json(JSON.parse(data));
});
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});