production-evyos-systems-an.../ServicesApi/src/utils/extract-routes.ts

96 lines
2.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { INestApplication, RequestMethod } from '@nestjs/common';
import { ModulesContainer, Reflector } from '@nestjs/core';
import { PATH_METADATA, METHOD_METADATA } from '@nestjs/common/constants';
import { PrismaService } from '@/src/prisma.service';
/**
* Helper: Method string'i döndür
*/
function getMethodString(requestMethod: RequestMethod): string {
return RequestMethod[requestMethod];
}
/**
* Helper: Path'leri normalize et (iki tane slash varsa düzelt)
*/
function normalizePath(...paths: string[]): string {
const normalized =
'/' +
paths
.filter(Boolean)
.map((p) => p.replace(/^\/|\/$/g, ''))
.filter((p) => p.length > 0)
.join('/');
return normalized === '/' ? '' : normalized; // Home route'ı dışla
}
export async function extractAndPersistRoutes(
app: INestApplication,
prisma: PrismaService,
): Promise<{ method: string; url: string }[]> {
const modulesContainer = app.get(ModulesContainer);
const reflector = app.get(Reflector);
const routes: { method: string; url: string }[] = [];
modulesContainer.forEach((moduleRef) => {
const controllers = [...moduleRef.controllers.values()];
controllers.forEach(({ metatype }) => {
if (!metatype || typeof metatype !== 'function') return;
const controllerPath =
reflector.get<string>(PATH_METADATA, metatype) ?? '';
const prototype = metatype.prototype;
const methodNames = Object.getOwnPropertyNames(prototype).filter(
(m) => m !== 'constructor',
);
methodNames.forEach((methodName) => {
const methodRef = prototype[methodName];
const routePath = reflector.get<string>(PATH_METADATA, methodRef);
const requestMethod = reflector.get<RequestMethod>(
METHOD_METADATA,
methodRef,
);
if (routePath !== undefined && requestMethod !== undefined) {
const method = getMethodString(requestMethod);
const fullPath = normalizePath(controllerPath, routePath);
if (fullPath !== '') {
routes.push({ method, url: fullPath });
}
}
});
});
});
const existing = await prisma.endpoint_restriction.findMany({
select: { endpoint_name: true, endpoint_method: true },
});
const existingSet = new Set(
existing.map((r) => `${r.endpoint_method}_${r.endpoint_name}`),
);
const newOnes = routes.filter(
(r) => !existingSet.has(`${r.method}_${r.url}`),
);
// İsteğe bağlı: veritabanına kaydet
// for (const route of newOnes) {
// await prisma.endpoint_restriction.create({
// data: {
// endpoint_method: route.method,
// endpoint_name: route.url,
// is_active: true,
// },
// });
// }
console.log('🧭 Route JSON Listesi:');
console.dir(routes, { depth: null });
return routes;
}