提交 10c38e9d authored 作者: 王绍森's avatar 王绍森

修改

上级 a4020e3c
...@@ -2,4 +2,5 @@ ...@@ -2,4 +2,5 @@
/models /models
/node_modules /node_modules
.DS_Store .DS_Store
api-doc.json api-doc.json
\ No newline at end of file /dist
\ No newline at end of file
...@@ -2,32 +2,46 @@ const fs = require('fs'); ...@@ -2,32 +2,46 @@ const fs = require('fs');
const path = require('path'); const path = require('path');
const { deleteFolderRecursive } = require('./utils'); const { deleteFolderRecursive } = require('./utils');
const { EROFS } = require('constants'); const { EROFS } = require('constants');
const { format } = require('path');
function formatModelName(str) {
if (!str) {
throw new Error('非法的model name: '+ str)
};
return str.replace(/[-\(\)\{\}]/g, '');
}
const directory = path.join(process.cwd(), 'dist');
function getSubType(subtye) { function getSubType(subtype, importedModels) {
// List«组织机构模型(OrgModel})» // List«组织机构模型(OrgModel})»
// 组织机构模型(OrgModel}) // 组织机构模型(OrgModel})
// Page«组织机构模型(OrgModel})» // Page«组织机构模型(OrgModel})»
// boolean // boolean
if (!subtye) { if (!subtype) {
console.error("subtype为空: ", subtye); console.error("subtype为空: ", subtype);
return; return;
} }
if (!subtye.includes('«')) { if (!subtype.includes('«')) {
let hasparent = subtye.match(/.*\((.+)\).*/) subtype = formatModelName(subtype)
if (hasparent) { if (!['boolean', 'number', 'boolean'].includes(subtype)) {
return hasparent[1] if (!importedModels.includes(subtype)) {
importedModels.push(subtype);
}
} }
return subtye return subtype;
}
if (subtype.startsWith('Page«')) {
return `{rows: ${getSubType(subtype.slice(5, -1), importedModels)}[], total: number | string}`;
} }
if (subtye.startsWith('Page«')) { if (subtype.startsWith('List«')) {
return `page<${getSubType(subtye.slice(5, -1))}>`; return `${getSubType(subtype.slice(5, -1), importedModels)}[]`;
} }
if (subtye.startsWith('List«')) { if (subtype.startsWith('Result«')) {
return `List<${getSubType(subtye.slice(5, -1))}>`; return getSubType(subtype.slice(7, -1), importedModels);
} }
if (subtye.startsWith('Result«')) { if (subtype.startsWith("Map«")) {
return `Result<${getSubType(subtye.slice(7, -1))}>`; const [keyType, valueType] = subtype.slice(4, -1).split(',');
return `{[${keyType}]: ${valueType}}`;
} }
throw new Error("为识别的subtype:" + subtye) throw new Error("为识别的subtype:" + subtye)
} }
...@@ -36,11 +50,11 @@ function getSubType(subtye) { ...@@ -36,11 +50,11 @@ function getSubType(subtye) {
* 获取ref的类型 * 获取ref的类型
* *
*/ */
function getTypeofDefinitions(ref) { function getTypeofDefinitions(ref, importedModels) {
// '#/definitions/Result«boolean»' // '#/definitions/Result«boolean»'
// '#/definitions/Result«List«资源管理模型(ModuleModel})»»' // '#/definitions/Result«List«资源管理模型(ModuleModel})»»'
// "#/definitions/资源管理新增参数模型" // "#/definitions/资源管理新增参数模型"
return getSubType(ref.replace('#/definitions/', '')); return getSubType(ref.replace('#/definitions/', ''), importedModels);
} }
function convertType(item, importedModels) { function convertType(item, importedModels) {
...@@ -52,7 +66,7 @@ function convertType(item, importedModels) { ...@@ -52,7 +66,7 @@ function convertType(item, importedModels) {
return convertType(item.items, importedModels) + '[]'; return convertType(item.items, importedModels) + '[]';
} }
if ($ref) { if ($ref) {
const typeofRef = getTypeofDefinitions($ref) const typeofRef = getTypeofDefinitions($ref, importedModels)
return typeofRef; return typeofRef;
} }
return type; return type;
...@@ -83,6 +97,7 @@ function getFields (properties, importedModels) { ...@@ -83,6 +97,7 @@ function getFields (properties, importedModels) {
function getModelInterface(title, name, properties) { function getModelInterface(title, name, properties) {
const imprtedModels = []; const imprtedModels = [];
name = formatModelName(name);
const titleComment = title ? ` const titleComment = title ? `
/** /**
...@@ -101,38 +116,18 @@ function getModelInterface(title, name, properties) { ...@@ -101,38 +116,18 @@ function getModelInterface(title, name, properties) {
} }
function generateModels(definitions) { function generateModels(definitions) {
const modelDirectory = path.resolve(__dirname, '../models');
if (!fs.existsSync(modelDirectory)) {
fs.mkdirSync(modelDirectory);
} else {
deleteFolderRecursive(modelDirectory);
fs.mkdirSync(modelDirectory);
}
const modelNames = Object.keys(definitions); const modelNames = Object.keys(definitions);
for (let index = 0; index < modelNames.length; index++) { for (let index = 0; index < modelNames.length; index++) {
const modelName = modelNames[index]; let modelName = modelNames[index];
// Page, Map, Result不用生成Model文件,用泛型处理 if (["Page«", "Result«", 'Map«'].some(prefix => modelName.startsWith(prefix))) {
if (['Page«', 'Map«', 'Result«'].some(i => modelName.startsWith(i))) continue; continue;
let title, name;
const { properties } = definitions[modelName];
// 模型中文名称加模型英文名称的类型, 比如:投票候选人(VoteCandidatesModel)
const match = modelName.match(/^(.+)\((.+)\)$/);
if (match) {
title = match[1];
name = match[2];
} else if (modelName) {
// modelName只是一个单词
name = modelName;
}
if (name) {
const modelCotent = getModelInterface(title, name, properties);
fs.writeFileSync(path.resolve(__dirname, `../models/${name}.ts`), modelCotent, {encoding: "utf-8"});
console.log('write model: ', name);
} }
const { title, properties, } = definitions[modelName]
modelName = formatModelName(modelName)
const modelCotent = getModelInterface(title, title, properties);
fs.writeFileSync(path.join(directory, `${modelName}.ts`), modelCotent, {encoding: "utf-8"});
console.log('write model: ', modelName);
} }
} }
...@@ -142,17 +137,13 @@ function generateModels(definitions) { ...@@ -142,17 +137,13 @@ function generateModels(definitions) {
* @param {*} parameters * @param {*} parameters
*/ */
function getParamsString(parameters, importedModels) { function getParamsString(parameters, importedModels) {
const parametersUsed = parameters ? parameters.filter(i => i.in !== 'header') : null; const parameter = parameters ? parameters.find(p => p.in === 'body' && p.name === 'param') : false;
const paramsString = parametersUsed ? parametersUsed.map(param => { let paramsString;
let fieldType = convertType(param, importedModels); if (parameter) {
if (fieldType) { paramsString = convertType(parameter.schema, importedModels);
console.error("函数参数类型获取失败:", param); }
}
return `${param.name}${param.required ? '' : '?'}: ${fieldType}`
}).join(', ') : null;
if (paramsString) { if (paramsString) {
return 'params: { ' + paramsString + ' }' return 'params: ' + paramsString + ''
} }
return ''; return '';
} }
...@@ -172,10 +163,10 @@ function getReturnType(schema, importedModels) { ...@@ -172,10 +163,10 @@ function getReturnType(schema, importedModels) {
function getApiMethods(apiMethodMap, apiName) { function getApiMethods(apiMethodMap, apiName) {
const importedModels = []; const importedModels = [];
let content = `import request from './request'`; let content = `\nimport request from './request'\n`;
const methodNames = Object.keys(apiMethodMap); const methodNames = Object.keys(apiMethodMap);
for (let index = 0; index < methodNames.length; index++) { for (let index = 0; index < methodNames.length; index++) {
const methodName = methodNames[index]; let methodName = methodNames[index];
const { post } = apiMethodMap[methodName]; const { post } = apiMethodMap[methodName];
if (!post) continue; if (!post) continue;
const { parameters, responses } = post; const { parameters, responses } = post;
...@@ -185,24 +176,20 @@ function getApiMethods(apiMethodMap, apiName) { ...@@ -185,24 +176,20 @@ function getApiMethods(apiMethodMap, apiName) {
console.log('response undefined: ', apiMethodMap[methodName]); console.log('response undefined: ', apiMethodMap[methodName]);
} }
const returnType = getReturnType(responses[200].schema, importedModels); const returnType = getReturnType(responses[200].schema, importedModels);
methodName = methodName === 'delete' ? 'deleteApi' : methodName;
content += ` content += `
\t export function ${methodName}(${paramsString}): Promise<${returnType}> { \t export function ${methodName}(${paramsString}): Promise<${returnType}> {
return request('/${apiName}/${methodName}', ${paramsString ? 'params' : ''}); return request(${paramsString ? 'params' : '{}'}, '/${apiName}/${methodName}');
} }
`; `;
} }
return importedModels.join("\n") + content;
return importedModels.reduce((acc, model) => acc + `import ${model} from './${model}';\n`, '') + content;
} }
function generateFunctions(paths) { function generateFunctions(paths) {
const apisDirectory = path.resolve(__dirname, '../apis');
if (!fs.existsSync(apisDirectory)) {
fs.mkdirSync(apisDirectory);
} else {
deleteFolderRecursive(apisDirectory);
fs.mkdirSync(apisDirectory);
}
const pathnameList = Object.keys(paths); const pathnameList = Object.keys(paths);
// { // {
...@@ -220,7 +207,7 @@ function generateFunctions(paths) { ...@@ -220,7 +207,7 @@ function generateFunctions(paths) {
let apiNames = Object.keys(apiMap); let apiNames = Object.keys(apiMap);
for (let index = 0; index < apiNames.length; index++) { for (let index = 0; index < apiNames.length; index++) {
const apiName = apiNames[index]; const apiName = apiNames[index];
fs.writeFileSync(path.resolve(__dirname, `../apis/${apiName}.ts`), getApiMethods(apiMap[apiName], apiName), {encoding: 'utf-8'}); fs.writeFileSync(path.join(directory, `${apiName}.ts`), getApiMethods(apiMap[apiName], apiName), {encoding: 'utf-8'});
console.log('write api functions: ', apiName); console.log('write api functions: ', apiName);
} }
} }
...@@ -236,6 +223,15 @@ module.exports = function() { ...@@ -236,6 +223,15 @@ module.exports = function() {
// 网关 // 网关
const gateWay = jsonObject.basePath; const gateWay = jsonObject.basePath;
if (!fs.existsSync(directory)) {
console.log('create directory: ', directory);
fs.mkdirSync(directory);
} else {
console.log('clean directory: ', directory);
deleteFolderRecursive(directory);
fs.mkdirSync(directory);
}
generateModels(jsonObject.definitions); generateModels(jsonObject.definitions);
generateFunctions(jsonObject.paths) generateFunctions(jsonObject.paths)
......
const getSwaggerJSON = require('./getSwaggerJSON'); const getSwaggerJSON = require('./getSwaggerJSON');
const generat = require('./generat') const generat = require('./generat')
const url = 'http://192.168.1.122/produce/v1/api/uia/v2/api-docs' const url = 'http://192.168.1.122:8101/zysoft-app-data-standard-web-service/v2/api-docs'
getSwaggerJSON(url, (err) => { getSwaggerJSON(url, (err) => {
if (!err) { if (!err) {
generat(); generat();
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论