fetch.ts 2.2 KB
Newer Older
1 2 3
// TODO: use this instead
// https://github.com/zeit/swr/blob/master/examples/axios-typescript/libs/useRequest.ts

4 5
import fetch from 'isomorphic-unfetch';

6 7
const API_TOKEN_KEY: string = globalThis.__vdl_api_token_key__ || '';

8 9 10
const API_TOKEN_HEADER = 'X-VisualDL-Instance-ID';

function addApiToken(options?: RequestInit): RequestInit | undefined {
11 12
    const id = getApiToken();
    if (!API_TOKEN_KEY || !id) {
13 14 15
        return options;
    }
    const {headers, ...rest} = options || {};
16 17 18 19 20 21
    const newHeaders = new Headers(headers);
    if (Array.isArray(id)) {
        id.forEach(value => newHeaders.append(API_TOKEN_HEADER, value));
    } else {
        newHeaders.append(API_TOKEN_HEADER, id);
    }
22 23
    return {
        ...rest,
24
        headers: newHeaders
25 26 27 28
    };
}

export function setApiToken(id?: string | string[] | null) {
29
    globalThis.__visualdl_instance_id__ = id || '';
30 31
}

32
export function getApiToken(): string | string[] | null {
33 34 35 36 37
    return globalThis.__visualdl_instance_id__ || '';
}

export const fetcher = async <T = unknown>(url: string, options?: RequestInit): Promise<T> => {
    const res = await fetch(process.env.API_URL + url, addApiToken(options));
38 39 40 41 42
    const response = await res.json();

    return response && 'data' in response ? response.data : response;
};

43 44 45
export type BlobResponse = {
    data: Blob;
    type: string | null;
46
    filename: string | null;
47 48
};

49 50
export const blobFetcher = async (url: string, options?: RequestInit): Promise<BlobResponse> => {
    const res = await fetch(process.env.API_URL + url, addApiToken(options));
51
    const data = await res.blob();
52 53 54 55 56 57 58 59 60
    const disposition = res.headers.get('Content-Disposition');
    let filename: string | null = null;
    if (disposition && disposition.indexOf('attachment') !== -1) {
        const matches = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/.exec(disposition);
        if (matches != null && matches[1]) {
            filename = matches[1].replace(/['"]/g, '');
        }
    }
    return {data, type: res.headers.get('Content-Type'), filename};
P
Peter Pan 已提交
61 62
};

63
export const cycleFetcher = async <T = unknown>(urls: string[], options?: RequestInit): Promise<T[]> => {
P
Peter Pan 已提交
64
    return await Promise.all(urls.map(url => fetcher<T>(url, options)));
65
};