@wx-sab/renkei 0.2.9 → 1.0.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/README.md CHANGED
@@ -13,7 +13,7 @@
13
13
  - [x] 多服务的 apifox 项目解析
14
14
  - [x] 支持 swagger 3.0 解析
15
15
  - [x] 支持自定义生成接口名
16
- - [ ] 支持过滤部分接口
16
+ - [x] 支持只生成部分服务接口
17
17
 
18
18
  ## Introduce
19
19
 
@@ -23,12 +23,15 @@ const readProjectConfigFile = () => {
23
23
  }
24
24
  return null;
25
25
  };
26
- const parse = new commander_1.default.Command('api').action(() => {
26
+ const parse = new commander_1.default.Command('api').option('-s, --service <service>', '只获取指定的服务,多个服务用","分隔', ',').action((param, options) => {
27
+ var _a;
28
+ // 只生成指定服务
29
+ const services = ((_a = param.service) === null || _a === void 0 ? void 0 : _a.split(',')) || [];
27
30
  const config = readProjectConfigFile();
28
31
  if (!config) {
29
32
  console.warn('未找到配置文件');
30
33
  return;
31
34
  }
32
- (0, generate_1.generateApis)(config);
35
+ (0, generate_1.generateApis)(config, services);
33
36
  });
34
37
  exports.default = parse;
@@ -6,4 +6,4 @@ import { GenerateConfig } from "./interface";
6
6
  * 单个配置生成
7
7
  */
8
8
  export declare const generate: (conf: GenerateConfig) => Promise<import("swagger-typescript-api").GenerateApiOutput>;
9
- export declare const generateApis: (config: GenerateConfig | GenerateConfig[]) => Promise<void>;
9
+ export declare const generateApis: (config: GenerateConfig | GenerateConfig[], services: string[]) => Promise<void>;
@@ -26,6 +26,7 @@ exports.generateApis = exports.generate = void 0;
26
26
  const path_1 = __importDefault(require("path"));
27
27
  const lodash_1 = __importDefault(require("lodash"));
28
28
  const swagger_typescript_api_1 = require("swagger-typescript-api");
29
+ const cli_progress_1 = __importDefault(require("cli-progress"));
29
30
  const utils_1 = require("./utils");
30
31
  /**
31
32
  * 单个配置生成
@@ -47,6 +48,8 @@ const generate = (conf) => {
47
48
  output: path_1.default.resolve(config.output, config.serviceName),
48
49
  // 模块化?
49
50
  modular: false,
51
+ // 静默
52
+ silent: true,
50
53
  extractRequestParams: true,
51
54
  // 清空输出目录?
52
55
  cleanOutput: false,
@@ -58,8 +61,8 @@ const generate = (conf) => {
58
61
  extraTemplates: [
59
62
  {
60
63
  name: "index.ts",
61
- path: path_1.default.resolve(__dirname, "../../templates/service.ejs"),
62
- },
64
+ path: path_1.default.resolve(__dirname, "../../templates/service.ejs")
65
+ }
63
66
  ],
64
67
  hooks: {
65
68
  onCreateRouteName(routeNameInfo, rawRouteInfo) {
@@ -80,7 +83,7 @@ const generate = (conf) => {
80
83
  return {
81
84
  duplicate: duplicate,
82
85
  original: methodName,
83
- usage: methodName,
86
+ usage: methodName
84
87
  };
85
88
  },
86
89
  onPrepareConfig(currentConfiguration) {
@@ -101,18 +104,19 @@ const generate = (conf) => {
101
104
  // 将 /api/v1/order-mains/{orderId} 转成 /api/v1/order-mains/${orderId}
102
105
  // routeData.raw.route 是进过 customRequestUrl 转换过的
103
106
  // @ts-ignore
104
- routeData.request.path = (_a = routeData.raw.route) === null || _a === void 0 ? void 0 : _a.replace(/\{([^}]+)\}/g, '${$1}');
107
+ routeData.request.path = (_a = routeData.raw.route) === null || _a === void 0 ? void 0 : _a.replace(/\{([^}]+)\}/g, "${$1}");
105
108
  return routeData;
106
109
  },
107
110
  onInit(configuration) {
108
111
  return Object.assign(Object.assign({}, configuration), { serviceName: config.serviceName, apifoxProjectId: config.apifoxProjectId, customResponseType: config.customResponseType, customMockService: config.customMockService });
109
- },
110
- },
112
+ }
113
+ }
111
114
  });
112
115
  };
113
116
  exports.generate = generate;
114
117
  // 批量生成接口
115
- const generateApis = (config) => __awaiter(void 0, void 0, void 0, function* () {
118
+ const generateApis = (config, services // 指定服务
119
+ ) => __awaiter(void 0, void 0, void 0, function* () {
116
120
  var _a, e_1, _b, _c;
117
121
  // 递归收集config下可能有的 projects ,也当做新的config
118
122
  const collectConfig = (conf, collects = []) => {
@@ -122,20 +126,30 @@ const generateApis = (config) => __awaiter(void 0, void 0, void 0, function* ()
122
126
  conf.forEach((con) => collectConfig(con, collects));
123
127
  }
124
128
  else {
125
- collects.push(lodash_1.default.omit(conf, 'projects'));
129
+ collects.push(lodash_1.default.omit(conf, "projects"));
126
130
  if (Array.isArray(conf.projects)) {
127
- conf.projects.forEach((project) => collectConfig(Object.assign(Object.assign({}, lodash_1.default.omit(conf, 'projects')), project), collects));
131
+ conf.projects.forEach((project) => collectConfig(Object.assign(Object.assign({}, lodash_1.default.omit(conf, "projects")), project), collects));
128
132
  }
129
133
  }
130
134
  return collects;
131
135
  };
132
- const _configs = collectConfig(config);
136
+ const _configs = collectConfig(config).filter((conf) => {
137
+ // 只筛选指定的服务
138
+ if (services.length > 0) {
139
+ return services.includes(conf.serviceName);
140
+ }
141
+ return true;
142
+ });
143
+ // 进度条控制
144
+ const progress = new cli_progress_1.default.SingleBar({});
145
+ progress.start(_configs.length, 0);
133
146
  try {
134
147
  for (var _d = true, _configs_1 = __asyncValues(_configs), _configs_1_1; _configs_1_1 = yield _configs_1.next(), _a = _configs_1_1.done, !_a; _d = true) {
135
148
  _c = _configs_1_1.value;
136
149
  _d = false;
137
150
  const conf = _c;
138
151
  yield (0, exports.generate)(conf);
152
+ progress.increment(1);
139
153
  }
140
154
  }
141
155
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
@@ -145,5 +159,7 @@ const generateApis = (config) => __awaiter(void 0, void 0, void 0, function* ()
145
159
  }
146
160
  finally { if (e_1) throw e_1.error; }
147
161
  }
162
+ progress.stop();
163
+ console.info("✅ 执行完毕");
148
164
  });
149
165
  exports.generateApis = generateApis;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wx-sab/renkei",
3
- "version": "0.2.9",
3
+ "version": "1.0.0",
4
4
  "description": "解析swagger转为ts代码,日本动漫《游戏王》中的‘Renkei’,意为连携或协作。",
5
5
  "main": "./lib/index.js",
6
6
  "bin": {
@@ -8,9 +8,10 @@
8
8
  },
9
9
  "scripts": {
10
10
  "dev": "ts-node ./src/index.ts",
11
- "demo": "ts-node ./demo.ts",
12
11
  "clean": "rm -rf lib",
13
- "build": "npm run clean & tsc --outDir lib"
12
+ "build": "npm run clean & tsc --outDir lib",
13
+ "version:alpha": "npm version premajor --preid alpha",
14
+ "api": "ts-node --transpile-only ./src/cli.ts api"
14
15
  },
15
16
  "repository": {
16
17
  "type": "git",
@@ -19,6 +20,7 @@
19
20
  "author": "sab-fe",
20
21
  "license": "ISC",
21
22
  "devDependencies": {
23
+ "@types/cli-progress": "^3.11.5",
22
24
  "@types/lodash": "^4.14.196",
23
25
  "@types/node": "^20.4.7",
24
26
  "typescript": "^5.1.6"
@@ -29,9 +31,10 @@
29
31
  ],
30
32
  "dependencies": {
31
33
  "axios": "^1.4.0",
34
+ "cli-progress": "^3.12.0",
32
35
  "commander": "^11.0.0",
33
36
  "lodash": "^4.17.21",
34
- "swagger-typescript-api": "^12.0.4",
37
+ "swagger-typescript-api": "^13.0.3",
35
38
  "ts-node": "^10.9.1"
36
39
  }
37
40
  }
@@ -1,7 +1,7 @@
1
1
  <%
2
- const { utils, route, config, modelTypes, namespace, modelNamespace, serviceName, requestTempalte, rawModelTypes, strict, } = it;
3
- const { requestBodyInfo, responseBodyInfo, specificArgNameResolver, routeParams, conflict, merged } = route;
4
- const { _, getInlineParseContent, getParseContent, parseSchema, getComponentByRef, require, pick } = utils;
2
+ const { utils, route, config, modelTypes, modelNamespace, serviceName, requestTempalte } = it;
3
+ const { requestBodyInfo, responseBodyInfo, specificArgNameResolver } = route;
4
+ const { _, getInlineParseContent, getParseContent, parseSchema, getComponentByRef, require } = utils;
5
5
  const { parameters, path, method, payload, query, formData, security, requestParams } = route.request;
6
6
  const { type, errorType, contentTypes } = route.response;
7
7
  const { HTTP_CLIENT, RESERVED_REQ_PARAMS_ARG_NAMES } = config.constants;
@@ -44,9 +44,9 @@ const argToTmpl = ({ name, optional, type, defaultValue }) => `${name}${!default
44
44
  const rawWrapperArgs = config.extractRequestParams ?
45
45
  _.compact([
46
46
  requestParams && {
47
- name: pathParams.length ? `{ ${_.join(pathParamsNames, ", ")}, ...${queryName} }` : queryName,
48
- optional: false,
49
- type: getInlineParseContent(requestParams),
47
+ name: pathParams.length ? `{ ${_.join(pathParamsNames, ", ")}, ...${queryName} }` : queryName,
48
+ optional: false,
49
+ type: getInlineParseContent(requestParams),
50
50
  },
51
51
  ...(!requestParams ? pathParams : []),
52
52
  payload,
@@ -70,8 +70,8 @@ const requestContentKind = {
70
70
  "JSON": "ContentType.Json",
71
71
  "URL_ENCODED": "ContentType.UrlEncoded",
72
72
  "FORM_DATA": "ContentType.FormData",
73
+ "TEXT": "ContentType.Text",
73
74
  }
74
-
75
75
  // RequestParams["format"]
76
76
  const responseContentKind = {
77
77
  "JSON": '"json"',
@@ -90,10 +90,10 @@ const describeReturnType = () => {
90
90
 
91
91
  switch(config.httpClientType) {
92
92
  case HTTP_CLIENT.AXIOS: {
93
- return `Promise<AxiosResponse<${type}>>`
93
+ return `Promise<AxiosResponse<${type}>>`
94
94
  }
95
95
  default: {
96
- return `Promise<HttpResponse<${type}, ${errorType}>`
96
+ return `Promise<HttpResponse<${type}, ${errorType}>`
97
97
  }
98
98
  }
99
99
  }
@@ -129,29 +129,14 @@ const wrappedDataArgs = _
129
129
  .map(argToTmpl)
130
130
  .join(', ')
131
131
 
132
- const getTypeSchema = (type) => {
133
- // Model.SalesService.IdParam => IdParam
134
- const realType = (type || '').split('.').pop()
135
- return rawModelTypes.find((item) => item.typeName === realType)?.rawTypeData?.properties
136
- }
137
-
138
- const requestBodySchemaNames = Object.keys(getTypeSchema(requestBodyInfo?.type) || {}).map((name) => ({ name }))
139
-
140
132
  %>
141
-
142
133
  /**
143
134
  <%~ routeDocs.description %>
144
135
 
145
- * <% /* Here you can add some other JSDoc tags */ %>
136
+ *<% /* Here you can add some other JSDoc tags */ %>
146
137
 
147
138
  <%~ routeDocs.lines %>
148
139
 
149
- <% if(merged) { %>
150
- * @merged
151
- <% } %>
152
- <% if(conflict) { %>
153
- * @conflict
154
- <% } %>
155
140
  */
156
141
  static public <%~ route.routeName.usage %> = async (<%~ wrappedDataArgs %>): Promise<<%~ getWrapperFullType(type) %>> => {
157
142
  const url = <%~ serviceName %>.generateUrl({
@@ -1,6 +1,6 @@
1
1
  <%
2
2
  const { config, route, utils } = it;
3
- const { _, formatDescription, fmtToJSDocLine, classNameCase, require } = utils;
3
+ const { _, formatDescription, fmtToJSDocLine, pascalCase, require } = utils;
4
4
  const { raw, request, routeName } = route;
5
5
 
6
6
  const jsDocDescription = raw.description ?
@@ -8,7 +8,7 @@ const jsDocDescription = raw.description ?
8
8
  fmtToJSDocLine('No description', { eol: false });
9
9
  const jsDocLines = _.compact([
10
10
  _.size(raw.tags) && ` * @tags ${raw.tags.join(", ")}`,
11
- ` * @name ${classNameCase(routeName.usage)}`,
11
+ ` * @name ${pascalCase(routeName.usage)}`,
12
12
  raw.summary && ` * @summary ${raw.summary}`,
13
13
  ` * @request ${_.upperCase(request.method)}:${raw.route}`,
14
14
  raw.deprecated && ` * @deprecated`,
@@ -18,10 +18,10 @@ const jsDocLines = _.compact([
18
18
  ...(config.generateResponses && raw.responsesTypes.length
19
19
  ? raw.responsesTypes.map(
20
20
  ({ type, status, description, isSuccess }) =>
21
- ` * @response \`${status}\` \`${type}\` ${description}`,
21
+ ` * @response \`${status}\` \`${_.replace(_.replace(type, /\/\*/g, "\\*"), /\*\//g, "*\\")}\` ${description}`,
22
22
  )
23
23
  : []),
24
- ]).join("\n");
24
+ ]).map(str => str.trimEnd()).join("\n");
25
25
 
26
26
 
27
27
  return {
@@ -0,0 +1,32 @@
1
+ <%
2
+ const { utils, config, routes, modelTypes } = it;
3
+ const { _, pascalCase } = utils;
4
+ const dataContracts = config.modular ? _.map(modelTypes, "name") : [];
5
+ %>
6
+
7
+ <% if (dataContracts.length) { %>
8
+ import { <%~ dataContracts.join(", ") %> } from "./<%~ config.fileNames.dataContracts %>"
9
+ <% } %>
10
+
11
+ <%
12
+ /* TODO: outOfModule, combined should be attributes of route, which will allow to avoid duplication of code */
13
+ %>
14
+
15
+ <% if (routes.outOfModule) { %>
16
+ <% for (const { routes: outOfModuleRoutes = [] } of routes.outOfModule) { %>
17
+ <% for (const route of outOfModuleRoutes) { %>
18
+ <%~ includeFile('@base/route-type.ejs', { ...it, route }) %>
19
+ <% } %>
20
+ <% } %>
21
+ <% } %>
22
+
23
+ <% if (routes.combined) { %>
24
+ <% for (const { routes: combinedRoutes = [], moduleName } of routes.combined) { %>
25
+ export namespace <%~ pascalCase(moduleName) %> {
26
+ <% for (const route of combinedRoutes) { %>
27
+ <%~ includeFile('@base/route-type.ejs', { ...it, route }) %>
28
+ <% } %>
29
+ }
30
+
31
+ <% } %>
32
+ <% } %>