portal-dashboard/app/hooks/usePinning.ts

76 lines
2.2 KiB
TypeScript
Raw Normal View History

import { useInvalidate, useNotification } from "@refinedev/core";
2024-03-22 17:53:39 +00:00
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useCallback, useContext } from "react";
import { PinningProcess } from "~/data/pinning";
import { PinningContext } from "~/providers/PinningProvider";
export const usePinning = () => {
2024-03-22 17:53:39 +00:00
const queryClient = useQueryClient();
const invalidate = useInvalidate();
const context = useContext(PinningContext);
2024-03-22 17:53:39 +00:00
const { open } = useNotification();
const { status: pinStatus, data: pinData, mutate: pinMutation } = useMutation({
2024-03-22 17:53:39 +00:00
mutationKey: ["pin-mutation"],
mutationFn: async (variables: { cid: string }) => {
const { cid } = variables;
const response = await PinningProcess.pin(cid);
2024-03-22 17:53:39 +00:00
if (!response.success) {
open?.({
type: "error",
message: `Error pinning ${cid}`,
description: response.message,
});
2024-03-26 14:54:51 +00:00
return Promise.reject(response);
}
2024-03-26 14:54:51 +00:00
queryClient.invalidateQueries({ queryKey: ["pin-progress", "file"] });
invalidate({ resource: "file", invalidates: ["list"] });
2024-03-26 14:54:51 +00:00
return Promise.resolve(response);
2024-03-22 17:53:39 +00:00
},
});
const { status: unpinStatus, data: unpinData, mutate: unpinMutation } = useMutation({
2024-03-22 17:53:39 +00:00
mutationKey: ["unpin-mutation"],
mutationFn: async (variables: { cid: string }) => {
const { cid } = variables;
const response = await PinningProcess.unpin(cid);
if (!response.success) {
open?.({
type: "error",
message: `Error removing ${cid}`,
description: response.message,
});
2024-03-26 14:54:51 +00:00
return Promise.reject(response);
2024-03-22 17:53:39 +00:00
}
queryClient.invalidateQueries({ queryKey: ["pin-progress"] });
invalidate({ resource: "file", invalidates: ["list"] });
2024-03-26 14:54:51 +00:00
return Promise.resolve(response);
2024-03-22 17:53:39 +00:00
},
});
2024-03-22 17:53:39 +00:00
const bulkPin = useCallback(
(cids: string[]) => {
for (const cid of cids) {
pinMutation({ cid });
}
},
[pinMutation],
);
return {
progressStatus: context.query.status,
progressData: context.query.data,
fetchProgress: context.query.refetch,
pinStatus,
pinData,
unpinStatus,
unpinData,
2024-03-22 17:53:39 +00:00
pin: pinMutation,
unpin: unpinMutation,
bulkPin,
};
};