WebService-Boilerplate/app.js

88 lines
1.7 KiB
JavaScript

/**
* @file Main entry point for the application backend.
*/
import express from "express";
import path from "path";
import cors from "cors";
import passport from "passport";
import BearerStrategy from "passport-http-bearer";
import spaRouter from "./routers/spaRouter.js";
import api_v1_Router from "./routers/api_v1_Router.js";
import expressListRoutes from "express-list-routes";
import AuthService from "./modules/Auth/AuthService";
/**
* The port the server will listen on.
* @type {number}
*/
const port = process.env.PORT || 3000;
/**
* The path to the distribution directory.
* @type {string}
*/
const distPath = path.join(path.resolve(), "dist");
/**
* The Express application instance.
* @type {express.Application}
*/
const app = express();
app.use(express.json());
/**
* Serves static files from the distribution directory in production, or the current working directory in development.
*/
if (process.env.NODE_ENV === "production") {
app.use("/", express.static(distPath));
} else {
app.use(express.static(path.join(process.cwd())));
}
/**
* Authentication middlewares
*/
app.use(cors());
passport.use(new BearerStrategy(AuthService.auth))
/**
* Mounts the API v1 router at the `/api/v1` endpoint.
*/
app.use("/api/v1", api_v1_Router);
/**
* Handles requests to the `/api` endpoint that don't match any existing routes.
* Responds with a 404 error.
*/
app.use("/api", (req, res) => {
res.status(404).json({error: 404});
});
/**
* Mounts the SPA router.
*/
app.use(spaRouter);
/**
* Starts the server and listens for incoming requests on the specified port.
*/
app.listen(port, () => {
console.log("Server listening on port", port);
});
expressListRoutes(app);