Created
April 8, 2020 16:11
-
-
Save moltar/529638563c969e0de0329b3c45bb34aa to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private async $request<R extends Runtype<any>>(config: AxiosRequestConfig, type?: R): Promise<Static<R>> { | |
// serialize to JSON | |
if (config.data && isObject(config.data)) { | |
config.data = JSON.stringify(config.data) | |
} | |
const { data, status, statusText } = await this.axios.request<any, AxiosResponse<Static<R>>>(config) | |
if (status === 204) { | |
return | |
} | |
if (status >= 400) { | |
// Well-known, internally defined, API errors | |
if (Errors.guard(data)) { | |
// throws only the first error, but theoretically there can be more errors | |
throw new ApiError(data.errors[0]) | |
} else { | |
throw new ApiUnknownError(status, statusText) | |
} | |
} | |
if (type) { | |
const res = type.validate(data) | |
if (!res.success) { | |
throw new ApiValidationError(res, config) | |
} | |
} | |
return data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment