openapi-ts-mock-generator
Version:
typescript mock data generator based openapi
177 lines (173 loc) • 6.12 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
// src/core/config.ts
import { Faker, ko } from "@faker-js/faker";
var FAKER_SEED = 1;
var faker = new Faker({
locale: [ko]
});
faker.seed(FAKER_SEED);
// src/utils/code-utils.ts
var toTypeScriptCode = (param, options) => {
const { depth = 0, isStatic } = options;
const prefixSpace = " ".repeat(depth * 2);
if (param === null) {
return "null";
}
if (Array.isArray(param)) {
const results = param.map((elem) => toTypeScriptCode(elem, __spreadProps(__spreadValues({}, options), { depth: depth + 1 }))).join(",\n" + prefixSpace);
return ["[", results, "]"].join("\n" + prefixSpace);
}
if (typeof param === "object") {
const results = Object.entries(param).map(([key, value]) => {
return generateObjectProperty(key, value, options, prefixSpace);
}).join("\n" + prefixSpace);
return ["{", `${results}`, "}"].join("\n" + prefixSpace);
}
if (typeof param === "string") {
if (isStatic === false && (param.startsWith("faker") || param.startsWith("Buffer.from(faker"))) {
return param;
}
if (param.endsWith(" as const")) {
return `"${param.slice(0, -" as const".length)}" as const`;
}
}
return JSON.stringify(param);
};
var shouldApplyNullableExtension = (value, isOptional) => {
if (!isOptional)
return false;
if (value === null)
return true;
if (typeof value === "string" && value.includes(",null")) {
return true;
}
return false;
};
var generateObjectProperty = (key, value, options, prefixSpace) => {
const { isOptional, depth = 0 } = options;
const shouldApplyNullable = shouldApplyNullableExtension(value, isOptional);
const nullableTypeExtensionStart = shouldApplyNullable ? `...(faker.datatype.boolean() ? {
${prefixSpace}` : "";
const nullableTypeExtensionEnd = shouldApplyNullable ? `
${prefixSpace}} : {})` : "";
const propertyValue = toTypeScriptCode(value, __spreadProps(__spreadValues({}, options), {
depth: depth + 1
}));
return `${nullableTypeExtensionStart}${prefixSpace}${key}: ${propertyValue}${nullableTypeExtensionEnd},`;
};
// src/utils/file-utils.ts
import { existsSync, mkdirSync, writeFileSync, rmSync, readdirSync, readFileSync } from "fs";
var readJsonFile = (filePath, defaultValue) => {
if (!existsSync(filePath)) {
return defaultValue;
}
try {
const content = readFileSync(filePath, "utf-8");
return JSON.parse(content);
} catch (error) {
console.warn(`Failed to read JSON file ${filePath}:`, error);
return defaultValue;
}
};
// src/parsers/faker-parser.ts
import { join } from "path";
var specialFakerParser = (options) => {
var _a, _b;
if (options.specialPath === void 0)
return {
titleSpecial: {},
descriptionSpecial: {}
};
const titlePath = join((_a = options.baseDir) != null ? _a : "", options.specialPath, "titles.json");
const descPath = join((_b = options.baseDir) != null ? _b : "", options.specialPath, "descriptions.json");
const titleSpecialKey = readJsonFile(titlePath, {});
const descriptionSpecialKey = readJsonFile(descPath, {});
const titleSpecial = Object.entries(titleSpecialKey).reduce((acc, [key, value]) => {
const fakerValue = getFakerValue(value, options);
acc[key] = fakerValue;
return acc;
}, {});
const descriptionSpecial = Object.entries(descriptionSpecialKey).reduce((acc, [key, value]) => {
const fakerValue = getFakerValue(value, options);
acc[key] = fakerValue;
return acc;
}, {});
return { titleSpecial, descriptionSpecial };
};
var getFakerValue = (value, options) => {
if ("value" in value) {
return value.value;
}
if ("module" in value && "type" in value) {
if (options.isStatic === false) {
const fakerOption = "options" in value ? toTypeScriptCode(value.options, __spreadValues({
depth: 0
}, options)) : "";
return `faker.${value.module}.${value.type}(${fakerOption})`;
}
const fakerModule = faker[value.module];
if (fakerModule === void 0) {
console.warn("can't find faker module", fakerModule);
return void 0;
}
const fakerFunc = fakerModule[value.type];
if (fakerFunc === void 0 || typeof fakerFunc !== "function") {
console.warn("can't find faker function", fakerFunc);
return void 0;
}
return "options" in value ? fakerFunc(value.options) : fakerFunc();
}
return void 0;
};
var validateFakerModule = (moduleName) => {
return moduleName in faker;
};
var validateFakerFunction = (moduleName, functionName) => {
try {
const fakerModule = faker[moduleName];
return typeof (fakerModule == null ? void 0 : fakerModule[functionName]) === "function";
} catch (e) {
return false;
}
};
var getAvailableFakerModules = () => {
return Object.keys(faker).filter((key) => typeof faker[key] === "object");
};
var getAvailableFakerFunctions = (moduleName) => {
try {
const fakerModule = faker[moduleName];
if (!fakerModule)
return [];
return Object.keys(fakerModule).filter(
(key) => typeof fakerModule[key] === "function"
);
} catch (e) {
return [];
}
};
export {
getAvailableFakerFunctions,
getAvailableFakerModules,
specialFakerParser,
validateFakerFunction,
validateFakerModule
};
//# sourceMappingURL=faker-parser.mjs.map