UNPKG

@common-grants/cli

Version:
66 lines (65 loc) 2.76 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.DefaultPreviewService = void 0; const express_1 = __importDefault(require("express")); const swagger_ui_express_1 = __importDefault(require("swagger-ui-express")); const promises_1 = require("fs/promises"); const js_yaml_1 = __importDefault(require("js-yaml")); class DefaultPreviewService { async createPreviewApp(specPath) { const app = (0, express_1.default)(); const openapiSpec = await this.getOpenApiSpec(specPath); app.use("/", swagger_ui_express_1.default.serve, swagger_ui_express_1.default.setup(openapiSpec, { explorer: false, })); return app; } async previewSpec(specPath) { const app = await this.createPreviewApp(specPath); const port = 3000; try { const server = app.listen(port, () => { console.log(`Preview server running at http://localhost:${port}`); }); // Handle server shutdown process.on("SIGINT", () => { server.close(() => { console.log("\nPreview server stopped"); process.exit(0); }); }); } catch (error) { console.error("Failed to start preview server:", error); throw error; } } async getOpenApiSpec(specPath) { try { const specContent = await (0, promises_1.readFile)(specPath, "utf-8"); const spec = js_yaml_1.default.load(specContent); // parses YAML or JSON string content if (!spec || typeof spec !== "object") { throw new Error("Invalid OpenAPI specification format"); } return spec; } catch (error) { if (error instanceof Error) { // Check if the error is a file not found error if (error.message.includes("ENOENT")) { throw new Error(`File not found: ${specPath}\nPlease check that the file exists and you have the correct path.`); } // For YAML parsing errors, provide a more helpful message if (error.message.includes("yaml")) { throw new Error(`Failed to parse OpenAPI specification: The file is not valid YAML/JSON format.\nError: ${error.message}`); } throw new Error(`Failed to load OpenAPI specification: ${error.message}`); } throw error; } } } exports.DefaultPreviewService = DefaultPreviewService;