Procházet zdrojové kódy

♻️ refactor(api): 重构租户API客户端管理

- 删除旧的api.ts文件,实现租户API客户端管理器tenantClientManager
- 所有API调用统一使用tenantClientManager.get()获取客户端实例
- 优化API请求路径配置方式,便于统一管理和维护

📦 build(deps): 添加axios依赖

- 在tenant-management-ui项目中添加axios@^1.11.0依赖

🔧 chore(init): 调整API客户端初始化位置

- 将租户API客户端初始化从web/src/client/tenant/api_init.ts移动到web/src/client/api_init.ts
- 删除冗余的tenant/api_init.ts文件
yourname před 1 měsícem
rodič
revize
490bc0652b

+ 1 - 0
packages/tenant-management-ui/package.json

@@ -54,6 +54,7 @@
     "@d8d/tenant-module-mt": "workspace:*",
     "@hookform/resolvers": "^5.2.1",
     "@tanstack/react-query": "^5.90.9",
+    "axios": "^1.11.0",
     "class-variance-authority": "^0.7.1",
     "clsx": "^2.1.1",
     "date-fns": "^4.1.0",

+ 0 - 5
packages/tenant-management-ui/src/client/api.ts

@@ -1,5 +0,0 @@
-import { hc } from 'hono/client';
-import { tenantRoutes } from '@d8d/tenant-module-mt';
-
-// 创建租户管理API客户端
-export const tenantClient = hc<typeof tenantRoutes>('/api/tenants');

+ 2 - 2
packages/tenant-management-ui/src/components/TenantConfigPage.tsx

@@ -10,7 +10,7 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
 import { Switch } from '@d8d/shared-ui-components/components/ui/switch';
 import { useForm } from 'react-hook-form';
 import { toast } from 'sonner';
-import { tenantClient } from '../api/tenantClient';
+import { tenantClientManager } from '../api/tenantClient';
 import { useTenantConfig } from '../hooks/useTenantConfig';
 
 interface TenantConfigFormData {
@@ -32,7 +32,7 @@ export const TenantConfigPage = () => {
   const { data: tenant, isLoading: isTenantLoading } = useQuery({
     queryKey: ['tenant', tenantId],
     queryFn: async () => {
-      const res = await tenantClient[':id'].$get({
+      const res = await tenantClientManager.get()[':id'].$get({
         param: { id: tenantId }
       });
       if (res.status !== 200) {

+ 3 - 3
packages/tenant-management-ui/src/components/TenantsPage.tsx

@@ -2,7 +2,7 @@ import React, { useState, useMemo, useCallback } from 'react';
 import { useQuery } from '@tanstack/react-query';
 import { format } from 'date-fns';
 import { Plus, Search, Edit, Trash2, Filter, X } from 'lucide-react';
-import { tenantClient } from '../api/tenantClient';
+import { tenantClientManager, tenantClient } from '../api/tenantClient';
 import type { InferRequestType, InferResponseType } from 'hono/client';
 import { Button } from '@d8d/shared-ui-components/components/ui/button';
 import { Input } from '@d8d/shared-ui-components/components/ui/input';
@@ -94,7 +94,7 @@ export const TenantsPage = () => {
         filterParams.createdAt = filters.createdAt;
       }
 
-      const res = await tenantClient.index.$get({
+      const res = await tenantClientManager.get().index.$get({
         query: {
           page: searchParams.page,
           pageSize: searchParams.limit,
@@ -205,7 +205,7 @@ export const TenantsPage = () => {
   // 处理创建表单提交
   const handleCreateSubmit = async (data: CreateTenantFormData) => {
     try {
-      const res = await tenantClient.index.$post({
+      const res = await tenantClientManager.get().index.$post({
         json: data
       });
       if (res.status !== 201) {

+ 15 - 12
packages/tenant-management-ui/src/hooks/AuthProvider.tsx

@@ -6,10 +6,7 @@ import {
 } from '@tanstack/react-query';
 import axios from 'axios';
 import 'dayjs/locale/zh-cn';
-import type {
-  AuthContextType
-} from '@d8d/shared-ui-components/types';
-import type { InferResponseType } from 'hono/client';
+import { tenantClientManager } from '../api/tenantClient';
 
 // 租户超级管理员用户类型
 type TenantSuperAdmin = {
@@ -20,6 +17,16 @@ type TenantSuperAdmin = {
 
 type User = TenantSuperAdmin;
 
+// 认证上下文类型
+interface AuthContextType<T = User> {
+  user: T | null;
+  token: string | null;
+  login: (username: string, password: string) => Promise<void>;
+  logout: () => Promise<void>;
+  isAuthenticated: boolean;
+  isLoading: boolean;
+}
+
 // 创建认证上下文
 const AuthContext = createContext<AuthContextType<User> | null>(null);
 
@@ -86,16 +93,12 @@ export const TenantAuthProvider: React.FC<{ children: React.ReactNode }> = ({ ch
 
   const handleLogin = async (username: string, password: string): Promise<void> => {
     try {
-      // 使用租户认证API登录
-      const response = await fetch('/api/v1/tenant-auth/login', {
-        method: 'POST',
-        headers: {
-          'Content-Type': 'application/json',
-        },
-        body: JSON.stringify({
+      // 使用租户认证RPC客户端登录
+      const response = await tenantClientManager.get().login.$post({
+        json: {
           username,
           password
-        })
+        }
       });
 
       if (!response.ok) {

+ 3 - 3
packages/tenant-management-ui/src/hooks/useTenantConfig.ts

@@ -1,5 +1,5 @@
 import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
-import { tenantClient } from '../api/tenantClient';
+import { tenantClientManager } from '../api/tenantClient';
 import { toast } from 'sonner';
 
 export function useTenantConfig(tenantId: number) {
@@ -8,7 +8,7 @@ export function useTenantConfig(tenantId: number) {
   const query = useQuery({
     queryKey: ['tenant-config', tenantId],
     queryFn: async () => {
-      const res = await tenantClient[':id'].$get({
+      const res = await tenantClientManager.get()[':id'].$get({
         param: { id: tenantId }
       });
 
@@ -24,7 +24,7 @@ export function useTenantConfig(tenantId: number) {
 
   const updateMutation = useMutation({
     mutationFn: async (config: Record<string, unknown>) => {
-      const res = await tenantClient[':id']['$put']({
+      const res = await tenantClientManager.get()[':id']['$put']({
         param: { id: tenantId },
         json: { config }
       });

+ 5 - 5
packages/tenant-management-ui/src/hooks/useTenants.ts

@@ -1,5 +1,5 @@
 import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
-import { tenantClient } from '../api/tenantClient';
+import { tenantClientManager, tenantClient } from '../api/tenantClient';
 import { toast } from 'sonner';
 
 export interface UseTenantsOptions {
@@ -22,7 +22,7 @@ export function useTenants(options: UseTenantsOptions = {}) {
   const query = useQuery({
     queryKey: ['tenants', page, pageSize, keyword, filters],
     queryFn: async () => {
-      const res = await tenantClient.index.$get({
+      const res = await tenantClientManager.get().index.$get({
         query: {
           page,
           pageSize,
@@ -41,7 +41,7 @@ export function useTenants(options: UseTenantsOptions = {}) {
 
   const createMutation = useMutation({
     mutationFn: async (data: Parameters<typeof tenantClient.index.$post>[0]['json']) => {
-      const res = await tenantClient.index.$post({ json: data });
+      const res = await tenantClientManager.get().index.$post({ json: data });
       if (res.status !== 201) {
         throw new Error('创建租户失败');
       }
@@ -58,7 +58,7 @@ export function useTenants(options: UseTenantsOptions = {}) {
 
   const updateMutation = useMutation({
     mutationFn: async ({ id, data }: { id: number; data: Parameters<typeof tenantClient[':id']['$put']>[0]['json'] }) => {
-      const res = await tenantClient[':id']['$put']({
+      const res = await tenantClientManager.get()[':id']['$put']({
         param: { id },
         json: data
       });
@@ -78,7 +78,7 @@ export function useTenants(options: UseTenantsOptions = {}) {
 
   const deleteMutation = useMutation({
     mutationFn: async (id: number) => {
-      const res = await tenantClient[':id']['$delete']({
+      const res = await tenantClientManager.get()[':id']['$delete']({
         param: { id }
       });
       if (res.status !== 204) {

+ 1 - 1
packages/tenant-management-ui/src/pages/LoginPage.tsx

@@ -1,5 +1,5 @@
 import { useState } from 'react';
-import { useNavigate } from 'react-router';
+import { useNavigate } from 'react-router-dom';
 import { useAuth } from '../hooks/AuthProvider';
 import { useForm } from 'react-hook-form';
 import { zodResolver } from '@hookform/resolvers/zod';

+ 3 - 0
pnpm-lock.yaml

@@ -4011,6 +4011,9 @@ importers:
       '@tanstack/react-query':
         specifier: ^5.90.9
         version: 5.90.9(react@19.2.0)
+      axios:
+        specifier: ^1.11.0
+        version: 1.12.2(debug@4.4.3)
       class-variance-authority:
         specifier: ^0.7.1
         version: 0.7.1

+ 8 - 1
web/src/client/api_init.ts

@@ -12,6 +12,7 @@ import { goodsCategoryClientManager } from '@d8d/goods-category-management-ui-mt
 import { deliveryAddressClientManager } from '@d8d/delivery-address-management-ui-mt/api';
 import { advertisementClientManager } from '@d8d/advertisement-management-ui-mt/api';
 
+
 // 初始化所有多租户API客户端
 userClientManager.init('/api/v1/users');
 authClientManager.init('/api/v1/auth');
@@ -24,4 +25,10 @@ advertisementTypeClientManager.init('/api/v1/advertisement-types');
 goodsClientManager.init('/api/v1/goods');
 goodsCategoryClientManager.init('/api/v1/goods-categories');
 deliveryAddressClientManager.init('/api/v1/delivery-addresses');
-advertisementClientManager.init('/api/v1/advertisements');
+advertisementClientManager.init('/api/v1/advertisements');
+
+
+// 租户管理UI包API客户端初始化
+import { tenantClientManager } from '@d8d/tenant-management-ui';
+// 初始化租户管理API客户端
+tenantClientManager.init('/api/v1/tenants');

+ 0 - 5
web/src/client/tenant/api_init.ts

@@ -1,5 +0,0 @@
-// 租户管理UI包API客户端初始化
-import { tenantClientManager } from '@d8d/tenant-management-ui';
-
-// 初始化租户管理API客户端
-tenantClientManager.init('/api/v1/tenants');