File size: 2,278 Bytes
ec4551b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useThirdParty } from '@gitroom/frontend/components/third-parties/third-party.media';
import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
import { useCallback, useEffect, useRef, useState } from 'react';
import useSWR from 'swr';

export const useThirdPartySubmit = () => {
  const thirdParty = useThirdParty();
  const fetch = useFetch();

  return useCallback(async (data?: any) => {
    if (!thirdParty.id) {
      return;
    }

    const response = await fetch(`/third-party/${thirdParty.id}/submit`, {
      body: JSON.stringify(data),
      method: 'POST',
    });

    return response.json();
  }, []);
};

export const useThirdPartyFunction = (type: 'EVERYTIME' | 'ONCE') => {
  const thirdParty = useThirdParty();
  const data = useRef<any>(undefined);
  const fetch = useFetch();

  return useCallback(
    async (functionName: string, sendData?: any) => {
      if (data.current && type === 'ONCE') {
        return data.current;
      }

      data.current = await (
        await fetch(`/third-party/function/${thirdParty.id}/${functionName}`, {
          ...(data ? { body: JSON.stringify(sendData) } : {}),
          method: 'POST',
        })
      ).json();

      return data.current;
    },
    [thirdParty, data]
  );
};

export const useThirdPartyFunctionSWR = (
  type: 'SWR' | 'LOAD_ONCE',
  functionName: string,
  data?: any
) => {
  const thirdParty = useThirdParty();
  const fetch = useFetch();

  const callBack = useCallback(
    async (functionName: string, data?: any) => {
      return (
        await fetch(`/third-party/function/${thirdParty.id}/${functionName}`, {
          ...(data ? { body: JSON.stringify(data) } : {}),
          method: 'POST',
        })
      ).json();
    },
    [thirdParty]
  );

  return useSWR<any>(
    `function-${thirdParty.id}-${functionName}`,
    () => {
      // @ts-ignore
      return callBack(functionName, { ...data });
    },
    {
      ...(type === 'LOAD_ONCE'
        ? {
            revalidateOnMount: true,
            revalidateOnFocus: false,
            revalidateOnReconnect: false,
            refreshInterval: 0,
            refreshWhenHidden: false,
            refreshWhenOffline: false,
            revalidateIfStale: false,
          }
        : {}),
    }
  );
};