-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
181 lines (142 loc) · 5.08 KB
/
Copy pathserver.js
File metadata and controls
181 lines (142 loc) · 5.08 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
const jsonServer = require("json-server");
const server = jsonServer.create();
const router = jsonServer.router("db.json");
const middlewares = jsonServer.defaults();
const low = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const { v4: uuidv4 } = require("uuid");
const dotenv = require("dotenv");
dotenv.config();
const path = require("path")
const fs = require("fs")
const adapter = new FileSync("db.json");
const db = low(adapter);
const customHeadersMiddleware = (req, res, next) => {
// Set custom headers
res.setHeader("Cache-Control", "public, max-age=3600");
res.setHeader("abc", "XYZ123");
// Continue with the next middleware or route handler
next();
};
server.use(middlewares);
server.use(jsonServer.bodyParser);
server.use(customHeadersMiddleware);
let dbData;
async function loadDbFromGitHub() {
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const REPO = "VidyBack/PostRequestVercel";
const FILE_PATH = "db.json";
const BRANCH = "master";
const res = await fetch(`https://api.github.com/repos/${REPO}/contents/${FILE_PATH}?ref=${BRANCH}`, {
headers: {
Authorization: `token ${GITHUB_TOKEN}`,
},
});
const fileData = await res.json();
if (fileData.content) {
const decoded = Buffer.from(fileData.content, "base64").toString("utf-8");
dbData = JSON.parse(decoded);
} else {
dbData = {}; // fallback if file doesn't exist
}
}
server.post("/add-template", async (req, res) => {
try {
if (!dbData) {
await loadDbFromGitHub();
}
const template = req.body.template;
if (!template || Object.keys(template).length === 0) {
return res.status(400).json({ error: "Template body cannot be empty" });
}
if (!template.id) {
const randomId = uuidv4();
template.id = randomId;
template.templateId = randomId;
}
const categoryInput = template.category?.[0];
if (!categoryInput) {
return res.status(400).json({ error: "Template must have a 'category' field" });
}
// Case-insensitive category
let matchedCategory = Object.keys(dbData).find(
(cat) => cat.toLowerCase() === categoryInput.toLowerCase()
);
if (!matchedCategory) matchedCategory = categoryInput;
dbData[matchedCategory] = [template, ...(dbData[matchedCategory] || [])];
console.log(`✅ Added new template to category '${matchedCategory}'`, template);
res.status(200).json({ message: `Template added to category '${matchedCategory}'.`, template });
} catch (err) {
console.error("Error adding template:", err);
res.status(500).json({ error: "Internal Server Error" });
}
});
server.post("/push-to-github", async (req, res) => {
try {
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const REPO = "VidyBack/ServerTemplates";
const FILE_PATH = "db.json";
const BRANCH = "main";
if (!dbData) {
return res.status(400).json({ error: "No in-memory DB data to push. Add templates first." });
}
console.log("githubtoken", GITHUB_TOKEN);
// 1️⃣ Fetch file metadata (get latest SHA)
const getFile = await fetch(
`https://api.github.com/repos/${REPO}/contents/${FILE_PATH}?ref=${BRANCH}`,
{
headers: {
Authorization: `token ${GITHUB_TOKEN}`,
},
}
);
const fileData = await getFile.json();
if (!fileData.sha) {
console.error("Could not get file SHA from GitHub response:", fileData);
return res.status(500).json({ error: "Failed to get file SHA from GitHub" });
}
// 2️⃣ Encode in-memory DB to base64
const encodedContent = Buffer.from(JSON.stringify(dbData, null, 2)).toString("base64");
// 3️⃣ Commit updated file
const commit = await fetch(`https://api.github.com/repos/${REPO}/contents/${FILE_PATH}`, {
method: "PUT",
headers: {
Authorization: `token ${GITHUB_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
message: `Updated db.json via API`,
content: encodedContent,
sha: fileData.sha,
branch: BRANCH,
}),
});
const commitResponse = await commit.json();
if (commitResponse.commit) {
console.log("✅ db.json successfully pushed to GitHub.");
return res.status(200).json({
message: "db.json successfully pushed to GitHub.",
commit: commitResponse.commit,
});
} else {
console.error("❌ GitHub commit failed:", commitResponse);
return res.status(500).json({ error: "GitHub commit failed", commitResponse });
}
} catch (error) {
console.error("Error pushing to GitHub:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});
server.post("/:purpose", (req, res) => {
// Process the request body and add/update data in db.json using lowdb
const newData = req.body;
// Add a new post
db.get(req.params.purpose).push(newData).write();
console.log("Added new post:", newData);
res.status(200).json(newData);
});
server.use(router);
const port = process.env.PORT || 8000;
server.listen(port, () => {
console.log(`JSON Server is running on http://localhost:${port}`);
});