UNPKG

openapi-mock-generator-cli

Version:
68 lines (67 loc) 2.82 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateSchemaMocksWithRelations = generateSchemaMocksWithRelations; exports.applyRelations = applyRelations; exports.mergeSchemaArray = mergeSchemaArray; const json_schema_faker_1 = require("json-schema-faker"); const faker_1 = require("@faker-js/faker"); const types_utils_1 = require("@migudevelop/types-utils"); json_schema_faker_1.JSONSchemaFaker.extend('faker', () => faker_1.faker); /** * Generates mock data for all schemas in the OpenAPI document. * @param schemas - The schemas to generate mocks for. * @param count - The number of mock objects to generate for each schema. * @returns A cache of mock data for each schema. */ function generateSchemaMocksWithRelations(schemas, count = 10) { const cache = {}; // Generate mocks for each schema for (const [name, schema] of Object.entries(schemas)) { cache[name] = Array.from({ length: count }, () => json_schema_faker_1.JSONSchemaFaker.generate(schema)); } // Apply relations between schemas for (const [name, mocks] of Object.entries(cache)) { cache[name] = mocks.map((mock) => applyRelations(mock, schemas, cache)); } return cache; } /** * Applies relations between mock data based on schema definitions. * @param mock - The mock object to process. * @param schemas - The schemas used to generate the mocks. * @param cache - The cache of generated mock data. * @returns The mock object with relations applied. */ function applyRelations(mock, schemas, cache) { for (const [key, value] of Object.entries(mock)) { if ((0, types_utils_1.isString)(value) && key.toLocaleLowerCase() != 'id' && key.toLocaleLowerCase().endsWith('id')) { const relatedName = key .toLocaleLowerCase() .trim() .replace('id', '') .replace(/[^a-zA-Z0-9 ]/g, ''); const targetSchema = Object.keys(schemas).find((schema) => schema.toLowerCase() === relatedName.toLowerCase()); if (targetSchema && cache[targetSchema]) { mock[key] = cache[targetSchema][Math.floor(Math.random() * cache[targetSchema].length)].id; } } } return mock; } /** * Merges an array of schema objects into a single schema object. * @param schemaArray - The array of schema objects to merge. * @returns A merged schema object containing all properties from the input array. */ function mergeSchemaArray(schemaArray) { const merged = {}; for (const schemaObject of schemaArray) { for (const [key, value] of Object.entries(schemaObject)) { merged[key] = Object.assign(Object.assign({}, value), merged[key]); } } return merged; }