Bin
2025-12-16 9e0b2ba2c317b1a86212f24cbae3195ad1f3dbfa
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
import { useCallback } from "react";
import { useMutation } from "@tanstack/react-query";
import { useAPI } from "@humansignal/core";
import { isDefined } from "@humansignal/core";
import { getProviderConfig } from "../providers";
 
interface UseStorageApiProps {
  target?: "import" | "export";
  storage?: any;
  project?: number;
  onSubmit: () => void;
  onClose: () => void;
  onValidationError?: (errors: Record<string, string>) => void;
}
 
const normalizeValidationErrors = (errors: Record<string, string | string[]>) => {
  const normalized: Record<string, string> = {};
 
  Object.entries(errors).forEach(([field, messages]) => {
    if (Array.isArray(messages)) {
      normalized[field] = messages.filter(Boolean).join(" ");
    } else if (typeof messages === "string") {
      normalized[field] = messages;
    }
  });
 
  return normalized;
};
 
export const useStorageApi = ({
  target,
  storage,
  project,
  onSubmit,
  onClose,
  onValidationError,
}: UseStorageApiProps) => {
  const api = useAPI();
  const isEditMode = Boolean(storage);
  const action = storage ? "updateStorage" : "createStorage";
 
  const handleValidationErrors = useCallback(
    (result: any) => {
      const validationErrors = result?.response?.validation_errors;
      if (validationErrors && onValidationError) {
        onValidationError(normalizeValidationErrors(validationErrors));
      }
    },
    [onValidationError],
  );
 
  const errorFilter = useCallback((result: any) => {
    return result?.$meta?.status === 400;
  }, []);
 
  // Clean form data for submission
  const cleanFormDataForSubmission = useCallback(
    (data: any) => {
      if (!isEditMode) return data;
 
      const cleanedData = { ...data };
 
      // Get the current provider config to identify access key fields
      const providerConfig = getProviderConfig(data.provider);
 
      // Get all field names from the current provider schema
      const validFieldNames = new Set([
        "project", // Always include project
        "provider", // Always include provider
        "title", // Always include title
        "prefix", // Common field for bucket prefix
        "path", // Common field for file path (used by redis)
        "use_blob_urls", // Common field for import method
        "regex_filter", // Common field for file filtering
        "recursive_scan", // Common field for recursive scanning
        "can_delete_objects", // Common field for export
        ...(providerConfig?.fields.map((field) => field.name) || []),
      ]);
 
      // Remove fields that aren't in the current provider's schema
      Object.keys(cleanedData).forEach((key) => {
        if (!validFieldNames.has(key)) {
          delete cleanedData[key];
        }
      });
 
      // Remove empty values only for access key fields in edit mode
      Object.keys(cleanedData).forEach((key) => {
        const field = providerConfig?.fields.find((f) => f.name === key);
        const isAccessKey = field && "type" in field && (field as any).accessKey;
 
        // Only remove empty values for access key fields
        if (
          isAccessKey &&
          (cleanedData[key] === "" || cleanedData[key] === undefined || cleanedData[key] === "••••••••••••••••")
        ) {
          delete cleanedData[key];
        }
      });
 
      return cleanedData;
    },
    [isEditMode],
  );
 
  // Test connection mutation
  const testConnectionMutation = useMutation({
    mutationFn: async (connectionData: any) => {
      if (!api) throw new Error("API context not available");
 
      const cleanedData = cleanFormDataForSubmission(connectionData);
      const body = { ...cleanedData };
 
      if (isDefined(storage?.id)) {
        body.id = storage.id;
      }
 
      const result = await api.callApi("validateStorage", {
        params: {
          target,
          type: connectionData.provider,
        },
        body,
        errorFilter,
      });
      if (result?.error) {
        handleValidationErrors(result);
      }
      return result;
    },
  });
 
  // Sync storage mutation
  const syncStorageMutation = useMutation({
    mutationFn: async (storageData: any) => {
      if (!api) throw new Error("API context not available");
 
      return api.callApi("syncStorage", {
        params: {
          target,
          type: storageData.provider,
          pk: storageData.id,
        },
      });
    },
  });
 
  // Create/Update storage mutation (with sync)
  const createStorageMutation = useMutation({
    mutationFn: async (storageData: any) => {
      if (!api) throw new Error("API context not available");
 
      const cleanedData = cleanFormDataForSubmission(storageData);
      const body = { ...cleanedData };
 
      if (isDefined(storage?.id)) {
        body.id = storage.id;
      }
 
      // First, save the storage
      const result = await api.callApi(action, {
        params: {
          target,
          type: storageData.provider,
          project,
          pk: storage?.id,
        },
        body,
        errorFilter,
      });
      if (result?.error) {
        handleValidationErrors(result);
      }
 
      // Only if storage save was successful, then trigger sync for import storages
      if (result?.$meta?.ok && target !== "export" && result?.id) {
        try {
          await api.callApi("syncStorage", {
            params: {
              target,
              type: storageData.provider,
              pk: result.id,
            },
          });
        } catch (error) {
          console.error("Failed to auto-sync storage:", error);
          // Don't fail the entire operation if sync fails
        }
      }
 
      return result;
    },
    onSuccess: (response) => {
      if (response?.$meta?.ok) {
        onSubmit();
        onClose();
      }
    },
  });
 
  // Save storage mutation (without sync)
  const saveStorageMutation = useMutation({
    mutationFn: async (storageData: any) => {
      if (!api) throw new Error("API context not available");
 
      const cleanedData = cleanFormDataForSubmission(storageData);
      const body = { ...cleanedData };
 
      if (isDefined(storage?.id)) {
        body.id = storage.id;
      }
 
      // Only save the storage, don't sync
      const result = await api.callApi(action, {
        params: {
          target,
          type: storageData.provider,
          project,
          pk: storage?.id,
        },
        body,
        errorFilter,
      });
      if (result?.error) {
        handleValidationErrors(result);
      }
 
      return result;
    },
    onSuccess: (response) => {
      if (response?.$meta?.ok) {
        onSubmit();
        onClose();
      }
    },
  });
 
  // Load files preview mutation
  const loadFilesPreviewMutation = useMutation({
    mutationFn: async (previewData: any) => {
      if (!api) throw new Error("API context not available");
 
      const cleanedData = cleanFormDataForSubmission(previewData);
      const body = { ...cleanedData };
 
      if (isDefined(storage?.id)) {
        body.id = storage.id;
        body.limit = 30;
      }
 
      const result = await api.callApi<{ files: any[] }>("storageFiles", {
        params: {
          target,
          type: previewData.provider,
        },
        body,
        errorFilter,
      });
      if ((result as any)?.error) {
        handleValidationErrors(result);
      }
      return result;
    },
  });
 
  return {
    testConnectionMutation,
    createStorageMutation,
    saveStorageMutation,
    loadFilesPreviewMutation,
    syncStorageMutation,
    isEditMode,
    action,
  };
};