Created
August 3, 2015 09:10
-
-
Save ameensol/e505275548a5ce068dfd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Mapware } from 'fluxette' | |
import { API } from '../types'; | |
import { dispatch, proxy } from '..'; | |
import api from '../../utils/api'; | |
import { methods } from '../../utils/api'; | |
var createCreator = (method, API) => ({ | |
request: (data) => ({ type: API[method.toUpperCase()].REQUEST, data }), | |
fail: (data) => ({ type: API[method.toUpperCase()].FAIL, data }), | |
done: (data) => ({ type: API[method.toUpperCase()].DONE, data }) | |
}) | |
// returns an object of action creators, one for action | |
// API is an object containing the type definitions for each method | |
var createCreators = (methods, API) => { | |
return methods.reduce((creators, method) => { | |
creators[method] = createCreator(method, API) | |
return creators | |
}, {}) | |
} | |
var creators = createCreators(methods, API) | |
creators.query = (method, data) => ({ type: API.QUERY, query: { method, data } }) | |
const ware = Mapware({ | |
[API.QUERY]: action => { | |
let { method, data } = action.query | |
// 1 launch async request | |
api[method](data, (err, res, body) => { | |
if (err) { | |
dispatch(creators[method].fail({ ...data, err })); | |
} else { | |
dispatch(creators[method].done({ ...data, body })); | |
} | |
}) | |
// 2 return modified action -- use creator | |
return creators[method].request(data) | |
} | |
}) | |
proxy(ware) | |
export default creators |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment