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

fix: 修复openapi

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