diff options
author | Brandon Millman <brandon.millman@gmail.com> | 2018-04-23 01:27:16 +0800 |
---|---|---|
committer | Brandon Millman <brandon.millman@gmail.com> | 2018-04-23 01:28:13 +0800 |
commit | fb31c493176ec952f6c3621348e328e38ade2174 (patch) | |
tree | 8ad240583fee79f2b620bc5931f5b59356d30419 /packages/website/ts/utils/fetch_utils.ts | |
parent | e51f9b3593c86c5ab4ec0ecb7e7ea8a9857a7c74 (diff) | |
download | dexon-sol-tools-fb31c493176ec952f6c3621348e328e38ade2174.tar dexon-sol-tools-fb31c493176ec952f6c3621348e328e38ade2174.tar.gz dexon-sol-tools-fb31c493176ec952f6c3621348e328e38ade2174.tar.bz2 dexon-sol-tools-fb31c493176ec952f6c3621348e328e38ade2174.tar.lz dexon-sol-tools-fb31c493176ec952f6c3621348e328e38ade2174.tar.xz dexon-sol-tools-fb31c493176ec952f6c3621348e328e38ade2174.tar.zst dexon-sol-tools-fb31c493176ec952f6c3621348e328e38ade2174.zip |
Refactor common fetch logic into fetch_utils
Diffstat (limited to 'packages/website/ts/utils/fetch_utils.ts')
-rw-r--r-- | packages/website/ts/utils/fetch_utils.ts | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/packages/website/ts/utils/fetch_utils.ts b/packages/website/ts/utils/fetch_utils.ts new file mode 100644 index 000000000..d2e902db5 --- /dev/null +++ b/packages/website/ts/utils/fetch_utils.ts @@ -0,0 +1,33 @@ +import { logUtils } from '@0xproject/utils'; +import * as _ from 'lodash'; +import * as queryString from 'query-string'; + +import { errorReporter } from 'ts/utils/error_reporter'; + +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 fetch(url); + if (response.status !== 200) { + const errorText = `Error requesting url: ${url}, ${response.status}: ${response.statusText}`; + logUtils.log(errorText); + const error = Error(errorText); + // tslint:disable-next-line:no-floating-promises + errorReporter.reportAsync(error); + throw error; + } + const result = await response.json(); + return result; + }, +}; + +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}`; +} |