aboutsummaryrefslogtreecommitdiffstats
path: root/packages/website/ts/utils/fetch_utils.ts
blob: f159e3180c8bd1f5c6b0653bfd6db89080d4c72c (plain) (blame)
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
import { fetchAsync, logUtils } from '@0xproject/utils';
import * as _ from 'lodash';
import * as queryString from 'query-string';

import { errorReporter } from 'ts/utils/error_reporter';

const logErrorIfPresent = (response: Response, requestedURL: string) => {
    if (response.status !== 200) {
        const errorText = `Error requesting url: ${requestedURL}, ${response.status}: ${response.statusText}`;
        logUtils.log(errorText);
        const error = Error(errorText);
        // tslint:disable-next-line:no-floating-promises
        errorReporter.reportAsync(error);
        throw error;
    }
};

export const fetchUtils = {
    async requestAsync(baseUrl: string, path: string, queryParams?: object): Promise<any> {
        const query = queryStringFromQueryParams(queryParams);
        const url = `${baseUrl}${path}${query}`;
        const response = await fetchAsync(url);
        logErrorIfPresent(response, url);
        const result = await response.json();
        return result;
    },
    async postAsync(baseUrl: string, path: string, body: object): Promise<Response> {
        const url = `${baseUrl}${path}`;
        const response = await fetchAsync(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(body),
        });
        logErrorIfPresent(response, url);
        return response;
    },
};

function queryStringFromQueryParams(queryParams?: object): string {
    // if params are undefined or empty, return an empty string
    if (_.isUndefined(queryParams) || _.isEmpty(queryParams)) {
        return '';
    }
    // stringify the formatted object
    const stringifiedParams = queryString.stringify(queryParams);
    return `?${stringifiedParams}`;
}