36 lines
1.6 KiB
JavaScript
36 lines
1.6 KiB
JavaScript
const { readFileSync, readdirSync } = require('node:fs');
|
|
const { join } = require('node:path');
|
|
const { apiEndpoints } = require('../lib/api/endpoints');
|
|
|
|
function controllers(directory) {
|
|
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
|
|
const path = join(directory, entry.name);
|
|
return entry.isDirectory() ? controllers(path) : path.endsWith('.controller.ts') ? [path] : [];
|
|
});
|
|
}
|
|
|
|
const routes = controllers(join(__dirname, '../../src')).flatMap((file) => {
|
|
const source = readFileSync(file, 'utf8');
|
|
const prefix = source.match(/@Controller\(\s*['"]([^'"]*)['"]\s*\)/)?.[1];
|
|
if (prefix === undefined) return [];
|
|
return Array.from(source.matchAll(/@(Get|Post|Patch|Delete|Put)\(\s*(?:['"]([^'"]*)['"])?\s*\)/g), (match) => {
|
|
const path = '/' + [prefix, match[2]].filter(Boolean).join('/');
|
|
return new RegExp('^' + path.split('/').map((segment) => segment.startsWith(':') ? '[^/]+' : segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('/') + '/?$');
|
|
});
|
|
});
|
|
|
|
function endpoints(value, prefix = '') {
|
|
return Object.entries(value).flatMap(([name, endpoint]) => {
|
|
const label = `${prefix}${name}`;
|
|
if (typeof endpoint === 'object') return endpoints(endpoint, `${label}.`);
|
|
const path = typeof endpoint === 'function' ? (endpoint.length ? endpoint('test-id') : endpoint()) : endpoint;
|
|
return [[label, path.split('?')[0]]];
|
|
});
|
|
}
|
|
|
|
describe('Dashboard/backend endpoint paths', () => {
|
|
test.each(endpoints(apiEndpoints))('%s maps to a backend controller (%s)', (_name, path) => {
|
|
expect(routes.some((route) => route.test(path))).toBe(true);
|
|
});
|
|
});
|