Files
Timetable-V2/server/index.js
2022-11-16 19:03:32 +01:00

64 lines
1.7 KiB
JavaScript

import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
// Import API endpoints
import {
getTimetable,
getSubstitutions,
getHistory,
getClasses,
} from "./api/index.js";
import auth from "./api/auth.js";
import { Parser } from "./parser/index.js";
// Check DSB Mobile credentials are supplied
if (!process.env.DSB_USER || !process.env.DSB_PASSWORD) {
console.error("Error: DSB Auth environment variables missing!");
process.exit(1);
}
// Create the Webserver
const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
// Initialize the Parser and set it to update the
// substitution plan at the specified update interval
new Parser(
process.env.DSB_USER,
process.env.DSB_PASSWORD,
process.env.UPDATE_INTERVAL || 1 * 60 * 1000 // Default to 1 minute
);
// Create new Auth class to store sessions
app.post("/login", auth.login);
// Check login for every API request
app.use("/api", auth.checkLogin);
// Provide check endpoint so the frontend
// can check if the user is logged in
app.get("/api/check", (_req, res) => {
res.sendStatus(200);
});
// Register API endpoints
app.get("/api/timetable", getTimetable);
app.get("/api/substitutions", getSubstitutions);
app.get("/api/history", getHistory);
app.get("/api/classes", getClasses);
// Respond with 400 for non-existent endpoints
app.get("/api/*", (_req, res) => {
res.sendStatus(400);
});
// Supply frontend files if any other url
// is requested to make vue router work
app.use("/", express.static("../dist"));
app.use("/*", express.static("../dist"));
app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
});