Skip to content

Instantly share code, notes, and snippets.

@deptno
Created March 11, 2017 15:21
Show Gist options
  • Save deptno/fefe644ad75705c22af1cdc4ed459308 to your computer and use it in GitHub Desktop.
Save deptno/fefe644ad75705c22af1cdc4ed459308 to your computer and use it in GitHub Desktop.
redux-thunk fetch wrapper
import {parse} from 'url';
import * as qs from 'qs';
const handleError = async response => {
const message = await response.json();
return new Error(JSON.stringify({code: response.status, message}));
};
const prefixer = (action: string) => [`PENDING_${action}`, `OK_${action}`, `ERR_${action}`];
export const GET = (action: string, url: string, query?: Object, hookOk = x => x, hookErr = x => x) => {
const [pending, ok, err] = prefixer(action);
return async dispatch => {
const {pathname} = parse(url);
const path = pathname.split('/');
dispatch({type: pending, path, query, payload: action});
try {
const target = query ? `${url}?${qs.stringify(query)}` : url;
const response = await fetch(target, {method: 'GET'});
if (response.status >= 400) {
throw await handleError(response);
}
const payload = hookOk(await response.json());
dispatch({type: ok, query, path, payload});
} catch(error) {
dispatch({type: err, query, path, payload: hookErr(error)});
}
}
};
export const POST = (action: string, url: string, body?, hookOk = x => x, hookErr = x => x) => {
const [pending, ok, err] = prefixer(action);
return async dispatch => {
const {pathname} = parse(url);
const path = pathname.split('/');
if (body) {
body = JSON.stringify(body);
}
dispatch({type: pending, path, body, payload: action});
try {
const response = await fetch(url, {method: 'POST', body: JSON.stringify(body)});
if (response.status >= 400) {
throw await handleError(response);
}
const payload = hookOk(await response.json());
dispatch({type: ok, path, body, payload});
} catch(error) {
dispatch({type: err, path, body, payload: hookErr(error)});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment