useTenantConfig.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
  2. import { tenantClientManager } from '../api/tenantClient';
  3. import { toast } from 'sonner';
  4. export function useTenantConfig(tenantId: number) {
  5. const queryClient = useQueryClient();
  6. const query = useQuery({
  7. queryKey: ['tenant-config', tenantId],
  8. queryFn: async () => {
  9. const res = await tenantClientManager.get()[':id'].$get({
  10. param: { id: tenantId }
  11. });
  12. if (res.status !== 200) {
  13. throw new Error('获取租户配置失败');
  14. }
  15. const tenant = await res.json();
  16. return tenant.config || {};
  17. },
  18. enabled: !!tenantId
  19. });
  20. const updateMutation = useMutation({
  21. mutationFn: async (config: Record<string, unknown>) => {
  22. const res = await tenantClientManager.get()[':id']['$put']({
  23. param: { id: tenantId },
  24. json: { config }
  25. });
  26. if (res.status !== 200) {
  27. throw new Error('更新租户配置失败');
  28. }
  29. return await res.json();
  30. },
  31. onSuccess: () => {
  32. toast.success('租户配置更新成功');
  33. queryClient.invalidateQueries({ queryKey: ['tenant-config', tenantId] });
  34. queryClient.invalidateQueries({ queryKey: ['tenants'] });
  35. },
  36. onError: () => {
  37. toast.error('更新配置失败,请重试');
  38. }
  39. });
  40. return {
  41. ...query,
  42. updateConfig: updateMutation.mutateAsync,
  43. isUpdating: updateMutation.isPending
  44. };
  45. }