Skip to content

Commit e44d91c

Browse files
committed
refactor: update toolkit
1 parent 58f9312 commit e44d91c

35 files changed

+1460
-1276
lines changed

toolkit/demos/simple.ts

Lines changed: 53 additions & 171 deletions
Original file line numberDiff line numberDiff line change
@@ -1,183 +1,65 @@
1-
// src/demo.ts
2-
import { api, types, utils } from '../src';
1+
// src/services/articleService.ts
2+
import api, { types, utils } from '@/api';
33

4-
// 使用类型定义
5-
const exampleUser: types.IUser = {
6-
name: '张三',
7-
password: 'hashed_password', // 实际应用中应该是加密后的密码
8-
avatar: 'https://example.com/avatar.jpg',
9-
10-
role: 'user',
11-
status: 'active',
12-
type: 'local',
13-
createAt: new Date().toISOString(),
14-
updateAt: new Date().toISOString()
15-
};
16-
17-
const exampleArticle: types.IArticle = {
18-
id: '1',
19-
title: '示例文章',
20-
cover: 'https://example.com/cover.jpg',
21-
summary: '这是一篇示例文章的摘要',
22-
content: '这是文章的完整内容...',
23-
html: '<p>这是文章的HTML内容...</p>',
24-
toc: '[]',
25-
category: {
26-
id: '1',
27-
label: '技术',
28-
value: 'tech',
29-
articles: [],
30-
createAt: new Date().toISOString(),
31-
updateAt: new Date().toISOString()
32-
},
33-
tags: ['typescript', 'api'],
34-
status: 'published',
35-
views: 0,
36-
likes: 0,
37-
isRecommended: false,
38-
password: '',
39-
needPassword: false,
40-
isCommentable: true,
41-
publishAt: new Date().toISOString(),
42-
createAt: new Date().toISOString(),
43-
updateAt: new Date().toISOString()
44-
};
45-
46-
// API 调用示例
47-
async function demoAPIUsage() {
48-
try {
49-
console.log('🚀 开始 API 演示...');
50-
51-
// 1. 获取所有用户
52-
console.log('📋 获取用户列表...');
53-
const users = await api.UserController_findAll();
54-
console.log('✅ 用户列表:', users);
55-
56-
// 2. 注册新用户
57-
console.log('📋 注册新用户...');
58-
const newUser = await api.UserController_register(exampleUser);
59-
console.log('✅ 新用户:', newUser);
60-
61-
// 3. 获取所有文章
62-
console.log('📋 获取文章列表...');
63-
const articles = await api.ArticleController_findAll();
64-
console.log('✅ 文章列表:', articles);
65-
66-
// 4. 创建新文章
67-
console.log('📋 创建新文章...');
68-
const createdArticle = await api.ArticleController_create(exampleArticle);
69-
console.log('✅ 新文章:', createdArticle);
70-
71-
// 5. 获取特定文章
72-
console.log('📋 获取特定文章...');
73-
const article = await api.ArticleController_findById({ id: '1' });
74-
console.log('✅ 文章详情:', article);
75-
76-
// 6. 更新文章浏览量
77-
console.log('📋 更新文章浏览量...');
78-
const updatedArticle = await api.ArticleController_updateViewsById({ id: '1' });
79-
console.log('✅ 更新后的文章:', updatedArticle);
4+
// 文章服务层
5+
export class ArticleService {
6+
// 获取所有文章
7+
static async getAllArticles() {
8+
try {
9+
const articles = await api.article.findAll();
10+
11+
// 格式化数据
12+
return articles.map(article => ({
13+
...article,
14+
formattedDate: utils.formatDate(new Date(article.createdAt || Date.now())),
15+
}));
16+
} catch (error) {
17+
throw this.handleError(error, '获取文章列表失败');
18+
}
19+
}
8020

81-
} catch (error) {
82-
console.error('❌ API 调用失败:', error);
83-
84-
// 使用工具函数处理错误
85-
if (error instanceof utils.ApiError) {
86-
console.error(`错误代码: ${error.code}, 消息: ${error.message}`);
21+
// 获取单篇文章
22+
static async getArticleById(id: string) {
23+
try {
24+
return await api.article.findById(id);
25+
} catch (error) {
26+
throw this.handleError(error, '获取文章失败');
8727
}
8828
}
89-
}
9029

91-
// 使用工具函数示例
92-
function demoUtilsUsage() {
93-
console.log('🛠️ 工具函数演示...');
94-
95-
// 1. 日期格式化
96-
const formattedDate = utils.formatDate(new Date(), 'YYYY年MM月DD日');
97-
console.log('✅ 格式化日期:', formattedDate);
98-
99-
// 2. 深度克隆
100-
const original = { name: '张三', profile: { age: 30 } };
101-
const cloned = utils.deepClone(original);
102-
console.log('✅ 深度克隆:', cloned);
103-
104-
// 3. 防抖函数
105-
const debouncedSearch = utils.debounce((query: string) => {
106-
console.log('🔍 搜索:', query);
107-
}, 300);
108-
109-
// 模拟搜索输入
110-
debouncedSearch('typescript');
111-
debouncedSearch('typescript api');
112-
113-
// 4. 节流函数
114-
const throttledScroll = utils.throttle((position: number) => {
115-
console.log('📜 滚动位置:', position);
116-
}, 1000);
117-
118-
// 模拟滚动事件
119-
throttledScroll(100);
120-
throttledScroll(200);
121-
throttledScroll(300);
122-
}
30+
// 创建文章
31+
static async createArticle(articleData: Partial<types.IArticle>) {
32+
try {
33+
return await api.article.create(articleData);
34+
} catch (error) {
35+
throw this.handleError(error, '创建文章失败');
36+
}
37+
}
12338

124-
// 高级用法示例
125-
async function demoAdvancedUsage() {
126-
console.log('🎯 高级用法演示...');
127-
128-
try {
129-
// 1. 使用 HTTP 客户端直接调用 API
130-
console.log('📋 使用 HTTP 客户端直接调用...');
131-
const httpClient = await import('@fecommunity/toolkit/utils').then(m => m.httpClient);
132-
133-
const response = await httpClient.get('/api/user');
134-
console.log('✅ 直接HTTP调用结果:', response);
135-
136-
// 2. 批量操作
137-
console.log('📋 批量获取数据...');
138-
const [users, articles, settings] = await Promise.all([
139-
api.UserController_findAll(),
140-
api.ArticleController_findAll(),
141-
api.SettingController_findAll()
142-
]);
143-
144-
console.log('✅ 批量获取完成:');
145-
console.log(' 用户数量:', users.length);
146-
console.log(' 文章数量:', articles.length);
147-
148-
// 3. 错误处理策略
149-
console.log('📋 错误处理演示...');
39+
// 更新文章
40+
static async updateArticle(id: string, updates: Partial<types.IArticle>) {
15041
try {
151-
// 模拟一个可能失败的请求
152-
await api.ArticleController_findById({ id: 'non-existent-id' });
42+
return await api.article.updateById(id, updates);
15343
} catch (error) {
154-
if (utils.isApiError(error)) {
155-
console.log('✅ 错误已正确处理:', error.message);
156-
} else {
157-
console.log('✅ 其他类型错误:', error.message);
158-
}
44+
throw this.handleError(error, '更新文章失败');
15945
}
160-
161-
} catch (error) {
162-
console.error('❌ 高级用法演示失败:', error);
16346
}
164-
}
16547

166-
// 完整演示
167-
async function runDemo() {
168-
console.log('🎬 开始 Toolkit 演示\n');
169-
170-
// 演示工具函数
171-
demoUtilsUsage();
172-
173-
// 演示 API 调用
174-
await demoAPIUsage();
175-
176-
// 演示高级用法
177-
await demoAdvancedUsage();
178-
179-
console.log('\n🎉 Toolkit 演示完成!');
180-
}
48+
// 删除文章
49+
static async deleteArticle(id: string) {
50+
try {
51+
return await api.article.deleteById(id);
52+
} catch (error) {
53+
throw this.handleError(error, '删除文章失败');
54+
}
55+
}
18156

182-
// 运行演示
183-
runDemo().catch(console.error);
57+
// 统一错误处理
58+
private static handleError(error: unknown, defaultMessage: string) {
59+
if (utils.ApiError.isInstance(error)) {
60+
return error;
61+
}
62+
63+
return new utils.ApiError(500, defaultMessage, error);
64+
}
65+
}

toolkit/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@fecommunity/reactpress-tookit",
3-
"version": "1.0.0",
3+
"version": "1.0.0-beta.0",
44
"main": "index.js",
55
"scripts": {
66
"generate": "node scripts/generate-swagger.js"

0 commit comments

Comments
 (0)