Files
mcs-lose/backend/server.js

110 lines
2.9 KiB
JavaScript

import express from "express";
import cors from "cors";
import env from "dotenv";
import {
query,
loginAdmin,
getTableData,
createEntry,
removeEntries,
saveRow,
resetData,
} from "./services/database.js";
import { generateToken, authenticate } from "./services/tokenService.js";
env.config();
const app = express();
const port = 8502;
app.use(cors());
// Increase body size limits to support large CSV JSON payloads
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
app.set("view engine", "ejs");
app.use(express.json({ limit: "10mb" }));
app.get("/", (req, res) => {
res.render("index.ejs", { title: port });
});
app.post("/lose", async (req, res) => {
const result = await query(req.body);
if (result.success) {
res.status(200).send("Update successful");
} else {
res.status(400).send("Update failed");
}
});
app.get("/table-data", authenticate, async (req, res) => {
const result = await getTableData();
if (result.success && result.data) {
res.status(200).json(result.data);
} else if (result.success && !result.data) {
res.status(204).json({ success: true });
} else {
res.status(500).json({ success: false });
}
});
app.post("/create-entry", authenticate, async (req, res) => {
try {
const result = await createEntry(req.body.losnummer);
if (result) {
res.status(201).json({ success: true });
} else {
res.status(400).json({ success: false, message: "Insert failed" });
}
} catch (err) {
console.error("/create-entry error", err);
res.status(500).json({ success: false, message: String(err) });
}
});
app.delete("/remove-entries", authenticate, async (req, res) => {
const result = await removeEntries(req.body.losnummern);
if (result) {
res.status(200).json({ success: true });
} else {
res.status(400).json({ success: false });
}
});
app.put("/save-row", authenticate, async (req, res) => {
const result = await saveRow(req.body);
if (result.success) {
res.status(200).json({ success: true });
} else {
res.status(400).json({ success: false });
}
});
app.post("/login", async (req, res) => {
const { username, password } = req.body;
const result = await loginAdmin(username, password);
if (result.success) {
const token = await generateToken({ username });
res.status(200).json({ success: true, token });
} else {
res.status(401).json({ success: false });
}
});
app.delete("/reset-data", authenticate, async (req, res) => {
const result = await resetData();
if (result.success) {
res.status(200).json({ success: true });
} else {
res.status(400).json({ success: false });
}
});
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
// error handling code
app.use((err, req, res, next) => {
// Log the error stack and send a generic error response
console.error(err.stack);
res.status(500).send("Something broke!");
});