1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
| import fs from 'fs'; import axios from 'axios'; import type { OpenApi, OpenApiReference, OpenApiSchema, OpenApiOperation, OpenApiResponse, OpenApiMediaType, OpenApiRequestBody, OpenApiResponses } from 'openapi-v3';
const genericityList: string[] = ['ListResult', 'Result', 'PageResult', 'PageData', 'TreeNodeResult']; const typeMapping: Record<string, string> = { 'integer': 'number', 'Integer': 'number', };
let tsContent = `import axios from 'axios'; import type { Result, ListResult, PageResult, TreeNodeResult } from '@/core/types/global';\n\n`;
function generateType(openapi: OpenApi): string { let typeContent = ''; if (!openapi.components?.schemas) { return typeContent; } Object.entries(openapi.components.schemas).forEach(([typeName, schema]) => { if (shouldSkipType(typeName)) { return; }
schema = schema as OpenApiSchema; const properties = schema.properties || {}; const requiredFields = schema.required || [];
const paramsTypeDefinition = Object.entries(properties) .map(([name, prop]) => { const required = requiredFields.includes(name) ? '' : '?'; return `${name}${required}: ${getPropertyType(prop)};`; }) .join('\n ');
typeContent += `export interface ${typeName} {\n ${paramsTypeDefinition}\n}\n\n`; }); return typeContent; }
function generateApi(openapi: OpenApi): string { let apiContent = ''; Object.entries(openapi.paths).forEach(([path, methods]) => { Object.entries(methods as Record<string, OpenApiOperation>).forEach(([method, operation]) => { const operationId = operation.operationId; const summary = operation.summary || operation.description; const requestBody = operation.requestBody as OpenApiRequestBody; const responses = operation.responses as OpenApiResponses;
let requestType = ''; if (requestBody?.content) { for (const contentType in requestBody.content) { if (requestBody.content[contentType].schema) { const requestBodySchema = requestBody.content[contentType].schema as OpenApiReference; const ref = requestBodySchema.$ref; if (ref) { const parts = ref.split('/'); requestType = parts[parts.length - 1]; requestType = handleSpecialTypes(openapi, requestType); } break; } } }
let responseType = ''; const response200 = responses['200'] as OpenApiResponse; for (const contentType in response200.content) { const mediaType = response200.content[contentType] as OpenApiMediaType; if (mediaType.schema) { const responseSchema = mediaType.schema as OpenApiReference; const ref = responseSchema.$ref; if (ref) { const parts = ref.split('/'); responseType = parts[parts.length - 1]; responseType = handleSpecialTypes(openapi, responseType); } break; } }
const functionName = operationId && operationId.replace(/[^\w]/g, '');
const functionComment = `/**\n * ${summary}\n */`;
const paramsType = requestType ? `params: ${requestType}` : 'params?: any'; const responseTypeDefinition = responseType ? `Promise<${responseType}>` : 'Promise<any>'; const axiosConfig = method.toLowerCase() === 'get' ? '{ params }' : 'params'; const functionDefinition = `${functionComment}\nexport function ${functionName}(\n ${paramsType}\n): ${responseTypeDefinition} {\n return axios.${method.toLowerCase()}('${path}', ${axiosConfig});\n}\n\n`;
apiContent += functionDefinition; }); }); return apiContent; }
function getPropertyType(property: OpenApiSchema | OpenApiReference): string { if ('type' in property && property.type === 'array' && property.items) { return `${getPropertyType(property.items)}[]`; } if ('type' in property && property.type === 'object' && property.properties) { return `{ ${Object.entries(property.properties).map(([name, prop]) => `${name}: ${getPropertyType(prop)}`).join(', ')} }`; } if ('type' in property && property.type && typeMapping[property.type]) { return typeMapping[property.type]; } if ((property as OpenApiReference).$ref) { const ref = (property as OpenApiReference).$ref || ''; const parts = ref.split('/'); const refType = parts[parts.length - 1]; return refType; } return 'type' in property && property.type || 'any'; }
function shouldSkipType(typeName: string): boolean { return genericityList.some(item => typeName.startsWith(item)); }
function handleSpecialTypes(openapi: OpenApi, typeName: string): string { genericityList.forEach(item => { if (typeName.startsWith(item)) { typeName = `${item}<${getInnerType(openapi, typeName, item)}>`; } }); return typeName; }
function getInnerType(openapi: OpenApi, typeName: string, prefix: string): string { const innerType = typeName.substring(prefix.length); if (typeMapping[innerType]) { return typeMapping[innerType]; }
if (openapi.components?.schemas) { const ref = openapi.components.schemas[innerType as a]; type a = keyof typeof openapi.components.schemas if (ref) { return innerType; } }
return innerType.charAt(0).toLowerCase() + innerType.slice(1); }
const username: string = 'aaa'; const password: string = '111'; async function getOpenApiDoc() { const res = await axios.get<OpenApi>('https://aaa.com/v3/api-docs/app', { headers: { 'Authorization': `Basic ${btoa(`${username}:${password}`)}` } }); const openapi = res.data tsContent += generateType(openapi); tsContent += generateApi(openapi);
const outputFile = 'generated-api.ts'; fs.writeFile(outputFile, tsContent, (err) => { if (err) { console.error(`写入文件时出错: ${err}`); } else { console.log(`TypeScript Axios 接口已生成到 ${outputFile}`); } }); }
getOpenApiDoc();
|