Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(types): update generics in request #2

Merged
merged 2 commits into from
Jan 9, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 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 @@ -145,7 +147,10 @@ const _catchStatusError = (res: Response): Promise<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 = any>(
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't this any be {} since we always expect an object.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No because of this...

url: string,
options?: RequestInit
): Promise<TResponseType> =>
_fetchJSON<TResponseType>(url, options).catch(_catchStatusError);

export default jsonRequest;