Skip to content

Commit cbbfd70

Browse files
committed
refactor: update api generator
1 parent d4a8568 commit cbbfd70

File tree

17 files changed

+540
-252
lines changed

17 files changed

+540
-252
lines changed

toolkit/demos/simple.ts

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
// src/services/articleService.ts
2-
import api, { types, utils } from '@/api';
2+
import api, { types, utils } from '../dist';
33

44
// 文章服务层
55
export class ArticleService {
66
// 获取所有文章
77
static async getAllArticles() {
88
try {
9-
const articles = await api.article.findAll();
9+
const articles = await api.article.getRecommendArticles({});
1010

1111
// 格式化数据
12-
return articles.map(article => ({
12+
return articles.data.map(article => ({
1313
...article,
1414
formattedDate: utils.formatDate(new Date(article.createdAt || Date.now())),
1515
}));
@@ -30,7 +30,7 @@ export class ArticleService {
3030
// 创建文章
3131
static async createArticle(articleData: Partial<types.IArticle>) {
3232
try {
33-
return await api.article.create(articleData);
33+
return await api.article.create({});
3434
} catch (error) {
3535
throw this.handleError(error, '创建文章失败');
3636
}
@@ -39,7 +39,7 @@ export class ArticleService {
3939
// 更新文章
4040
static async updateArticle(id: string, updates: Partial<types.IArticle>) {
4141
try {
42-
return await api.article.updateById(id, updates);
42+
return await api.article.updateById(id);
4343
} catch (error) {
4444
throw this.handleError(error, '更新文章失败');
4545
}

toolkit/scripts/generate-api-types.js

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,12 @@ async function generateApiTypes() {
3535
httpClientType: 'axios',
3636
typePrefix: 'I',
3737
generateClient: true,
38+
generateResponses: true,
39+
extractRequestParams: true,
40+
extractResponseBody: true,
41+
extractRequestBody: true,
42+
extractResponseHeaders: true,
43+
generateResponseTypes: true,
3844
hooks: {
3945
onPrepareConfig: (currentConfiguration) => {
4046
const config = currentConfiguration.config;
@@ -89,10 +95,10 @@ async function organizeGeneratedFiles() {
8995
} else if (file.includes('contract') || file === 'types.ts') {
9096
// 类型定义文件
9197
fs.moveSync(filePath, path.join(typesDir, file === 'types.ts' ? 'index.ts' : file), { overwrite: true });
92-
console.log(`📄 移动类型文件: ${file} -> types/`);
98+
console.log(`📄 移动类型文件: {file} -> types/`);
9399
} else {
94100
// 其他文件留在根目录
95-
console.log(`📄 保留文件: ${file}`);
101+
console.log(`📄 保留文件: {file}`);
96102
}
97103
}
98104
});
@@ -215,14 +221,15 @@ async function renameApiMethods() {
215221
const filePath = path.join(apiDir, file);
216222
let content = fs.readFileSync(filePath, 'utf8');
217223

218-
// 使用正则表达式匹配并重命名方法
224+
// 使用更精确的正则表达式匹配并重命名方法
219225
// 匹配模式: 方法名以 Controller 开头,后面跟着大写字母
226+
// 例如: articleControllerFindById -> findById
220227
content = content.replace(
221228
/(\w+)Controller([A-Z]\w+)/g,
222-
(match, prefix, methodName) => {
229+
(match, className, methodName) => {
223230
// 将方法名的首字母小写
224231
const newMethodName = methodName.charAt(0).toLowerCase() + methodName.slice(1);
225-
return `${prefix}${newMethodName}`;
232+
return newMethodName;
226233
}
227234
);
228235

@@ -289,10 +296,17 @@ async function createMainIndex() {
289296
const mainIndexContent = `// Auto-generated API client
290297
// Generated from Swagger/OpenAPI specification
291298
292-
export * from './api';
293-
export * from './types';
294-
export * from './utils';
299+
// 导出 API 实例
300+
export { default as api } from './api/ApiInstance';
301+
export * from './api/ApiInstance';
295302
303+
// 导出类型定义
304+
export * as types from './types';
305+
306+
// 导出工具函数
307+
export * as utils from './utils';
308+
309+
// 默认导出 API 实例
296310
export { default } from './api/ApiInstance';
297311
`;
298312

@@ -563,13 +577,14 @@ generateApiTypes()
563577
console.log('');
564578
console.log('💡 使用方法:');
565579
console.log(' 1. 直接使用默认实例:');
566-
console.log(' import api from \'@/api\';');
567-
console.log(' api.article.findAll();');
580+
console.log(' import api from \'@fe/toolkit\';');
581+
console.log(' api.article.findById();');
568582
console.log('');
569-
console.log(' 2. 创建自定义实例:');
570-
console.log(' import { createApiInstance } from \'@/api\';');
571-
console.log(' const customApi = createApiInstance({ baseURL: \'https://api.example.com\' });');
572-
console.log(' customApi.article.findAll();');
583+
console.log(' 2. 导入所有模块:');
584+
console.log(' import { api, types, utils } from \'@fe/toolkit\';');
585+
console.log(' const articles = await api.article.findAll();');
586+
console.log(' const formattedDate = utils.formatDate(new Date());');
587+
console.log(' const articleType: types.IArticle = { ... };');
573588
})
574589
.catch((error) => {
575590
console.error('❌ API 生成过程失败:', error.message);

toolkit/src/api/Article.ts

Lines changed: 67 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -9,33 +9,48 @@
99
* ---------------------------------------------------------------
1010
*/
1111

12-
import { IArticle } from '../types/data-contracts';
12+
import {
13+
checkPasswordData,
14+
createData,
15+
deleteByIdData,
16+
findAllData,
17+
findArticlesByCategoryData,
18+
findArticlesByTagData,
19+
findByIdData,
20+
getArchivesData,
21+
getRecommendArticlesData,
22+
recommendData,
23+
updateByIdData,
24+
updateLikesByIdData,
25+
updateViewsByIdData,
26+
} from '../types/data-contracts';
1327
import { HttpClient, RequestParams } from './HttpClient';
1428

1529
export class Article<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {
1630
/**
1731
* No description
1832
*
1933
* @tags Article
20-
* @name Articlecreate
34+
* @name create
2135
* @request POST:/article
36+
* @response `200` `createData` 创建文章
2237
*/
23-
articlecreate = (params: RequestParams = {}) =>
24-
this.request<IArticle[], any>({
38+
create = (params: RequestParams = {}) =>
39+
this.request<createData, any>({
2540
path: `/article`,
2641
method: 'POST',
27-
format: 'json',
2842
...params,
2943
});
3044
/**
3145
* No description
3246
*
3347
* @tags Article
34-
* @name ArticlefindAll
48+
* @name findAll
3549
* @request GET:/article
50+
* @response `200` `findAllData`
3651
*/
37-
articlefindAll = (params: RequestParams = {}) =>
38-
this.request<void, any>({
52+
findAll = (params: RequestParams = {}) =>
53+
this.request<findAllData, any>({
3954
path: `/article`,
4055
method: 'GET',
4156
...params,
@@ -44,11 +59,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
4459
* No description
4560
*
4661
* @tags Article
47-
* @name ArticlefindArticlesByCategory
62+
* @name findArticlesByCategory
4863
* @request GET:/article/category/{id}
64+
* @response `200` `findArticlesByCategoryData`
4965
*/
50-
articlefindArticlesByCategory = (id: string, params: RequestParams = {}) =>
51-
this.request<void, any>({
66+
findArticlesByCategory = (id: string, params: RequestParams = {}) =>
67+
this.request<findArticlesByCategoryData, any>({
5268
path: `/article/category/${id}`,
5369
method: 'GET',
5470
...params,
@@ -57,11 +73,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
5773
* No description
5874
*
5975
* @tags Article
60-
* @name ArticlefindArticlesByTag
76+
* @name findArticlesByTag
6177
* @request GET:/article/tag/{id}
78+
* @response `200` `findArticlesByTagData`
6279
*/
63-
articlefindArticlesByTag = (id: string, params: RequestParams = {}) =>
64-
this.request<void, any>({
80+
findArticlesByTag = (id: string, params: RequestParams = {}) =>
81+
this.request<findArticlesByTagData, any>({
6582
path: `/article/tag/${id}`,
6683
method: 'GET',
6784
...params,
@@ -70,11 +87,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
7087
* No description
7188
*
7289
* @tags Article
73-
* @name ArticlegetRecommendArticles
90+
* @name getRecommendArticles
7491
* @request GET:/article/all/recommend
92+
* @response `200` `getRecommendArticlesData`
7593
*/
76-
articlegetRecommendArticles = (params: RequestParams = {}) =>
77-
this.request<void, any>({
94+
getRecommendArticles = (params: RequestParams = {}) =>
95+
this.request<getRecommendArticlesData, any>({
7896
path: `/article/all/recommend`,
7997
method: 'GET',
8098
...params,
@@ -83,11 +101,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
83101
* No description
84102
*
85103
* @tags Article
86-
* @name ArticlegetArchives
104+
* @name getArchives
87105
* @request GET:/article/archives
106+
* @response `200` `getArchivesData`
88107
*/
89-
articlegetArchives = (params: RequestParams = {}) =>
90-
this.request<void, any>({
108+
getArchives = (params: RequestParams = {}) =>
109+
this.request<getArchivesData, any>({
91110
path: `/article/archives`,
92111
method: 'GET',
93112
...params,
@@ -96,11 +115,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
96115
* No description
97116
*
98117
* @tags Article
99-
* @name Articlerecommend
118+
* @name recommend
100119
* @request GET:/article/recommend
120+
* @response `200` `recommendData`
101121
*/
102-
articlerecommend = (params: RequestParams = {}) =>
103-
this.request<void, any>({
122+
recommend = (params: RequestParams = {}) =>
123+
this.request<recommendData, any>({
104124
path: `/article/recommend`,
105125
method: 'GET',
106126
...params,
@@ -109,11 +129,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
109129
* No description
110130
*
111131
* @tags Article
112-
* @name ArticlefindById
132+
* @name findById
113133
* @request GET:/article/{id}
134+
* @response `200` `findByIdData`
114135
*/
115-
articlefindById = (id: string, params: RequestParams = {}) =>
116-
this.request<void, any>({
136+
findById = (id: string, params: RequestParams = {}) =>
137+
this.request<findByIdData, any>({
117138
path: `/article/${id}`,
118139
method: 'GET',
119140
...params,
@@ -122,11 +143,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
122143
* No description
123144
*
124145
* @tags Article
125-
* @name ArticleupdateById
146+
* @name updateById
126147
* @request PATCH:/article/{id}
148+
* @response `200` `updateByIdData`
127149
*/
128-
articleupdateById = (id: string, params: RequestParams = {}) =>
129-
this.request<void, any>({
150+
updateById = (id: string, params: RequestParams = {}) =>
151+
this.request<updateByIdData, any>({
130152
path: `/article/${id}`,
131153
method: 'PATCH',
132154
...params,
@@ -135,11 +157,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
135157
* No description
136158
*
137159
* @tags Article
138-
* @name ArticledeleteById
160+
* @name deleteById
139161
* @request DELETE:/article/{id}
162+
* @response `200` `deleteByIdData`
140163
*/
141-
articledeleteById = (id: string, params: RequestParams = {}) =>
142-
this.request<void, any>({
164+
deleteById = (id: string, params: RequestParams = {}) =>
165+
this.request<deleteByIdData, any>({
143166
path: `/article/${id}`,
144167
method: 'DELETE',
145168
...params,
@@ -148,11 +171,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
148171
* No description
149172
*
150173
* @tags Article
151-
* @name ArticlecheckPassword
174+
* @name checkPassword
152175
* @request POST:/article/{id}/checkPassword
176+
* @response `200` `checkPasswordData`
153177
*/
154-
articlecheckPassword = (id: string, params: RequestParams = {}) =>
155-
this.request<void, any>({
178+
checkPassword = (id: string, params: RequestParams = {}) =>
179+
this.request<checkPasswordData, any>({
156180
path: `/article/${id}/checkPassword`,
157181
method: 'POST',
158182
...params,
@@ -161,11 +185,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
161185
* No description
162186
*
163187
* @tags Article
164-
* @name ArticleupdateViewsById
188+
* @name updateViewsById
165189
* @request POST:/article/{id}/views
190+
* @response `200` `updateViewsByIdData`
166191
*/
167-
articleupdateViewsById = (id: string, params: RequestParams = {}) =>
168-
this.request<void, any>({
192+
updateViewsById = (id: string, params: RequestParams = {}) =>
193+
this.request<updateViewsByIdData, any>({
169194
path: `/article/${id}/views`,
170195
method: 'POST',
171196
...params,
@@ -174,11 +199,12 @@ export class Article<SecurityDataType = unknown> extends HttpClient<SecurityData
174199
* No description
175200
*
176201
* @tags Article
177-
* @name ArticleupdateLikesById
202+
* @name updateLikesById
178203
* @request POST:/article/{id}/likes
204+
* @response `200` `updateLikesByIdData`
179205
*/
180-
articleupdateLikesById = (id: string, params: RequestParams = {}) =>
181-
this.request<void, any>({
206+
updateLikesById = (id: string, params: RequestParams = {}) =>
207+
this.request<updateLikesByIdData, any>({
182208
path: `/article/${id}/likes`,
183209
method: 'POST',
184210
...params,

0 commit comments

Comments
 (0)