Просмотр исходного кода

✨ feat(client): 重构API客户端架构,支持多模块调用

- 引入所有API路由类型定义,实现类型安全调用
- 按RPC规范重命名客户端实例,新增authClient、userClient等10+客户端
- 优化银龄用户资源客户端结构,使用集中对象管理相关接口

♻️ refactor(utils): 优化axios fetch适配器实现

- 重构axiosFetch函数参数处理逻辑,支持RequestInfo和URL类型输入
- 显式设置responseType为json,确保响应正确解析
- 统一错误处理机制,提高适配器稳定性

🔧 chore(server): 调整路由导入顺序,优化代码组织

- 将silverUserProfileRoutes和silverTalentsAdminRoutes导入移至文件顶部
- 保持路由注册逻辑不变,提升代码可读性和维护性
yourname 10 месяцев назад
Родитель
Сommit
29f227d725
3 измененных файлов с 150 добавлено и 33 удалено
  1. 128 12
      src/client/api.ts
  2. 20 19
      src/client/utils/axios.ts
  3. 2 2
      src/server/api.ts

+ 128 - 12
src/client/api.ts

@@ -1,17 +1,133 @@
-import { hc } from 'hono/client'
+import { hc } from 'hono/client';
+import type {
+  AuthRoutes,
+  UserRoutes,
+  RoleRoutes,
+  FileRoutes,
+  CompanyRoutes,
+  JobRoutes,
+  ApplicationRoutes,
+  FavoriteRoutes,
+  ViewRoutes,
+  CompanyImageRoutes,
+  SilverTalentsRoutes,
+  ElderlyUniversityRoutes,
+  PolicyNewsRoutes,
+  UserPreferenceRoutes,
+  HomeRoutes,
+  SilverUsersKnowledgesRoutes,
+  SilverUsersKnowledgeCategoriesRoutes,
+  SilverUsersKnowledgeTagsRoutes,
+  SilverUsersKnowledgeStatsRoutes,
+  SilverUsersKnowledgeInteractionsRoutes,
+  SilverUsersKnowledgeRankingsRoutes,
+  SilverTalentsAdminRoutes,
+  MyCompanyRoutes
+} from '@/server/api';
 import { axiosFetch } from './utils/axios'
-import { type SilverTalentsAdminRoutes } from '@/server/api'
 
-// 银龄库管理客户端
-export const silverTalentsAdminClient = hc<SilverTalentsAdminRoutes>('/api/v1', {
+// 客户端实例 - 严格按照RPC规范命名
+export const authClient = hc<AuthRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1.auth;
+
+export const userClient = hc<UserRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1.users;
+
+export const roleClient = hc<RoleRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1.roles;
+
+export const fileClient = hc<FileRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1.files;
+
+// 企业信息客户端 - 新增
+export const myCompanyClient = hc<MyCompanyRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['companies'].my;
+ 
+// 银龄岗具体资源客户端(调整为标准格式)
+export const companyClient = hc<CompanyRoutes>('/', {
   fetch: axiosFetch,
-}).api.v1.admin['silver-talents']
+}).api.v1['silver-jobs'].companies;
 
-// 类型定义
-export type SilverTalentAdminList = InferResponseType<typeof silverTalentsAdminClient.$get, 200>
-export type SilverTalentAdminDetail = InferResponseType<typeof silverTalentsAdminClient[':id'].$get, 200>
-export type SilverTalentAdminStats = InferResponseType<typeof silverTalentsAdminClient.stats.$get, 200>
-export type UpdateSilverTalentRequest = InferRequestType<typeof silverTalentsAdminClient[':id'].$put>['json']
-export type UpdateCertificationRequest = InferRequestType<typeof silverTalentsAdminClient[':id']['certification'].$patch>['json']
+export const jobClient = hc<JobRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['silver-jobs'].jobs;
+
+export const applicationClient = hc<ApplicationRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['silver-jobs'].applications;
+
+export const favoriteClient = hc<FavoriteRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['silver-jobs'].favorites;
+
+export const viewClient = hc<ViewRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['silver-jobs'].views;
 
-import type { InferResponseType, InferRequestType } from 'hono/client'
+export const companyImageClient = hc<CompanyImageRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['silver-jobs']['company-images'];
+
+// 银龄用户资源客户端 - 重构为集中的对象,避免过深实例化
+export const silverUsersClient = {
+  knowledges: hc<SilverUsersKnowledgesRoutes>('/', {
+    fetch: axiosFetch,
+  }).api.v1['silver-users'].knowledges,
+  
+  ['knowledge-categories']: hc<SilverUsersKnowledgeCategoriesRoutes>('/', {
+    fetch: axiosFetch,
+  }).api.v1['silver-users']['knowledge-categories'],
+  
+  ['knowledge-tags']: hc<SilverUsersKnowledgeTagsRoutes>('/', {
+    fetch: axiosFetch,
+  }).api.v1['silver-users']['knowledge-tags'],
+  
+  ['knowledge-stats']: hc<SilverUsersKnowledgeStatsRoutes>('/', {
+    fetch: axiosFetch,
+  }).api.v1['silver-users']['knowledge-stats'],
+  
+  ['knowledge-interactions']: hc<SilverUsersKnowledgeInteractionsRoutes>('/', {
+    fetch: axiosFetch,
+  }).api.v1['silver-users']['knowledge-interactions'],
+  
+  ['knowledge-rankings']: hc<SilverUsersKnowledgeRankingsRoutes>('/', {
+    fetch: axiosFetch,
+  }).api.v1['silver-users']['knowledge-rankings'],
+  
+  profiles: hc<any>('/', {
+    fetch: axiosFetch,
+  }).api.v1['silver-users'].profiles
+};
+
+// 其他资源客户端
+export const elderlyUniversityClient = hc<ElderlyUniversityRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['elderly-universities'];
+
+export const policyNewsClient = hc<PolicyNewsRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['policy-news'];
+
+export const userPreferenceClient = hc<UserPreferenceRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['user-preferences'];
+
+// 首页API客户端
+export const homeClient = hc<HomeRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1.home;
+
+export const silverTalentsClient = hc<SilverTalentsRoutes>('/', {
+  fetch: axiosFetch,
+}).api.v1['silver-talents']
+
+
+// 银龄库管理客户端
+export const silverTalentsAdminClient = hc<SilverTalentsAdminRoutes>('/api/v1', {
+  fetch: axiosFetch,
+}).api.v1.admin['silver-talents']

+ 20 - 19
src/client/utils/axios.ts

@@ -1,28 +1,29 @@
 import axios from 'axios'
 
-export const axiosFetch: typeof fetch = async (input, init) => {
-  const config: any = {
-    method: init?.method || 'GET',
-    url: input instanceof Request ? input.url : input as string,
-    headers: init?.headers ? Object.fromEntries(new Map(init.headers as any)) : {},
-    data: init?.body,
-  }
+// 创建axios fetch适配器
+export const axiosFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
+  
+  const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
+  const method = init?.method || 'GET';
+  const headers = init?.headers ? Object.fromEntries(new Map(init.headers as any)) : {};
+  const data = init?.body;
 
   try {
-    const response = await axios(config)
+    const response = await axios({
+      url,
+      method,
+      headers,
+      data,
+      responseType: 'json',
+      validateStatus: () => true,
+    });
+
     return new Response(JSON.stringify(response.data), {
       status: response.status,
       statusText: response.statusText,
       headers: response.headers as any,
-    })
-  } catch (error: any) {
-    if (error.response) {
-      return new Response(JSON.stringify(error.response.data), {
-        status: error.response.status,
-        statusText: error.response.statusText,
-        headers: error.response.headers as any,
-      })
-    }
-    throw error
+    });
+  } catch (error) {
+    throw error;
   }
-}
+};

+ 2 - 2
src/server/api.ts

@@ -17,6 +17,8 @@ import elderlyUniversityRoutes from './api/elderly-universities/index'
 import policyNewsRoutes from './api/policy-news/index'
 import userPreferenceRoutes from './api/user-preferences/index'
 import homeRoutes from './api/home/index'
+import silverUserProfileRoutes from './api/silver-users/profiles/index'
+import silverTalentsAdminRoutes from './api/silver-talents-admin/index'
 import { AuthContext } from './types/context'
 import { AppDataSource } from './data-source'
 
@@ -88,11 +90,9 @@ const silverUsersKnowledgeInteractionsApiRoutes = api.route('/api/v1/silver-user
 const silverUsersKnowledgeRankingsApiRoutes = api.route('/api/v1/silver-users/knowledge-rankings', silverUsersRoutes.knowledgeRankings)
 
 // 注册 silver-user-profiles 路由
-import silverUserProfileRoutes from './api/silver-users/profiles/index'
 const silverUserProfileApiRoutes = api.route('/api/v1/silver-users/profiles', silverUserProfileRoutes)
 
 // 注册银龄库管理后台路由
-import silverTalentsAdminRoutes from './api/silver-talents-admin/index'
 const silverTalentsAdminApiRoutes = api.route('/api/v1/admin/silver-talents', silverTalentsAdminRoutes)
 
 export type AuthRoutes = typeof authRoutes