|
| 1 | +import { useCallback, useContext, useState } from "react"; |
| 2 | +import { useQueryClient } from "react-query"; |
| 3 | +import { |
| 4 | + ProjectListContext, |
| 5 | + ProjectsListSchema, |
| 6 | +} from "../contexts/ProjectListContext"; |
| 7 | + |
| 8 | +interface Toast { |
| 9 | + id: string; |
| 10 | + title: string; |
| 11 | + color: "success" | "danger"; |
| 12 | + iconType: string; |
| 13 | +} |
| 14 | + |
| 15 | +const useRegistryRefresh = () => { |
| 16 | + const [refreshing, setRefreshing] = useState(false); |
| 17 | + const [toasts, setToasts] = useState<Toast[]>([]); |
| 18 | + const queryClient = useQueryClient(); |
| 19 | + const projectListCtx = useContext(ProjectListContext); |
| 20 | + const basename = projectListCtx?.basename || ""; |
| 21 | + |
| 22 | + const removeToast = useCallback((removedToast: { id: string }) => { |
| 23 | + setToasts((prev) => prev.filter((t) => t.id !== removedToast.id)); |
| 24 | + }, []); |
| 25 | + |
| 26 | + const handleRefresh = useCallback(async () => { |
| 27 | + setRefreshing(true); |
| 28 | + try { |
| 29 | + const refreshRes = await fetch(`${basename}/api/v1/registry/refresh`, { |
| 30 | + method: "POST", |
| 31 | + }); |
| 32 | + if (!refreshRes.ok) { |
| 33 | + throw new Error(`Registry refresh failed (${refreshRes.status})`); |
| 34 | + } |
| 35 | + const res = await fetch(`${basename}/projects-list.json`, { |
| 36 | + headers: { "Content-Type": "application/json" }, |
| 37 | + }); |
| 38 | + if (!res.ok) { |
| 39 | + throw new Error(`Failed to fetch project list (${res.status})`); |
| 40 | + } |
| 41 | + const json = await res.json(); |
| 42 | + const parsed = ProjectsListSchema.parse(json); |
| 43 | + queryClient.setQueryData("feast-projects-list", parsed); |
| 44 | + await queryClient.invalidateQueries("registry-rest-bulk"); |
| 45 | + setToasts((prev) => [ |
| 46 | + ...prev, |
| 47 | + { |
| 48 | + id: String(Date.now()), |
| 49 | + title: "Refresh successful", |
| 50 | + color: "success" as const, |
| 51 | + iconType: "check", |
| 52 | + }, |
| 53 | + ]); |
| 54 | + } catch { |
| 55 | + setToasts((prev) => [ |
| 56 | + ...prev, |
| 57 | + { |
| 58 | + id: String(Date.now()), |
| 59 | + title: "Refresh failed", |
| 60 | + color: "danger" as const, |
| 61 | + iconType: "alert", |
| 62 | + }, |
| 63 | + ]); |
| 64 | + } finally { |
| 65 | + setRefreshing(false); |
| 66 | + } |
| 67 | + }, [basename, queryClient]); |
| 68 | + |
| 69 | + return { refreshing, toasts, handleRefresh, removeToast }; |
| 70 | +}; |
| 71 | + |
| 72 | +export default useRegistryRefresh; |
0 commit comments