File size: 1,036 Bytes
cd6f98e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import type { Session } from "next-auth";

import OauthApi from "../services/workflow/oauthApi";

const QUERY_KEY = ["sid"];

export function useSID(session: Session | null) {
  const api = OauthApi.fromSession(session);
  const queryClient = useQueryClient();

  const { data, refetch } = useQuery(QUERY_KEY, async () => await api.get_info_sid(), {
    enabled: !!session,
    retry: false,
  });

  const { mutateAsync: install } = useMutation(async () => {
    if (!session) return;

    window.location.href = await api.install("sid");
  });

  const { mutateAsync: uninstall } = useMutation(async () => {
    if (!session) return;

    await api.uninstall("sid");
    queryClient.setQueriesData(QUERY_KEY, { connected: false });
  });

  return {
    connected: data?.connected ?? false,
    refetch,
    install: async () => install(),
    uninstall: async () => uninstall(),
    manage: () => void window.open("https://me.sid.ai/", "_blank"),
  };
}