UNCLASSIFIED - NO CUI

Skip to content
Snippets Groups Projects
Code owners
Assign users and groups as approvers for specific file changes. Learn more.
app.js 1.69 KiB
const express = require('express');
const { runMigrations } = require('./data/dataLayer');
const { getHealth, getVersion, getUser } = require('./controller/controller.js');
const app = express();
const port = 8000;

// This middleware logs every incoming request with the current timestamp, HTTP method, and URL path.
app.use((req, res, next) => {
    const timestamp = new Date().toISOString();
    console.log(`[${timestamp}] ${req.method} ${req.originalUrl}`);
    next();
});

// Basic route to test whether the API is alive and reachable.
app.get('/api', async (req, res) => {
    res.send('Hello World! at specific path /api');
});

app.get('/api/health', getHealth);
app.get('/api/me', getUser);
app.get('/api/version', getVersion);

// This route handles all other paths not previously defined by returning a 404.
app.all('*', async (req, res) => {
    res.status(404).send(`Not found: ${req.path}`);
});

// This middleware catches any errors that occur in the request processing pipeline.
// It logs the error details and sends a 500 Internal Server Error response.
// Consider expanding on this to inspect the error and return a status code based on known error conditions,
// or keep it as a failsafe to ensure sensitive information about the system is not returned.
app.use(async (err, req, res, next) => {
    const timestamp = new Date().toISOString();
    console.error(`[${timestamp}] Error: ${err.message}`);
    console.error(err.stack);
    res.status(500).send('Internal Server Error');
});

// Run database migrations to ensure the database is up to date, then start the api server.
runMigrations().then(
    app.listen(port, () => {
        console.log(`App is running at http://localhost:${port}`);
    })
);