Skip to content

Instantly share code, notes, and snippets.

@JuoCode
Last active April 1, 2016 02:40
Show Gist options
  • Save JuoCode/89559f56a162f611a9a31206f94086ca to your computer and use it in GitHub Desktop.
Save JuoCode/89559f56a162f611a9a31206f94086ca to your computer and use it in GitHub Desktop.
Redux actionCreator creator
export const createAction = options => {
const { type, success, error, request } = options;
return (...params) => {
const isFn = (obj) => typeof obj === 'function';
const isStr = (obj) => typeof obj === 'string';
return dispatch => {
const startSender = () => dispatch({ type: `${type}_START` });
const successSender = () => dispatch({ type: `${type}_SUCCESS` });
const errorSender = () => dispatch({ type: `${type}_ERROR` });
const successHandler = success ? (isFn(success) ? success : (isStr(success) ? successSender : undefined)) : undefined;
const errorHandler = error ? (isFn(error) ? error : (isStr(error) ? errorSender : undefined)) : undefined;
startSender();
return request(...params)().then(successHandler, errorHandler);
};
};
};
import { createAction } from 'redux/RestModule';
import RestClient, { AccessTokenInterceptor } from './Restful';
// Create Post modal
const Post = RestClient.all('posts');
Post.addRequestInterceptor(AccessTokenInterceptor);
export const fetchPosts = createAction({
type: 'POSTS_FETCH',
request: () => Post.getAll,
success: 'PostS_FETCHED',
error: 'POSTS_FETCH_FAILED'
});
export const actions = {
fetchPosts
};
import cookie from 'react-cookie';
import restful, { fetchBackend } from 'restful.js';
// Create rest client
const Client = restful('http://api.example.com', fetchBackend(fetch));
// Load AccessToken from cookie and inject to rest client by interceptor
const AccessToken = cookie.load('KEY_OF_ACCESS_TOKEN_IN_COOKIE');
export const AccessTokenInterceptor = (config) => {
return Object.assign({}, config, { headers: Object.assign(config.headers, { AccessToken }) });
};
export default Client;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment