openapi-ts-request 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 openapi-ui
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,147 @@
1
+ ## Introduce
2
+
3
+ [![GitHub Repo stars](https://img.shields.io/github/stars/openapi-ui/openapi-ts-request?style=social)](https://github.com/openapi-ui/openapi-ts-request)
4
+ [![npm (scoped)](https://img.shields.io/npm/v/openapi-ts-request)](https://www.npmjs.com/package/openapi-ts-request)
5
+ ![GitHub tag](https://img.shields.io/github/v/tag/openapi-ui/openapi-ts-request?include_prereleases)
6
+
7
+ 根据 [Swagger2/OpenAPI3](https://swagger.io/blog/news/whats-new-in-openapi-3-0/) 文档生成 ts 类型、request client 请求代码。
8
+
9
+ ## Features
10
+
11
+ * supports Swagger2.0/OpenAPI 3.0,3.1 specifications
12
+ * generate TypeScript Interfaces, Reuquest clients, Display Babel
13
+ * supports Custom Request Function, Fetch、Axios、Uniapp-Request、Node.js、XHR client available
14
+ * supports JSON specifications
15
+
16
+ ## Usage
17
+
18
+ ```bash
19
+ npm i openapi-ts-request --save-dev
20
+
21
+ pnpm i openapi-ts-request -D
22
+ ```
23
+
24
+ ### CosmiConfig
25
+
26
+ 在项目根目录新建 ```openapi-ts-request.config.ts```
27
+ > 配置文件还支持 ***.openapi-ts-request.ts***, ***openapi-ts-request.config.cjs*** 等格式,参考 [cosmiconfig](https://github.com/cosmiconfig/cosmiconfig?tab=readme-ov-file#cosmiconfig)
28
+
29
+ ```ts
30
+ export default {
31
+ schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
32
+ }
33
+ ```
34
+
35
+ 如果项目有多个生成需求,支持传入数组配置
36
+
37
+ ```ts
38
+ export default [
39
+ {
40
+ schemaPath: 'http://app.swagger.io/v2/swagger.json',
41
+ serversPath: './src/apis/app',
42
+ },
43
+ {
44
+ schemaPath: 'http://auth.swagger.io/v2/swagger.json',
45
+ serversPath: './src/apis/auth',
46
+ }
47
+ ]
48
+ ```
49
+
50
+ 在 ```package.json``` 的 ```script``` 中添加 api: ```"openapi": "openapi-ts-request",```
51
+
52
+ 生成 api
53
+
54
+ ```bash
55
+ npm run openapi
56
+ ```
57
+
58
+ ### JS
59
+
60
+ 任意目录 ```xxx/xxx``` 新建 ```openapi-ts-request.config.js```
61
+
62
+ ```ts
63
+ const { generateService } = require('openapi-ts-request')
64
+
65
+ generateService({
66
+ schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
67
+ serversPath: './apis',
68
+ })
69
+ ```
70
+
71
+ 在 ```package.json``` 的 ```script``` 中添加 script: ```"openapi": "node xxx/xxx/openapi-ts-request.config.js"```
72
+
73
+ 生成 api
74
+
75
+ ```bash
76
+ npm run openapi
77
+ ```
78
+
79
+ ### TS
80
+
81
+ 任意目录 ```xxx/xxx``` 新建 ```openapi-ts-request.config.ts```
82
+
83
+ ```ts
84
+ const { generateService } = require('openapi-ts-request')
85
+
86
+ generateService({
87
+ schemaPath: 'http://petstore.swagger.io/v2/swagger.json',
88
+ serversPath: './apis',
89
+ })
90
+ ```
91
+
92
+ 在 ```package.json``` 的 ```script``` 中添加 api: ```"openapi": "ts-node xxx/xxx/openapi-ts-request.config.ts",```
93
+
94
+ 生成 api
95
+ ```bash
96
+ npm run openapi
97
+ ```
98
+
99
+ ## Parameter
100
+
101
+ | 属性 | 必填 | 备注 | 类型 | 默认值 |
102
+ | ---- | ---- | ---- | ---- | - |
103
+ | schemaPath | 是 | Swagger 2.0 或 OpenAPI 3.0 的地址 | string | - |
104
+ | serversPath | 否 | 生成的文件夹的路径 | string | './src/apis' |
105
+ | requestLibPath | 否 | 自定义请求方法路径 | string | - |
106
+ | allowedTags | 否 | 生成指定 tags 下面的 api | string[] | - |
107
+ | requestOptionsType | 否 | 自定义请求方法 options 参数类型 | string | '{ [key: string]: any }' |
108
+ | requestImportStatement | 否 | 自定义请求方法表达式,例如:'@/request' | string | - |
109
+ | apiPrefix | 否 | api 的前缀,例如:"'api'" | string | - |
110
+ | dataFields | 否 | 定义 response 中数据字段类型 | string[] | - |
111
+ | mockFolder | 否 | mock目录 | string | './mocks' |
112
+ | nullable | 否 | 使用null代替可选 | boolean | false |
113
+ | isCamelCase | 否 | 小驼峰命名文件和请求函数 | boolean | true |
114
+ | hook | 否 | 自定义 hook | [Custom Hook](#Custom-Hook) | - |
115
+
116
+ ## Custom Hook
117
+
118
+ | 属性 | 类型 | 说明 |
119
+ | -------------- | ---- | ------------------ |
120
+ | afterOpenApiDataInited | (openAPIData: OpenAPIObject) => OpenAPIObject | - |
121
+ | customFunctionName | (data: APIDataType) => string | 自定义请求方法函数名称 |
122
+ | customTypeName | (data: APIDataType) => string | 自定义类型名称 |
123
+ | customClassName | (tagName: string) => string | 自定义类名 |
124
+ | customType | (<br>schemaObject: SchemaObject \| ReferenceObject,<br>namespace: string,<br>originGetType:(schemaObject: SchemaObject \| ReferenceObject, namespace: string) => string,<br>) => string | 自定义获取类型 <br> *返回非字符串将使用默认方法获取type* |
125
+ | customFileNames | (<br>operationObject: OperationObject,<br>apiPath: string,<br>apiMethod: string,<br>) => string[] | 自定义生成文件名,可返回多个,表示生成多个文件. <br> *返回为空,则使用默认的获取方法获取* |
126
+
127
+ ## Mock
128
+
129
+ 目前使用 [mockjs](http://mockjs.com) 生成 mock 数据,mocks 文件启动需要借助 [@umijs/server](https://umijs.org/docs/guides/mock),后面会寻找其他方案以达到更好的 mock 体验
130
+
131
+ ## Thanks
132
+
133
+ - [openapi2typescript](https://github.com/chenshuai2144/openapi2typescript)
134
+
135
+ ps:由于 openapi2typescript 仓库作者不怎么维护这个工具,不会主动增加功能,有些激进的pr也不再合并,为了更大的自主性,也为了方便自己更好的维护此工具,所以基于此仓库重构代码并添加了很多功能(后续还会加一些对部分场景有用的功能),并附上了注释方便大家感兴趣的一起参与(都是为开源做一点贡献,应该不会被诟病吧😭😭😭),例如:
136
+ * 支持 tags 筛选api(对 apifox 工具管理接口非常有用)
137
+ * 支持枚举和枚举翻译
138
+ * 改善 interface 对枚举的引用方式,对 ast 提示更友好
139
+ * 改写 type 文件组织方式,引用 type 的提示更友好
140
+ * 解决 type 重名问题
141
+ * 支持配置文件方式使用,避免强制依赖 ts-node
142
+ * 支持自定义 prettier 配置,将作用于生成后的代码
143
+ * 替换 openapi 规范定义包:openapi3-ts => openapi-types
144
+ * 添加 eslint、tslint 规则,优化代码
145
+ * 添加 husky、lint-staged、commitlint 等等工程化工具
146
+ * 优化对外提供的参数
147
+ * 优化 npm 包依赖
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,31 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var _a;
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ const tslib_1 = require("tslib");
6
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
7
+ const cosmiconfig_1 = require("cosmiconfig");
8
+ const index_1 = require("./index");
9
+ const explorerSync = (0, cosmiconfig_1.cosmiconfigSync)('openapi-ts-request');
10
+ const config = (_a = explorerSync.search()) === null || _a === void 0 ? void 0 : _a.config;
11
+ function run() {
12
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
13
+ try {
14
+ if (config) {
15
+ const configs = Array.isArray(config)
16
+ ? config
17
+ : [config];
18
+ for (const config of configs) {
19
+ yield (0, index_1.generateService)(config);
20
+ }
21
+ }
22
+ else {
23
+ throw new Error('config is not found');
24
+ }
25
+ }
26
+ catch (error) {
27
+ console.log(chalk_1.default.red(error));
28
+ }
29
+ });
30
+ }
31
+ void run();
@@ -0,0 +1,29 @@
1
+ import { Dictionary } from 'lodash';
2
+ import { ParameterObject, SchemaObject } from '../type';
3
+ export declare const serviceEntryFileName = "index";
4
+ export declare const interfaceFileName = "types";
5
+ export declare const displayEnumLabelFileName = "displayEnumLabel";
6
+ export declare enum TypescriptFileType {
7
+ interface = "interface",
8
+ serviceController = "serviceController",
9
+ serviceIndex = "serviceIndex",
10
+ displayEnumLabel = "displayEnumLabel"
11
+ }
12
+ export declare const DEFAULT_SCHEMA: SchemaObject;
13
+ export declare const DEFAULT_PATH_PARAM: ParameterObject & Dictionary<any>;
14
+ export declare enum methods {
15
+ get = "get",
16
+ put = "put",
17
+ post = "post",
18
+ delete = "delete",
19
+ patch = "patch"
20
+ }
21
+ export declare enum parametersInsEnum {
22
+ query = "query",
23
+ path = "path",
24
+ cookie = "cookie",
25
+ header = "header",
26
+ file = "file"
27
+ }
28
+ export declare const parametersIn: string[];
29
+ export declare const numberEnum: string[];
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.numberEnum = exports.parametersIn = exports.parametersInsEnum = exports.methods = exports.DEFAULT_PATH_PARAM = exports.DEFAULT_SCHEMA = exports.TypescriptFileType = exports.displayEnumLabelFileName = exports.interfaceFileName = exports.serviceEntryFileName = void 0;
4
+ exports.serviceEntryFileName = 'index';
5
+ exports.interfaceFileName = 'types';
6
+ exports.displayEnumLabelFileName = 'displayEnumLabel';
7
+ var TypescriptFileType;
8
+ (function (TypescriptFileType) {
9
+ TypescriptFileType["interface"] = "interface";
10
+ TypescriptFileType["serviceController"] = "serviceController";
11
+ TypescriptFileType["serviceIndex"] = "serviceIndex";
12
+ TypescriptFileType["displayEnumLabel"] = "displayEnumLabel";
13
+ })(TypescriptFileType || (exports.TypescriptFileType = TypescriptFileType = {}));
14
+ exports.DEFAULT_SCHEMA = {
15
+ type: 'object',
16
+ properties: { id: { type: 'number' } },
17
+ };
18
+ exports.DEFAULT_PATH_PARAM = {
19
+ in: 'path',
20
+ name: null,
21
+ schema: {
22
+ type: 'string',
23
+ },
24
+ required: true,
25
+ isObject: false,
26
+ type: 'string',
27
+ };
28
+ var methods;
29
+ (function (methods) {
30
+ methods["get"] = "get";
31
+ methods["put"] = "put";
32
+ methods["post"] = "post";
33
+ methods["delete"] = "delete";
34
+ methods["patch"] = "patch";
35
+ })(methods || (exports.methods = methods = {}));
36
+ // Possible values are "query", "path", "file", "header", "cookie". (https://swagger.io/specification/)
37
+ var parametersInsEnum;
38
+ (function (parametersInsEnum) {
39
+ parametersInsEnum["query"] = "query";
40
+ parametersInsEnum["path"] = "path";
41
+ parametersInsEnum["cookie"] = "cookie";
42
+ parametersInsEnum["header"] = "header";
43
+ parametersInsEnum["file"] = "file";
44
+ })(parametersInsEnum || (exports.parametersInsEnum = parametersInsEnum = {}));
45
+ exports.parametersIn = ['query', 'path', 'cookie'];
46
+ exports.numberEnum = [
47
+ 'integer',
48
+ 'long',
49
+ 'float',
50
+ 'double',
51
+ 'number',
52
+ 'int',
53
+ 'float',
54
+ 'double',
55
+ 'int32',
56
+ 'int64',
57
+ ];
@@ -0,0 +1,2 @@
1
+ export declare const prettierFile: (content: string) => [string, boolean];
2
+ export declare function writeFile(folderPath: string, fileName: string, content: string): boolean;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.writeFile = exports.prettierFile = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const sync_1 = require("@prettier/sync");
6
+ const fs_1 = require("fs");
7
+ const path_1 = require("path");
8
+ const prettier_config_cjs_1 = tslib_1.__importDefault(require("../../prettier.config.cjs"));
9
+ const prettierFile = (content) => {
10
+ let result = content;
11
+ let hasError = false;
12
+ try {
13
+ result = (0, sync_1.format)(content, Object.assign(Object.assign({}, prettier_config_cjs_1.default), { parser: 'typescript', importOrderSeparation: false }));
14
+ }
15
+ catch (error) {
16
+ hasError = true;
17
+ }
18
+ return [result, hasError];
19
+ };
20
+ exports.prettierFile = prettierFile;
21
+ function mkdir(dir) {
22
+ if (!(0, fs_1.existsSync)(dir)) {
23
+ mkdir((0, path_1.dirname)(dir));
24
+ (0, fs_1.mkdirSync)(dir);
25
+ }
26
+ }
27
+ function writeFile(folderPath, fileName, content) {
28
+ const filePath = (0, path_1.join)(folderPath, fileName);
29
+ mkdir((0, path_1.dirname)(filePath));
30
+ const [prettierContent, hasError] = (0, exports.prettierFile)(content);
31
+ (0, fs_1.writeFileSync)(filePath, prettierContent, {
32
+ encoding: 'utf8',
33
+ });
34
+ return hasError;
35
+ }
36
+ exports.writeFile = writeFile;
@@ -0,0 +1,6 @@
1
+ import { OpenAPIObject } from '../type';
2
+ export type genMockDataServerConfig = {
3
+ openAPI: OpenAPIObject;
4
+ mockFolder: string;
5
+ };
6
+ export declare const mockGenerator: ({ openAPI, mockFolder, }: genMockDataServerConfig) => void;
@@ -0,0 +1,202 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mockGenerator = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs_1 = tslib_1.__importDefault(require("fs"));
6
+ const lodash_1 = require("lodash");
7
+ const mockjs_1 = tslib_1.__importDefault(require("mockjs"));
8
+ const path_1 = require("path");
9
+ const tiny_pinyin_1 = tslib_1.__importDefault(require("tiny-pinyin"));
10
+ const log_1 = tslib_1.__importDefault(require("../log"));
11
+ const index_1 = tslib_1.__importDefault(require("../parser-mock/index"));
12
+ const util_1 = require("../parser-mock/util");
13
+ const config_1 = require("./config");
14
+ const file_1 = require("./file");
15
+ mockjs_1.default.Random.extend({
16
+ country() {
17
+ const data = [
18
+ '阿根廷',
19
+ '澳大利亚',
20
+ '巴西',
21
+ '加拿大',
22
+ '中国',
23
+ '法国',
24
+ '德国',
25
+ '印度',
26
+ '印度尼西亚',
27
+ '意大利',
28
+ '日本',
29
+ '韩国',
30
+ '墨西哥',
31
+ '俄罗斯',
32
+ '沙特阿拉伯',
33
+ '南非',
34
+ '土耳其',
35
+ '英国',
36
+ '美国',
37
+ ];
38
+ return data[(0, util_1.getRandomInt)(0, data.length)];
39
+ },
40
+ phone() {
41
+ const phonepreFix = ['111', '112', '114', '136', '170', '180', '183'];
42
+ return (phonepreFix[(0, util_1.getRandomInt)(0, phonepreFix.length)] + mockjs_1.default.mock(/\d{8}/));
43
+ },
44
+ status() {
45
+ const status = ['success', 'error', 'default', 'processing', 'warning'];
46
+ return status[(0, util_1.getRandomInt)(0, status.length)];
47
+ },
48
+ authority() {
49
+ const authority = ['admin', 'user', 'guest'];
50
+ return authority[(0, util_1.getRandomInt)(0, authority.length)];
51
+ },
52
+ avatar() {
53
+ const avatar = [
54
+ 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
55
+ 'https://gw.alipayobjects.com/zos/rmsportal/udxAbMEhpwthVVcjLXik.png',
56
+ 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
57
+ 'https://gw.alipayobjects.com/zos/rmsportal/ThXAXghbEsBCCSDihZxY.png',
58
+ 'https://gw.alipayobjects.com/zos/rmsportal/OKJXDXrmkNshAMvwtvhu.png',
59
+ 'https://avatars0.githubusercontent.com/u/507615?s=40&v=4',
60
+ 'https://avatars1.githubusercontent.com/u/8186664?s=40&v=4',
61
+ ];
62
+ return avatar[(0, util_1.getRandomInt)(0, avatar.length)];
63
+ },
64
+ group() {
65
+ const data = [
66
+ '体验技术部',
67
+ '创新科技组',
68
+ '前端 6 组',
69
+ '区块链平台部',
70
+ '服务技术部',
71
+ ];
72
+ return data[(0, util_1.getRandomInt)(0, data.length)];
73
+ },
74
+ label() {
75
+ const label = [
76
+ '很有想法的',
77
+ '小清新',
78
+ '傻白甜',
79
+ '阳光少年',
80
+ '大咖',
81
+ '健身达人',
82
+ '程序员',
83
+ '算法工程师',
84
+ '川妹子',
85
+ '名望程序员',
86
+ '大长腿',
87
+ '海纳百川',
88
+ '专注设计',
89
+ '爱好广泛',
90
+ 'IT 互联网',
91
+ ];
92
+ return label[(0, util_1.getRandomInt)(0, label.length)];
93
+ },
94
+ href() {
95
+ const href = [
96
+ 'https://preview.pro.ant.design/dashboard/analysis',
97
+ 'https://ant.design',
98
+ 'https://procomponents.ant.design/',
99
+ 'https://umijs.org/',
100
+ 'https://github.com/umijs/dumi',
101
+ ];
102
+ return href[(0, util_1.getRandomInt)(0, href.length)];
103
+ },
104
+ });
105
+ const genMockData = (example) => {
106
+ if (!example) {
107
+ return {};
108
+ }
109
+ if (typeof example === 'string') {
110
+ return mockjs_1.default.mock(example);
111
+ }
112
+ if (Array.isArray(example)) {
113
+ return mockjs_1.default.mock(example);
114
+ }
115
+ return Object.keys(example)
116
+ .map((name) => {
117
+ return {
118
+ [name]: mockjs_1.default.mock(example[name]),
119
+ };
120
+ })
121
+ .reduce((pre, next) => {
122
+ return Object.assign(Object.assign({}, pre), next);
123
+ }, {});
124
+ };
125
+ const genByTemp = ({ method, path, parameters, status, data, }) => {
126
+ if (!(0, lodash_1.includes)(config_1.methods, method.toLocaleLowerCase())) {
127
+ return '';
128
+ }
129
+ let securityPath = path;
130
+ (0, lodash_1.forEach)(parameters, (item) => {
131
+ if (item.in === 'path') {
132
+ securityPath = securityPath.replace(`{${item.name}}`, `:${item.name}`);
133
+ }
134
+ });
135
+ return `'${method.toUpperCase()} ${securityPath}': (req: Request, res: Response) => {
136
+ res.status(${status}).send(${data});
137
+ }`;
138
+ };
139
+ const genMockFiles = (mockFunction) => {
140
+ return (0, file_1.prettierFile)(`
141
+ /* eslint-disable */
142
+ // @ts-ignore
143
+ import { Request, Response } from 'express';
144
+
145
+ export default {
146
+ ${mockFunction.join('\n,')}
147
+ }`)[0];
148
+ };
149
+ const mockGenerator = ({ openAPI, mockFolder, }) => {
150
+ const openAPIParse = new index_1.default(openAPI);
151
+ const docs = openAPIParse.parser();
152
+ const pathList = (0, lodash_1.keys)(docs.paths);
153
+ const { paths } = docs;
154
+ const mockActionsObj = {};
155
+ pathList.forEach((path) => {
156
+ const pathConfig = paths[path];
157
+ (0, lodash_1.keys)(pathConfig).forEach((method) => {
158
+ var _a, _b, _c;
159
+ const methodConfig = pathConfig[method];
160
+ if (methodConfig) {
161
+ let conte = (_b = (methodConfig.operationId ||
162
+ ((_a = methodConfig === null || methodConfig === void 0 ? void 0 : methodConfig.tags) === null || _a === void 0 ? void 0 : _a.join('/')) ||
163
+ path.replace('/', '').split('/')[1])) === null || _b === void 0 ? void 0 : _b.replace(/[^\w^\s^\u4e00-\u9fa5]/gi, '');
164
+ if (/[\u3220-\uFA29]/.test(conte)) {
165
+ conte = tiny_pinyin_1.default.convertToPinyin(conte, '', true);
166
+ }
167
+ if (!conte) {
168
+ return;
169
+ }
170
+ const response = (_c = methodConfig.responses) === null || _c === void 0 ? void 0 : _c['200'];
171
+ const data = genMockData(response === null || response === void 0 ? void 0 : response.example);
172
+ if (!mockActionsObj[conte]) {
173
+ mockActionsObj[conte] = [];
174
+ }
175
+ const tempFile = genByTemp({
176
+ method,
177
+ path,
178
+ parameters: methodConfig.parameters,
179
+ status: '200',
180
+ data: JSON.stringify(data),
181
+ });
182
+ if (tempFile) {
183
+ mockActionsObj[conte].push(tempFile);
184
+ }
185
+ }
186
+ });
187
+ });
188
+ Object.keys(mockActionsObj).forEach((file) => {
189
+ if (!file || (0, lodash_1.isUndefined)(file)) {
190
+ return;
191
+ }
192
+ if (file.includes('/')) {
193
+ const dirName = (0, path_1.dirname)((0, path_1.join)(mockFolder, `${file}.mock.ts`));
194
+ if (!fs_1.default.existsSync(dirName)) {
195
+ fs_1.default.mkdirSync(dirName);
196
+ }
197
+ }
198
+ (0, file_1.writeFile)(mockFolder, `${file}.mock.ts`, genMockFiles(mockActionsObj[file]));
199
+ });
200
+ (0, log_1.default)('✅ 生成 mock 文件成功');
201
+ };
202
+ exports.mockGenerator = mockGenerator;
@@ -0,0 +1,31 @@
1
+ import type { GenerateServiceProps } from '../index';
2
+ import { OpenAPIObject } from '../type';
3
+ import { ControllerType, TagAPIDataType } from './type';
4
+ export default class ServiceGenerator {
5
+ protected apiData: TagAPIDataType;
6
+ protected classNameList: ControllerType[];
7
+ protected finalPath: string;
8
+ protected config: GenerateServiceProps;
9
+ protected openAPIData: OpenAPIObject;
10
+ constructor(config: GenerateServiceProps, openAPIData: OpenAPIObject);
11
+ genFile(): void;
12
+ private getInterfaceTPConfigs;
13
+ private getServiceTPConfigs;
14
+ private genFileFromTemplate;
15
+ private getTemplate;
16
+ private getFuncationName;
17
+ private getType;
18
+ private getTypeName;
19
+ private getBodyTP;
20
+ private getFileTP;
21
+ private resolveFileTP;
22
+ private getResponseTP;
23
+ private getParamsTP;
24
+ private resolveObject;
25
+ private resolveArray;
26
+ private resolveProperties;
27
+ private resolveEnumObject;
28
+ private resolveAllOfObject;
29
+ private getProps;
30
+ private resolveRefObject;
31
+ }