Commit 1a8bf461 authored by 邓晓峰's avatar 邓晓峰

fix: 修复openapi

parent e3a58a52
Pipeline #23702 skipped with stages
// @ts-ignore
//import { Request, Response } from 'express';
// import { Request, Response } from 'express';
module.exports = {};
// @ts-ignore
//import { Request, Response } from 'express';
// import { Request, Response } from 'express';
module.exports = {
'GET /api/rule': (req, res) => {
res
.status(200)
.send({
res.status(200).send({
data: [
{
key: 77,
disabled: true,
href: 'https://umijs.org/',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '杜明',
owner: 'Johnson',
desc: '展金习设许此备还育住第即但没新何进。',
......@@ -39,7 +38,8 @@ module.exports = {
key: 98,
disabled: true,
href: 'https://procomponents.ant.design/',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '韩军',
owner: 'Hall',
desc: '二应据称感号单常强持社少便快极西流能。',
......@@ -53,7 +53,8 @@ module.exports = {
key: 94,
disabled: false,
href: 'https://preview.pro.ant.design/dashboard/analysis',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
name: '刘平',
owner: 'Lopez',
desc: '大管别消证物拉主今解过格科家角。',
......@@ -67,7 +68,8 @@ module.exports = {
key: 74,
disabled: true,
href: 'https://ant.design',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
name: '苏娟',
owner: 'Miller',
desc: '需八相严平写今的快验二历林。',
......@@ -168,13 +170,12 @@ module.exports = {
});
},
'POST /api/rule': (req, res) => {
res
.status(200)
.send({
res.status(200).send({
key: 71,
disabled: true,
href: 'https://ant.design',
avatar: 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
avatar:
'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
name: '段勇',
owner: 'Thomas',
desc: '院题质数下布进或会府速体快型前快。',
......@@ -186,9 +187,7 @@ module.exports = {
});
},
'PUT /api/rule': (req, res) => {
res
.status(200)
.send({
res.status(200).send({
key: 94,
disabled: true,
href: 'https://umijs.org/',
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -98,9 +98,9 @@
"@ant-design/pro-utils": "^1.10.4",
"@babel/polyfill": "7.4.3",
"@babel/runtime": "^7.10.5",
"@wisdom-utils/components": "0.0.9",
"@wisdom-utils/components": "0.0.14",
"@wisdom-utils/runtime": "0.0.15",
"@wisdom-utils/utils": "0.0.44",
"@wisdom-utils/utils": "0.0.46",
"animate.css": "^4.1.1",
"antd": "^4.11.2",
"compression": "1.7.4",
......@@ -114,7 +114,7 @@
"js-cookie": "^2.2.1",
"kit_global_config": "^1.0.24",
"kit_logger": "^1.0.2",
"kit_utils": "^1.3.10",
"kit_utils": "^1.3.11",
"lodash": "4.17.11",
"minimist": "1.2.0",
"mqtt-client": "^1.0.11",
......
......@@ -60,6 +60,7 @@ const generateService = async ({ requestLibPath, schemaPath, mockFolder, ...rest
const requestImportStatement = getImportStatement(requestLibPath);
const serviceGenerator = new serviceGenerators.ServiceGenerator({
namespace: 'API',
basePath: openAPI.servers[0].url,
requestImportStatement,
...rest,
}, openAPI);
......
const chalk = require('chalk');
const Log = (...rest) => console.log(`${chalk.blue('[openAPI]')}: ${rest.join('\n')}`);
const Log = (...rest) =>
console.log(`${chalk.blue('[openAPI]')}: ${rest.join('\n')}`);
module.exports = Log;
const mockjs = require("mockjs");
const fs = require("fs");
const util = require("./util");
const path = require("path");
const openAPIParserMock = require("./openAPIParserMock/index");
const log = require("./log");
const mockjs = require('mockjs');
const fs = require('fs');
const path = require('path');
const util = require('./util');
const openAPIParserMock = require('./openAPIParserMock/index');
const log = require('./log');
mockjs.Random.extend({
country() {
const data = [
......@@ -56,7 +56,13 @@ mockjs.Random.extend({
return avatar[id];
},
group() {
const data = ['体验技术部', '创新科技组', '前端 6 组', '区块链平台部', '服务技术部'];
const data = [
'体验技术部',
'创新科技组',
'前端 6 组',
'区块链平台部',
'服务技术部',
];
const id = (Math.random() * data.length).toFixed();
return data[id];
},
......@@ -93,7 +99,7 @@ mockjs.Random.extend({
return href[id];
},
});
const genMockData = (example) => {
const genMockData = example => {
if (!example) {
return {};
}
......@@ -104,50 +110,61 @@ const genMockData = (example) => {
return mockjs.mock(example);
}
return Object.keys(example)
.map((name) => {
return {
.map(name => ({
[name]: mockjs.mock(example[name]),
};
})
.reduce((pre, next) => {
return {
}))
.reduce(
(pre, next) => ({
...pre,
...next,
};
}, {});
}),
{},
);
};
const genByTemp = ({ method, path, status, data, }) => {
if (!['get', 'put', 'post', 'delete', 'patch'].includes(method.toLocaleLowerCase())) {
// eslint-disable-next-line no-shadow
const genByTemp = ({ method, path, status, data }) => {
if (
!['get', 'put', 'post', 'delete', 'patch'].includes(
method.toLocaleLowerCase(),
)
) {
return '';
}
return `'${method.toUpperCase()} ${path}': (req, res) => {
res.status(${status}).send(${data});
}`;
};
const genMockFiles = (mockFunction) => {
return util.prettierFile(`
const genMockFiles = mockFunction =>
util.prettierFile(`
// @ts-ignore
//import { Request, Response } from 'express';
module.exports = {
${mockFunction.join('\n,')}
}`)[0];
};
const mockGenerator = async ({ openAPI, mockFolder }) => {
// eslint-disable-next-line new-cap
const openAPParse = new openAPIParserMock(openAPI);
const docs = openAPParse.parser();
const pathList = Object.keys(docs.paths);
const { paths } = docs;
const mockActionsObj = {};
pathList.forEach((path) => {
// eslint-disable-next-line no-shadow
pathList.forEach(path => {
const pathConfig = paths[path];
Object.keys(pathConfig).forEach((method) => {
Object.keys(pathConfig).forEach(method => {
const methodConfig = pathConfig[method];
if (methodConfig) {
const conte = methodConfig && methodConfig.tags && methodConfig.tags.join('/') ||
const conte =
(methodConfig && methodConfig.tags && methodConfig.tags.join('/')) ||
path.replace('/', '').split('/')[1] ||
methodConfig.operationId;
const data = genMockData(methodConfig && methodConfig.responses && methodConfig.responses['200'] && methodConfig.responses['200'].example);
const data = genMockData(
methodConfig &&
methodConfig.responses &&
methodConfig.responses['200'] &&
methodConfig.responses['200'].example,
);
if (!mockActionsObj[conte]) {
mockActionsObj[conte] = [];
}
......@@ -163,17 +180,21 @@ const mockGenerator = async ({ openAPI, mockFolder }) => {
}
});
});
Object.keys(mockActionsObj).forEach((file) => {
Object.keys(mockActionsObj).forEach(file => {
if (!file || file === 'undefined') {
return;
}
fs.writeFileSync(path.join(mockFolder, `${file}.mock.js`), genMockFiles(mockActionsObj[file]), {
fs.writeFileSync(
path.join(mockFolder, `${file}.mock.js`),
genMockFiles(mockActionsObj[file]),
{
encoding: 'utf8',
});
},
);
});
log('✅ 生成 mock 文件成功');
};
module.exports = {
mockGenerator
mockGenerator,
};
......@@ -24,9 +24,11 @@ const getDateByName = (name, parentsKey) => {
if (name.toLocaleLowerCase().endsWith('id')) {
return 'uuid';
}
if (name.toLocaleLowerCase().endsWith('type') ||
if (
name.toLocaleLowerCase().endsWith('type') ||
name.toLocaleLowerCase().endsWith('key') ||
['key'].includes(name)) {
['key'].includes(name)
) {
return 'id';
}
if (name.toLocaleLowerCase().endsWith('label') || ['label'].includes(name)) {
......@@ -59,33 +61,37 @@ const getDateByName = (name, parentsKey) => {
if (['country'].includes(name)) {
return 'country';
}
if (['url', 'imageUrl', 'href'].includes(name) ||
if (
['url', 'imageUrl', 'href'].includes(name) ||
name.toLocaleLowerCase().endsWith('url') ||
name.toLocaleLowerCase().endsWith('urls') ||
name.toLocaleLowerCase().endsWith('image') ||
name.toLocaleLowerCase().endsWith('link')) {
name.toLocaleLowerCase().endsWith('link')
) {
return 'href';
}
if (name.toLocaleLowerCase().endsWith('errorcode')) {
return 'errorCode';
}
if (['type', 'status'].includes(name) ||
if (
['type', 'status'].includes(name) ||
name.toLocaleLowerCase().endsWith('status') ||
name.toLocaleLowerCase().endsWith('type')) {
name.toLocaleLowerCase().endsWith('type')
) {
return 'status';
}
if (name.toLocaleLowerCase().endsWith('authority')) {
return 'authority';
}
return 'csentence';
}
};
function primitive(schemaParams, propsName) {
const schema = utils.objectify(schemaParams);
console.log("schemaParams", propsName)
const { type, format } = schema;
const value = primitives[`${type}_${format || getDateByName(propsName)}`] || primitives[type];
const value =
primitives[`${type}_${format || getDateByName(propsName)}`] ||
primitives[type];
if (typeof schema.example === 'undefined') {
return value || `Unknown Type: ${schema.type}`;
}
......@@ -102,19 +108,21 @@ class OpenAPIGeneratorMockJs {
if (!type) {
if (properties) {
type = 'object';
}
else if (items) {
} else if (items) {
type = 'array';
}
else {
} else {
return null;
}
}
if (type === 'object') {
const props = utils.objectify(properties);
const obj = {};
// eslint-disable-next-line guard-for-in
for (const name in props) {
obj[name] = this.sampleFromSchema(props[name], [...(propsName || []), name]);
obj[name] = this.sampleFromSchema(props[name], [
...(propsName || []),
name,
]);
}
if (additionalProperties === true) {
obj.additionalProp1 = {};
......@@ -122,7 +130,10 @@ class OpenAPIGeneratorMockJs {
}
if (additionalProperties) {
const additionalProps = utils.objectify(additionalProperties);
const additionalPropVal = this.sampleFromSchema(additionalProps, propsName);
const additionalPropVal = this.sampleFromSchema(
additionalProps,
propsName,
);
for (let i = 1; i < 4; i += 1) {
obj[`additionalProp${i}`] = additionalPropVal;
}
......@@ -131,11 +142,12 @@ class OpenAPIGeneratorMockJs {
}
if (type === 'array') {
const item = this.sampleFromSchema(items, propsName);
return new Array(parseInt((Math.random() * 20).toFixed(0), 10)).fill(item);
return new Array(parseInt((Math.random() * 20).toFixed(0), 10)).fill(
item,
);
}
if (localSchema.enum) {
if (localSchema.default)
return localSchema.default;
if (localSchema.default) return localSchema.default;
return utils.normalizeArray(localSchema.enum)[0];
}
if (type === 'file') {
......@@ -144,23 +156,28 @@ class OpenAPIGeneratorMockJs {
return primitive(localSchema, propsName);
};
this.parser = () => {
// eslint-disable-next-line no-shadow
const openAPI = {
...this.openAPI,
};
// eslint-disable-next-line guard-for-in
for (const path in openAPI.paths) {
// eslint-disable-next-line guard-for-in
for (const method in openAPI.paths[path]) {
const api = openAPI.paths[path][method];
// eslint-disable-next-line guard-for-in
for (const code in api.responses) {
const response = api.responses[code];
const schema = response.content &&
const schema =
response.content &&
response.content['application/json'] &&
utils.inferSchema(response.content['application/json']);
if (schema) {
response.example = schema ? this.sampleFromSchema(schema) : null;
}
}
if (!api.parameters)
continue;
// eslint-disable-next-line no-continue
if (!api.parameters) continue;
for (const parameter of api.parameters) {
const schema = utils.inferSchema(parameter);
parameter.example = schema ? this.sampleFromSchema(schema) : null;
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment