openapi-mock-generator-cli
Version:
CLI tool to generate mock data from OpenAPI specifications.
117 lines (116 loc) • 5.54 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseOpenApiDocument = parseOpenApiDocument;
exports.containsSchema = containsSchema;
exports.containsComponentSchemas = containsComponentSchemas;
exports.getOpenApiSchema = getOpenApiSchema;
exports.getOpenApiSchemasByResponses = getOpenApiSchemasByResponses;
exports.extractOpenApiSchemas = extractOpenApiSchemas;
const logger_1 = require("../helppers/logger");
const swagger_parser_1 = __importDefault(require("@apidevtools/swagger-parser"));
const types_utils_1 = require("@migudevelop/types-utils");
/**
* Parses an OpenAPI document from the given file path.
* @param {string} filePath - The path to the OpenAPI document file.
* @returns {Promise<OpenAPIV3.Document>} The parsed OpenAPI document.
* @throws Will throw an error if the document cannot be parsed.
*/
function parseOpenApiDocument(filePath) {
return __awaiter(this, void 0, void 0, function* () {
try {
const api = (yield swagger_parser_1.default.parse(filePath));
return api;
}
catch (error) {
console.error('Error parsing OpenAPI document:', error);
throw error;
}
});
}
/**
* Checks if a response object contains a schema in the 'application/json' content type.
* @param {OpenAPIV3.ResponseObject} response - The OpenAPI response object.
* @returns {boolean} True if the response contains a schema, false otherwise.
*/
function containsSchema(response) {
var _a, _b;
return !!((_b = (_a = response === null || response === void 0 ? void 0 : response.content) === null || _a === void 0 ? void 0 : _a['application/json']) === null || _b === void 0 ? void 0 : _b.schema);
}
/**
* Checks if an OpenAPI document contains component schemas.
* @param {OpenAPIV3.Document} response - The OpenAPI document.
* @returns {boolean} True if the document does not contain component schemas, false otherwise.
*/
function containsComponentSchemas(response) {
var _a;
return (0, types_utils_1.isNullish)((_a = response === null || response === void 0 ? void 0 : response.components) === null || _a === void 0 ? void 0 : _a.schemas);
}
/**
* Retrieves the schema from a response object in the 'application/json' content type.
* @template T - The type of the OpenAPI response object.
* @param {T} response - The OpenAPI response object.
* @returns {OpenAPIV3.SchemaObject | undefined} The schema object, or undefined if not found.
*/
function getOpenApiSchema(response) {
var _a;
return (_a = response === null || response === void 0 ? void 0 : response.content) === null || _a === void 0 ? void 0 : _a['application/json'].schema;
}
/**
* Extracts schemas from the responses of an OpenAPI operation.
* @template T - The type of the OpenAPI responses object.
* @param {T} responses - The OpenAPI responses object.
* @param {string} method - The HTTP method of the operation.
* @param {string} path - The path of the operation.
* @returns {OpenAPIV3.SchemaObject[]} An array of schema objects found in the responses.
*/
function getOpenApiSchemasByResponses(responses, method, path) {
const schemas = [];
for (const statusCode in responses) {
const response = responses[statusCode];
if (containsSchema(response)) {
const schema = getOpenApiSchema(response);
schemas.push(schema);
logger_1.Logger.success(`Found schema for ${method.toUpperCase()} with ${statusCode} code in ${path}`);
}
else {
logger_1.Logger.warn(`No schema found for ${method.toUpperCase()} with ${statusCode} code in ${path}`);
}
}
return schemas;
}
/**
* Extracts component schemas from an OpenAPI document file.
* @param {string} filePath - The path to the OpenAPI document file.
* @returns {Promise<OpenAPIV3.SchemaObject | undefined>} The extracted schemas, or undefined if not found.
* @throws Will throw an error if the document cannot be parsed.
*/
function extractOpenApiSchemas(filePath) {
return __awaiter(this, void 0, void 0, function* () {
try {
const api = yield parseOpenApiDocument(filePath);
if (!containsComponentSchemas(api) && !(0, types_utils_1.isNullish)(api === null || api === void 0 ? void 0 : api.components)) {
logger_1.Logger.info('Extracting schemas from components...');
return api.components.schemas;
}
else {
logger_1.Logger.warn('No schemas found in components.');
}
}
catch (error) {
logger_1.Logger.error('Error parsing OpenAPI document:', error);
throw error;
}
});
}