-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_api_files_temp.py
More file actions
231 lines (201 loc) · 5.49 KB
/
create_api_files_temp.py
File metadata and controls
231 lines (201 loc) · 5.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import os
base_dir = r'C:\Users\Ni0daunn\Desktop\work\EzMonitor\app\monitor-app'
types_dir = os.path.join(base_dir, 'src', 'types')
api_dir = os.path.join(base_dir, 'src', 'api')
# 创建目录
os.makedirs(types_dir, exist_ok=True)
print(f'Created: {types_dir}')
os.makedirs(api_dir, exist_ok=True)
print(f'Created: {api_dir}')
# 创建 api.ts
api_types_content = '''/**
* API 响应通用结构
*/
export interface ApiResponse<T = any> {
code: number;
message: string;
data: T;
}
/**
* 分页请求参数
*/
export interface PaginationParams {
page: number;
pageSize: number;
}
/**
* 分页响应数据
*/
export interface PaginationResponse<T = any> {
list: T[];
total: number;
page: number;
pageSize: number;
}
/**
* API 错误响应
*/
export interface ApiError {
code: number;
message: string;
details?: any;
}
'''
with open(os.path.join(types_dir, 'api.ts'), 'w', encoding='utf-8') as f:
f.write(api_types_content)
print('Created: src/types/api.ts')
# 创建 client.ts
client_content = '''import axios, {
AxiosInstance,
AxiosRequestConfig,
AxiosResponse,
InternalAxiosRequestConfig,
} from 'axios';
import type { ApiResponse, ApiError } from '../types/api';
/**
* 创建 Axios 实例
*/
const apiClient: AxiosInstance = axios.create({
baseURL: 'http://localhost:3001',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
/**
* 请求拦截器
*/
apiClient.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
// 可以在这里添加 token
const token = localStorage.getItem('token');
if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}`;
}
// 请求日志(开发环境)
if (import.meta.env.DEV) {
console.log('📤 API Request:', {
method: config.method?.toUpperCase(),
url: config.url,
params: config.params,
data: config.data,
});
}
return config;
},
(error) => {
console.error('❌ Request Error:', error);
return Promise.reject(error);
}
);
/**
* 响应拦截器
*/
apiClient.interceptors.response.use(
(response: AxiosResponse<ApiResponse>) => {
// 响应日志(开发环境)
if (import.meta.env.DEV) {
console.log('📥 API Response:', {
url: response.config.url,
status: response.status,
data: response.data,
});
}
// 统一处理业务错误码
const { code, message, data } = response.data;
if (code !== 0 && code !== 200) {
const error: ApiError = {
code,
message: message || '请求失败',
details: data,
};
console.error('❌ Business Error:', error);
// 可以在这里添加全局错误提示
return Promise.reject(error);
}
return response;
},
(error) => {
// 处理 HTTP 错误
let errorMessage = '网络请求失败';
let errorCode = -1;
if (error.response) {
// 服务器返回错误状态码
const { status, data } = error.response;
errorCode = status;
switch (status) {
case 401:
errorMessage = '未授权,请重新登录';
// 可以在这里跳转到登录页
break;
case 403:
errorMessage = '拒绝访问';
break;
case 404:
errorMessage = '请求的资源不存在';
break;
case 500:
errorMessage = '服务器错误';
break;
case 502:
errorMessage = '网关错误';
break;
case 503:
errorMessage = '服务不可用';
break;
default:
errorMessage = data?.message || `请求失败 (${status})`;
}
} else if (error.request) {
// 请求已发送但没有收到响应
errorMessage = '服务器无响应,请检查网络连接';
} else {
// 请求配置出错
errorMessage = error.message || '请求配置错误';
}
const apiError: ApiError = {
code: errorCode,
message: errorMessage,
details: error.response?.data,
};
console.error('❌ HTTP Error:', apiError);
// 可以在这里添加全局错误提示(如 message.error)
return Promise.reject(apiError);
}
);
/**
* 封装的请求方法
*/
export const request = {
get: <T = any>(url: string, config?: AxiosRequestConfig) => {
return apiClient.get<ApiResponse<T>>(url, config);
},
post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) => {
return apiClient.post<ApiResponse<T>>(url, data, config);
},
put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) => {
return apiClient.put<ApiResponse<T>>(url, data, config);
},
delete: <T = any>(url: string, config?: AxiosRequestConfig) => {
return apiClient.delete<ApiResponse<T>>(url, config);
},
patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig) => {
return apiClient.patch<ApiResponse<T>>(url, data, config);
},
};
export default apiClient;
'''
with open(os.path.join(api_dir, 'client.ts'), 'w', encoding='utf-8') as f:
f.write(client_content)
print('Created: src/api/client.ts')
# 创建 index.ts
index_content = '''/**
* API 统一导出
*/
export { default as apiClient, request } from './client';
export type { ApiResponse, ApiError, PaginationParams, PaginationResponse } from '../types/api';
'''
with open(os.path.join(api_dir, 'index.ts'), 'w', encoding='utf-8') as f:
f.write(index_content)
print('Created: src/api/index.ts')
print('\n✅ All files created successfully!')