1
import type { RequestHandler, Router } from 'express';
2
import express from 'express';
3
import type { Reference } from 'isolated-vm';
4
import type { IncomingHttpHeaders } from 'node:http';
5
import asyncHandler from '../../../../utils/async-handler.js';
6
import { callReference } from './call-reference.js';
8
export function registerRouteGenerator(endpointName: string, endpointRouter: Router) {
9
const router = express.Router();
11
endpointRouter.use(`/${endpointName}`, router);
13
const registerRoute = (
14
path: Reference<string>,
15
method: Reference<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'>,
19
headers: IncomingHttpHeaders;
21
}) => { status: number; body: string } | Promise<{ status: number; body: string }>
24
if (path.typeof !== 'string') throw new TypeError('Route path has to be of type string');
25
if (method.typeof !== 'string') throw new TypeError('Route method has to be of type string');
26
if (cb.typeof !== 'function') throw new TypeError('Route handler has to be of type function');
28
const pathCopied = path.copySync();
29
const methodCopied = method.copySync();
31
const handler: RequestHandler = asyncHandler(async (req, res) => {
32
const request = { url: req.url, headers: req.headers, body: req.body };
34
const response = await callReference(cb, [request]);
36
const responseCopied = await response.copy();
38
res.status(responseCopied.status).send(responseCopied.body);
41
switch (methodCopied) {
43
router.get(pathCopied, handler);
46
router.post(pathCopied, handler);
49
router.put(pathCopied, handler);
52
router.patch(pathCopied, handler);
55
router.delete(pathCopied, handler);
60
const unregisterFunction = () => {
61
endpointRouter.stack = endpointRouter.stack.filter((layer) => router !== layer.handle);
64
return { register: registerRoute, unregisterFunction };