Skip to content

Commit

Permalink
Merge pull request #2 from jcreamer898/jc-add-users
Browse files Browse the repository at this point in the history
fix(types): update generics in request
  • Loading branch information
kwelch authored Jan 9, 2019
2 parents 9b6dabb + 54dd2b3 commit 2cb171e
Showing 1 changed file with 15 additions and 6 deletions.
21 changes: 15 additions & 6 deletions src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ const _checkStatus = (res: Response): Promise<Response> => {
return Promise.resolve(res);
};

const _tryParseJSON = (res: Response): Promise<any> => {
const _tryParseJSON = <TResponseType>(
res: Response
): Promise<TResponseType> => {
try {
return (
res
Expand All @@ -35,10 +37,10 @@ const _tryParseJSON = (res: Response): Promise<any> => {
* with our JSON API. Parses the JSON, provides appropriate headers, and asserts
* a valid status from the server.
*/
const _fetchJSON = <T>(
const _fetchJSON = <TResponseType>(
url: string,
{headers = {}, method = 'GET', mode, ...options}: RequestInit = {}
): Promise<T> => {
): Promise<TResponseType> => {
let fetchHeaders = headers as HeadersInit;

if (method !== 'GET') {
Expand All @@ -58,7 +60,7 @@ const _fetchJSON = <T>(

return fetch(url, fetchOptions)
.then(_checkStatus)
.then(_tryParseJSON);
.then<TResponseType>(_tryParseJSON);
};

const _hasArgumentsError = (responseData: JSONResponseData): boolean =>
Expand Down Expand Up @@ -141,11 +143,18 @@ const _catchStatusError = (res: Response): Promise<any> =>
);
});

export interface DefaultApiResponse {
[key: string]: any;
}

/**
* Low-level method that makes fetch requests, returning the response formatted as JSON.
* It parses errors from API v3 and throws exceptions with those errors
*/
const jsonRequest = <T>(url: string, options?: RequestInit) =>
_fetchJSON<T>(url, options).catch(_catchStatusError);
const jsonRequest = <TResponseType = DefaultApiResponse>(
url: string,
options?: RequestInit
): Promise<TResponseType> =>
_fetchJSON<TResponseType>(url, options).catch(_catchStatusError);

export default jsonRequest;

0 comments on commit 2cb171e

Please sign in to comment.