@sasonarik/nextapi-swagger
Version:
CLI tool to generate Next.js API routes and types from Swagger/OpenAPI specs
36 lines (35 loc) • 1.65 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateRoutes = generateRoutes;
const fs_extra_1 = __importDefault(require("fs-extra"));
const path_1 = __importDefault(require("path"));
const routeHandlerBuilder_1 = require("./routeHandlerBuilder");
async function generateRoutes(spec, apiBasePath, options, baseName) {
for (const [route, methods] of Object.entries(spec.paths || {})) {
for (const [method, operation] of Object.entries(methods ?? {})) {
if (!operation || typeof operation !== "object")
continue;
const methodUpper = method.toUpperCase();
const normalizedRoute = route.startsWith("/api/")
? route.slice(4)
: route;
const urlPath = normalizedRoute
.replace(/{(.*?)}/g, "[$1]")
.replace(/^\/|\/$/g, "");
const segments = urlPath ? urlPath.split("/") : [];
const outDir = path_1.default.join(apiBasePath, ...segments);
const outPath = path_1.default.join(outDir, "route.ts");
const handlerCode = (0, routeHandlerBuilder_1.generateHandlerForMethod)({
method: methodUpper,
route,
operation: operation,
baseName,
});
await fs_extra_1.default.ensureDir(path_1.default.dirname(outPath));
await fs_extra_1.default.writeFile(outPath, handlerCode.trimStart());
}
}
}