@dazhicheng/utils 1.3.35 → 1.3.37

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dazhicheng/utils",
3
- "version": "1.3.35",
3
+ "version": "1.3.37",
4
4
  "description": "工具库",
5
5
  "main": "./dist/index.esm.js",
6
6
  "type": "module",
@@ -51,7 +51,7 @@
51
51
  "defu": "^6.1.4",
52
52
  "klona": "^2.0.6",
53
53
  "tailwind-merge": "^3.5.0",
54
- "@dazhicheng/openapi": "1.1.8"
54
+ "@dazhicheng/openapi": "1.1.10"
55
55
  },
56
56
  "peerDependencies": {
57
57
  "axios": "^1.0.0",
package/src/openapi.ts CHANGED
@@ -1,133 +1,168 @@
1
- import type { GenerateServiceProps } from "@dazhicheng/openapi";
2
- import type { APIDataType } from "@dazhicheng/openapi/serviceGenerator";
3
- import { ttOpenAPI } from "@dazhicheng/openapi";
4
- import process from "node:process";
5
-
6
- /**
7
- * 将 kebab-case 或 snake_case 转为 PascalCase,如 user-center → UserCenter
8
- */
9
- function toPascalCase(str: string): string {
10
- return str
11
- .split(/[-_]/)
12
- .map(s => s.charAt(0).toUpperCase() + s.slice(1))
13
- .join("");
14
- }
15
-
16
- export async function runOpenAPI(
17
- envConfig: Record<string, string> = {
18
- dev: "192.168.128.215:11000",
19
- sit: "192.168.129.178:9768",
20
- main: "192.168.129.178:9768",
21
- },
22
- servicesData: Record<string, string[]> = {
23
- iam: [],
24
- rule: ["/procurementTicketConfig/delete"],
25
- // basic: [],
26
- },
27
- ) {
28
- const _envConfig = envConfig;
29
-
30
- const envs = Object.keys(_envConfig) as Env[];
31
-
32
- const env = process.argv[2];
33
-
34
- if (!env || !envs.includes(env as any)) {
35
- console.error(`❌ 请传入环境参数: pnpm openapi ${envs.join(" | ")}`);
36
- process.exit(1);
37
- }
38
-
39
- type Env = keyof typeof _envConfig;
40
-
41
- const microServices = servicesData;
42
-
43
- function getServices(env: Env): GenerateServiceProps[] {
44
- const host = _envConfig[env];
45
- return Object.entries(microServices).map(([name, paths]) => ({
46
- schemaPath: `http://${host}/${name}/v3/api-docs`,
47
- serversPath: "./src/api",
48
- projectName: name,
49
- namespace: `${toPascalCase(name)}API`,
50
- requestLibPath: "import request from '@/utils/http'",
51
- // 指定生成某些接口,不传则全量生成
52
- specifiedPaths: paths,
53
- apiPrefix: name,
54
- }));
55
- }
56
-
57
- const services = getServices(env as any);
58
-
59
- /**
60
- * @description 将路径模板转成名称:按 `/` 分段,去掉路径变量(如 `${id}`、`{id}`),
61
- * 再把剩余段从右往左拼成驼峰(最后一段保持原样作为基底,向左各段首字母大写后拼到前面)。
62
- * 例如:`/api/user/${id}/profile` → `profileUserApi`,`/order/{orderId}` → `order`。
63
- */
64
- function pathToName(pathTemplate: string): string {
65
- // 同时过滤 ${var} {var} 形式的路径变量
66
- const VARIABLE_PATTERN = /^\$?\{[^}]+\}$/;
67
- const parts = pathTemplate.split("/").filter(part => part && !VARIABLE_PATTERN.test(part));
68
- return parts
69
- .slice()
70
- .reverse()
71
- .reduce<string>(
72
- (name, tag, index) => (index === 0 ? tag : name + tag.charAt(0).toUpperCase() + tag.slice(1)),
73
- "",
74
- );
75
- }
76
-
77
- const commonHook = {
78
- customFunctionName(data: APIDataType & { _namesWithNumericSuffix?: Set<string> }) {
79
- // const reserved = [
80
- // "export",
81
- // "import",
82
- // "delete",
83
- // "default",
84
- // "class",
85
- // "new",
86
- // "return",
87
- // "switch",
88
- // "case",
89
- // "throw",
90
- // "try",
91
- // "catch",
92
- // "finally",
93
- // "const",
94
- // "let",
95
- // "var",
96
- // "function",
97
- // // 配合后端的特殊字段
98
- // "page",
99
- // "list",
100
- // "matchConfig",
101
- // "enableDisable",
102
- // "exportExcel",
103
- // "selectList",
104
- // "queryById",
105
- // ];
106
- // const name = data.operationId!.split("_")[0]!;
107
- // if (reserved.includes(name)) {
108
- // const tag = data.path?.split("/").filter(Boolean)[0] || "";
109
- // return `${name}${tag.charAt(0).toUpperCase() + tag.slice(1)}`;
110
- // }
111
- // return name;
112
- return pathToName(data.path);
113
- },
114
- customFileNames(operationObject: any, apiPath: string) {
115
- const segments = apiPath.split("/").filter(Boolean);
116
- return segments[0] ? [segments[0]] : [];
117
- },
118
- };
119
-
120
- for (const config of services) {
121
- console.log(`🚀 [${env}] 正在生成: ${config.projectName} -> ${config.schemaPath}`);
122
- try {
123
- await ttOpenAPI({
124
- ...config,
125
- isCamelCase: true,
126
- hook: commonHook,
127
- });
128
- console.log(`✅ ${config.projectName} 生成完成`);
129
- } catch (error: any) {
130
- console.error(`❌ ${config.projectName} 生成失败: ${error.message}`);
131
- }
132
- }
133
- }
1
+ import type { GenerateServiceProps } from "@dazhicheng/openapi";
2
+ import type { APIDataType } from "@dazhicheng/openapi/serviceGenerator";
3
+ import { ttOpenAPI } from "@dazhicheng/openapi";
4
+ import process from "node:process";
5
+
6
+ type DevConfig = "dev" | "sit" | "main";
7
+
8
+ /**
9
+ * kebab-case 或 snake_case 转为 PascalCase,如 user-center → UserCenter
10
+ */
11
+ function toPascalCase(str: string): string {
12
+ return str
13
+ .split(/[-_]/)
14
+ .map(s => s.charAt(0).toUpperCase() + s.slice(1))
15
+ .join("");
16
+ }
17
+
18
+ type BasicAuthCredential = {
19
+ username: string;
20
+ password: string;
21
+ };
22
+
23
+ function toBasicAuthorization(credential?: BasicAuthCredential) {
24
+ if (!credential?.username || !credential?.password) {
25
+ return undefined;
26
+ }
27
+ return `Basic ${Buffer.from(`${credential.username}:${credential.password}`).toString("base64")}`;
28
+ }
29
+
30
+ export async function runOpenAPI(
31
+ envConfig: Record<string, string> = {
32
+ dev: "192.168.128.215:11000",
33
+ sit: "192.168.129.178:9768",
34
+ main: "192.168.129.178:9768",
35
+ },
36
+ servicesData: Record<string, string[]> = {
37
+ // iam: [],
38
+ // rule: ["/procurementTicketConfig/delete"],
39
+ // basic: [],
40
+ },
41
+ authorization?:
42
+ | string
43
+ | ((ctx: { env: DevConfig; host: string }) => Promise<string | undefined> | string | undefined),
44
+ authConfig: Record<DevConfig, BasicAuthCredential> = {
45
+ dev: { username: "swadmin", password: "tt123456!" },
46
+ sit: { username: "swadmin", password: "tt123456!" },
47
+ main: { username: "swadmin", password: "tt123456!" },
48
+ },
49
+ ) {
50
+ const _envConfig = envConfig;
51
+
52
+ const envs = Object.keys(_envConfig) as Env[];
53
+
54
+ const env = process.argv[2];
55
+
56
+ if (!env || !envs.includes(env as any)) {
57
+ console.error(`❌ 请传入环境参数: pnpm openapi ${envs.join(" | ")}`);
58
+ process.exit(1);
59
+ }
60
+
61
+ type Env = keyof typeof _envConfig;
62
+
63
+ const microServices = servicesData;
64
+
65
+ function getServices(env: Env): GenerateServiceProps[] {
66
+ const host = _envConfig[env];
67
+ return Object.entries(microServices).map(([name, paths]) => ({
68
+ schemaPath: `http://${host}/${name}/v3/api-docs`,
69
+ serversPath: "./src/api",
70
+ projectName: name,
71
+ namespace: `${toPascalCase(name)}API`,
72
+ requestLibPath: "import request from '@/utils/http'",
73
+ // 指定生成某些接口,不传则全量生成
74
+ specifiedPaths: paths,
75
+ apiPrefix: name,
76
+ }));
77
+ }
78
+
79
+ const services = getServices(env as DevConfig);
80
+ const host = _envConfig[env as Env];
81
+
82
+ async function resolveAuthorization() {
83
+ if (!authorization) {
84
+ return toBasicAuthorization(authConfig?.[env as DevConfig]);
85
+ }
86
+ if (typeof authorization === "string") {
87
+ return authorization;
88
+ }
89
+ return authorization({ env: env as DevConfig, host: host as string });
90
+ }
91
+
92
+ /**
93
+ * @description 将路径模板转成名称:按 `/` 分段,去掉路径变量(如 `${id}`、`{id}`),
94
+ * 再把剩余段从右往左拼成驼峰(最后一段保持原样作为基底,向左各段首字母大写后拼到前面)。
95
+ * 例如:`/api/user/${id}/profile` → `profileUserApi`,`/order/{orderId}` → `order`。
96
+ */
97
+ function pathToName(pathTemplate: string): string {
98
+ // 同时过滤 ${var} 与 {var} 形式的路径变量
99
+ const VARIABLE_PATTERN = /^\$?\{[^}]+\}$/;
100
+ const parts = pathTemplate.split("/").filter(part => part && !VARIABLE_PATTERN.test(part));
101
+ return parts
102
+ .slice()
103
+ .reverse()
104
+ .reduce<string>(
105
+ (name, tag, index) => (index === 0 ? tag : name + tag.charAt(0).toUpperCase() + tag.slice(1)),
106
+ "",
107
+ );
108
+ }
109
+
110
+ const commonHook = {
111
+ customFunctionName(data: APIDataType & { _namesWithNumericSuffix?: Set<string> }) {
112
+ // const reserved = [
113
+ // "export",
114
+ // "import",
115
+ // "delete",
116
+ // "default",
117
+ // "class",
118
+ // "new",
119
+ // "return",
120
+ // "switch",
121
+ // "case",
122
+ // "throw",
123
+ // "try",
124
+ // "catch",
125
+ // "finally",
126
+ // "const",
127
+ // "let",
128
+ // "var",
129
+ // "function",
130
+ // // 配合后端的特殊字段
131
+ // "page",
132
+ // "list",
133
+ // "matchConfig",
134
+ // "enableDisable",
135
+ // "exportExcel",
136
+ // "selectList",
137
+ // "queryById",
138
+ // ];
139
+ // const name = data.operationId!.split("_")[0]!;
140
+ // if (reserved.includes(name)) {
141
+ // const tag = data.path?.split("/").filter(Boolean)[0] || "";
142
+ // return `${name}${tag.charAt(0).toUpperCase() + tag.slice(1)}`;
143
+ // }
144
+ // return name;
145
+ return pathToName(data.path);
146
+ },
147
+ customFileNames(operationObject: any, apiPath: string) {
148
+ const segments = apiPath.split("/").filter(Boolean);
149
+ return segments[0] ? [segments[0]] : [];
150
+ },
151
+ };
152
+
153
+ for (const config of services) {
154
+ console.log(`🚀 [${env}] 正在生成: ${config.projectName} -> ${config.schemaPath}`);
155
+ try {
156
+ const authHeader = await resolveAuthorization();
157
+ await ttOpenAPI({
158
+ ...config,
159
+ authorization: authHeader,
160
+ isCamelCase: true,
161
+ hook: commonHook,
162
+ });
163
+ console.log(`✅ ${config.projectName} 生成完成`);
164
+ } catch (error: any) {
165
+ console.error(`❌ ${config.projectName} 生成失败: ${error.message}`);
166
+ }
167
+ }
168
+ }