directus

Форк
0
65 строк · 2.0 Кб
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';
7

8
export function registerRouteGenerator(endpointName: string, endpointRouter: Router) {
9
	const router = express.Router();
10

11
	endpointRouter.use(`/${endpointName}`, router);
12

13
	const registerRoute = (
14
		path: Reference<string>,
15
		method: Reference<'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'>,
16
		cb: Reference<
17
			(req: {
18
				url: string;
19
				headers: IncomingHttpHeaders;
20
				body: string;
21
			}) => { status: number; body: string } | Promise<{ status: number; body: string }>
22
		>,
23
	) => {
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');
27

28
		const pathCopied = path.copySync();
29
		const methodCopied = method.copySync();
30

31
		const handler: RequestHandler = asyncHandler(async (req, res) => {
32
			const request = { url: req.url, headers: req.headers, body: req.body };
33

34
			const response = await callReference(cb, [request]);
35

36
			const responseCopied = await response.copy();
37

38
			res.status(responseCopied.status).send(responseCopied.body);
39
		});
40

41
		switch (methodCopied) {
42
			case 'GET':
43
				router.get(pathCopied, handler);
44
				break;
45
			case 'POST':
46
				router.post(pathCopied, handler);
47
				break;
48
			case 'PUT':
49
				router.put(pathCopied, handler);
50
				break;
51
			case 'PATCH':
52
				router.patch(pathCopied, handler);
53
				break;
54
			case 'DELETE':
55
				router.delete(pathCopied, handler);
56
				break;
57
		}
58
	};
59

60
	const unregisterFunction = () => {
61
		endpointRouter.stack = endpointRouter.stack.filter((layer) => router !== layer.handle);
62
	};
63

64
	return { register: registerRoute, unregisterFunction };
65
}
66

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.