summary refs log tree commit diff
path: root/src/api/routes.js
blob: b91e7ba66754a9ee1d1aaaf0d5d139ca5daab400 (plain) (blame)
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
import * as routes from './routes/index.js';
import * as url from 'node:url';
import express from 'express';

function logHttpEntry(method, route, routeMethod) {
    if (routeMethod.description) console.log('%', '#', routeMethod.description);

    console.log('%', method, '{{baseUrl}}' + route, 'HTTP/1.1');
    if (routeMethod.exampleHeaders) {
        for (var key of Object.keys(routeMethod.exampleHeaders)) {
            console.log('%', `${key}: ${routeMethod.exampleHeaders[key]}`);
        }
    }
    if (routeMethod.exampleBody) {
        console.log('%', 'Content-Type: application/json');
        console.log('% ');
        console.log(
            '%',
            JSON.stringify(routeMethod.exampleBody, null, 4).replaceAll(
                '\n',
                '\n% '
            )
        );
        console.log('% ');
    }
    console.log('% ');
    console.log('%', '###');
}

export function registerRoutes(app) {
    // http file header:
    console.log('%', '');
    let routeCount = 0;

    Object.keys(routes).forEach(routeName => {
        /**
         * @type {RouteDescription}
         */
        const route = routes[routeName];
        if (route === undefined) return;

        Object.keys(route.methods).forEach(routeMethodName => {
            /**
             * @type {RouteMethod}
             */
            const routeMethod = route.methods[routeMethodName];
            if (routeMethod === undefined) return;

            console.log(
                'Registering',
                routeMethodName.toUpperCase(),
                route.path
            );
            logHttpEntry(
                routeMethodName.toUpperCase(),
                route.path,
                routeMethod
            );
            app[routeMethodName](route.path, [
                ...routeMethod.middlewares,
                routeMethod.method
            ]);
            routeCount++;
        });
    });

    console.log(`Registered ${routeCount} routes.`);
}

if (import.meta.url.startsWith('file:')) {
    const modulePath = url.fileURLToPath(import.meta.url);
    if (process.argv[1] === modulePath) {
        const app = express();
        registerRoutes(app);
        process.exit(1);
    }
}