11import path from 'path' ;
22import fs from 'fs' ;
33import Mock from 'mockjs' ;
4- import axios from 'axios' ;
5- import { createSwaggerMockData } from './swaggerAction.js'
4+ import { ResponseExample , NotFoundResponse } from './response.js' ;
5+ // import axios from 'axios';
6+ // import { createSwaggerMockData } from './swaggerAction.js'
67export const createAPIFile = ( dataJson , folderPath , fileName ) => {
78 const apiFolderPath = path . resolve ( folderPath ) ; // 定义 API 目录的绝对路径
89 const filePath = path . resolve ( apiFolderPath , fileName ) ; // 定义 get.json 文件的绝对路径
@@ -41,55 +42,4 @@ export const generateApi = (app, filePath, actions) => {
4142 } ) ;
4243 } ) ;
4344 } ) ;
44- }
45-
46- // swagger生成路由
47- export const createRoutes = ( { app, data } ) => {
48- const paths = data . paths || { }
49- if ( ! paths ) {
50- return
51- }
52- const keys = Object . keys ( paths ) ;
53- const limit = Math . min ( keys . length , 100 ) ; // 只生成前100个路由
54-
55- for ( let i = 0 ; i < limit ; i ++ ) {
56- const pathKey = keys [ i ] ;
57- const pathInfo = paths [ pathKey ] ;
58- const lastSegment = `/${ pathKey . split ( '/' ) . pop ( ) } ` ;
59-
60- Object . keys ( pathInfo ) . forEach ( method => {
61- app [ method ] ( lastSegment , async ( req , res ) => {
62- const { Action } = req . body ;
63- if ( Action ) {
64- // TODO: 这里指读取了$ref字段,如果没有关联需要处理下
65- const responseSchema = pathInfo [ method ] . responses [ '200' ] . schema [ '$ref' ] . split ( '/' ) . pop ( ) ;
66- const response = data . definitions [ responseSchema ]
67- const mockResponse = await createSwaggerMockData ( data , response )
68- return res . status ( 200 ) . json ( mockResponse ) ;
69- } else {
70- return res . status ( 404 ) . send ( NotFoundResponse ) ;
71- }
72- } ) ;
73- } ) ;
74- }
75- } ;
76-
77- // Step3: 获取swagger api json的数据,注册接口
78- export const fetchAndCreateRoutes = async ( { app, swaggerApi } ) => {
79- const routePromises = swaggerApi . map ( async ( item ) => {
80- const { type, url } = item ;
81- if ( type === 'action' ) {
82- try {
83- // TODO: 优化, 全局加载,方便后面读取直接使用
84- const response = await axios . get ( url ) ;
85- const data = response . data ;
86- createRoutes ( { app, data } ) ;
87- } catch ( error ) {
88- console . error ( 'Error fetching data from URL:' , url , error ) ;
89- }
90- }
91- } ) ;
92-
93- // 等待所有的请求完成
94- await Promise . all ( routePromises ) ;
95- } ;
45+ }
0 commit comments