UNPKG

openapi-ts-mock-generator

Version:
158 lines (156 loc) 5.87 kB
// 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); var GEN_COMMENT = "/* Do not edit this file. */\n/* This file generated by openapi-ts-mock-generator. */\n\n"; // src/utils/file-utils.ts import { existsSync, mkdirSync, writeFileSync, rmSync, readdirSync, readFileSync } from "fs"; import * as path from "path"; var ensureDir = (dirPath) => { if (!existsSync(dirPath)) { mkdirSync(dirPath, { recursive: true }); } }; var clearDirectory = (dirPath) => { if (existsSync(dirPath)) { readdirSync(dirPath).forEach((file) => { rmSync(path.join(dirPath, file)); }); } }; var safeWriteFile = (filePath, content) => { const dir = path.dirname(filePath); ensureDir(dir); writeFileSync(filePath, content); }; // src/generators/handler-generator.ts import { camelCase, pascalCase } from "change-case-all"; import * as path2 from "path"; var generateHandlers = (paths, options) => { const firstTags = Array.from(new Set(paths.map((path3) => path3.tags[0]))); const handlersPerTag = firstTags.reduce((acc, tag) => { acc[tag] = []; return acc; }, {}); paths.forEach((path3) => { const handler = generateSingleHandler(path3, options); handlersPerTag[path3.tags[0]].push(handler); }); writeHandlerFiles(handlersPerTag, options); }; var generateSingleHandler = (path3, options) => { var _a; const codeBaseArray = [` http.${path3.method}(\`\${handlerUrl}${path3.pathname}\`, () => {`]; if (path3.responses.length === 1) { const res = path3.responses[0]; if (((_a = res.schema) == null ? void 0 : _a.type) === "ref") { const schemaName = pascalCase(res.schema.value.$ref.replace("#/components/schemas/", "")); codeBaseArray.push(` // Schema is ${schemaName}`); } const outputResName = `get${pascalCase(path3.operationId)}${res.statusCode}`; codeBaseArray.push(` return HttpResponse.json(${outputResName}(), {`); codeBaseArray.push(` status: ${res.statusCode},`); codeBaseArray.push(` })`); } else if (path3.responses.length > 1) { codeBaseArray.push(` const responses = [`); path3.responses.forEach((res) => { var _a2; const schemaName = ((_a2 = res.schema) == null ? void 0 : _a2.type) === "ref" ? pascalCase(res.schema.value.$ref.replace("#/components/schemas/", "")) : ""; const schemaComment = schemaName ? ` // Schema is ${schemaName}` : ""; const outputResName = `get${pascalCase(path3.operationId)}${res.statusCode}`; codeBaseArray.push( ` [${outputResName}(), { status: ${res.statusCode} }],${schemaComment}` ); }); codeBaseArray.push(` ]`); codeBaseArray.push(` const randomIndex = Math.floor(Math.random() * responses.length)`); codeBaseArray.push(` return HttpResponse.json(...responses[randomIndex])`); } else { codeBaseArray.push(` return HttpResponse.json()`); } codeBaseArray.push(` }),`); return codeBaseArray.join("\n"); }; var writeHandlerFiles = (handlersPerTag, options) => { var _a; const directory = path2.join(options.baseDir, "handlers"); ensureDir(directory); if (options.clear) { clearDirectory(directory); } Object.entries(handlersPerTag).forEach(([tag, handlers]) => { const content = generateHandlerFileContent(tag, handlers, options); const fileName2 = path2.join(directory, `${tag}.ts`); safeWriteFile(fileName2, content); console.log(`Generated Handler ${fileName2}`); }); const mockHandlersContent = generateMockHandlersFile(handlersPerTag, options); const fileName = path2.join((_a = options.baseDir) != null ? _a : "", "mockHandlers.ts"); safeWriteFile(fileName, mockHandlersContent); console.log(`Generated mock handlers ${fileName}`); }; var generateHandlerFileContent = (tag, handlers, options) => { const importMSW = `import { http, HttpResponse } from 'msw'`; const responseNames = handlers.reduce((acc, handler) => { const matched = handler.match(/get[A-Z]\w+/g); if (matched === null) return acc; return [...acc, ...matched]; }, []).join(", "); const importResponses = responseNames.length > 0 ? `import { ${responseNames} } from "../response" ` : ""; const handlerUrl = `const handlerUrl = "${options.handlerUrl}"`; const handlerName = camelCase(tag); const mockHandlers = [ `${importMSW}`, `${importResponses}`, `${handlerUrl}`, ``, `export const ${handlerName}Handlers = [`, `${handlers.join("\n\n")}`, `]` ].join("\n"); return GEN_COMMENT + mockHandlers; }; var generateMockHandlersFile = (handlersPerTag, options) => { const handlersImport = Object.keys(handlersPerTag).map((tag) => { const handlerName = `${camelCase(tag)}Handlers`; return `import { ${handlerName} } from "./handlers/${tag}"`; }).join("\n"); const handlersArrayItem = Object.keys(handlersPerTag).map((tag) => { const handlerName = `${camelCase(tag)}Handlers`; return ` ...${handlerName},`; }).join("\n"); const mockHandlers = [ `${handlersImport}`, ``, `export const handlers = [`, `${handlersArrayItem}`, `]` ].join("\n"); return GEN_COMMENT + mockHandlers; }; var generateHandlersForTag = (paths, tag, options) => { return paths.filter((path3) => path3.tags.includes(tag)).map((path3) => generateSingleHandler(path3, options)); }; var extractResponseNames = (handlers) => { return handlers.reduce((acc, handler) => { const matched = handler.match(/get[A-Z]\w+/g); if (matched === null) return acc; return [...acc, ...matched]; }, []); }; var generateHandlerName = (tag) => { return `${camelCase(tag)}Handlers`; }; export { extractResponseNames, generateHandlerName, generateHandlers, generateHandlersForTag }; //# sourceMappingURL=handler-generator.mjs.map