Skip to content

Instantly share code, notes, and snippets.

@jlogsdon
Last active September 15, 2015 13:52
Show Gist options
  • Save jlogsdon/dd82bddacae908e17879 to your computer and use it in GitHub Desktop.
Save jlogsdon/dd82bddacae908e17879 to your computer and use it in GitHub Desktop.
import { Todo as TodoTypes } from '../ActionTypes';
export function getAll() {
return api => ({
type: TodoTypes.getAll,
payload: api('/api/todos')
});
}
// Generated from a helper in my actual codebase
export default {
Todos: {
getAll: {
begin: 'Todos_getAll_begin',
end: 'Todos_getAll_end'
}
}
}
import { createStore, combineReducers, applyMiddleware } from 'redux';
import * as reducers from '../reducers';
function isFunction(obj) {
return typeof obj === 'function';
}
function isPromise(obj) {
return obj && obj.payload && isFunction(obj.payload.then);
}
function promiseMiddleware(api, { dispatch, getState }) {
return next => function _r(action) {
if (isFunction(action)) {
return _r(action(api, getState));
}
if (isPromise(action)) {
const { payload, type, ...rest } = action;
next({ ...rest, type: type.begin });
return payload.then(
result => next({ ...rest, type: type.end, payload: result }),
error => next({ ...rest, type: type.end, payload: error, error: true })
);
}
return next(action);
};
}
export default function (api, initialState) {
const createStoreWithMiddleware = applyMiddleware(promiseMiddleware.bind(null, api))(createStore);
const reducer = combineReducers(reducers);
return createStoreWithMiddleware(reducer, initialState);
}
import createStore from './createStore';
import request from 'superagent';
import qs from 'qs';
import createStore from './lib/createStore';
import createAPI from './lib/createAPI';
const api = createAPI(({ method, pathname, query = {}, body = {} }) => {
const url = `http://api.host${pathname}.json`;
return request(method, url)
.query(qs.stringify(query))
.send(body);
});
const store = createStore(api);
export default function todos(state, action) {
switch (action.type) {
'Todos_getAll_begin':
return state.merge({loading: true});
'Todos_getAll_end':
return state.merge({loading: false, todos: action.payload});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment