export function useTokens()

in src/components/Storage/api/useTokens.tsx [22:80]


export function useTokens(fullPath: string) {
  const config = useEmulatorConfig('storage');
  const [bucket] = useBucket();
  const key = `storage/tokens/${bucket}/${fullPath}`;

  const fetcher = async () => {
    const url = `http://${
      config.hostAndPort
    }/v0/b/${bucket}/o/${encodeURIComponent(fullPath)}`;

    const response = await fetch(url, {
      method: 'GET',
      headers: { Authorization: 'Bearer owner' },
    });

    const result = await response.json();

    return (result.downloadTokens || '').split(',').filter((t: string) => !!t);
  };

  const { data, mutate } = useSWR<string[]>(key, fetcher, {
    suspense: true,
  });

  async function createToken() {
    await fetch(
      `http://${config!.hostAndPort}/v0/b/${bucket}/o/${encodeURIComponent(
        fullPath
      )}?create_token=true`,

      {
        headers: { Authorization: 'Bearer owner' },
        method: 'POST',
      }
    );

    mutate();
  }

  async function deleteToken(token: string) {
    await fetch(
      `http://${config!.hostAndPort}/v0/b/${bucket}/o/${encodeURIComponent(
        fullPath
      )}?delete_token=${token}`,
      {
        headers: { Authorization: 'Bearer owner' },
        method: 'POST',
      }
    );

    mutate();
  }

  return {
    tokens: data || [],
    createToken,
    deleteToken,
  };
}