Skip to content

Instantly share code, notes, and snippets.

@moltar
Created April 8, 2020 16:11
Show Gist options
  • Save moltar/529638563c969e0de0329b3c45bb34aa to your computer and use it in GitHub Desktop.
Save moltar/529638563c969e0de0329b3c45bb34aa to your computer and use it in GitHub Desktop.
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