Last active
October 27, 2017 17:06
-
-
Save thecolorblue/81be3a99ea05847b28fdead24ce44db5 to your computer and use it in GitHub Desktop.
First attempt at creating re-usable redux resources.
This file contains hidden or 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
| class CatalogItem { | |
| name = 'CATALOGITEM' | |
| constructor(item) { | |
| Object.assign(this, { | |
| ...item, | |
| ...item.Attributes.map(a => a.ExpandedAttributeName.split(' : ')).reduce((o, a) => { o[a[0]] = a[1]; return o; }, {}), | |
| Currency: 'USD' | |
| }) | |
| } | |
| } | |
| class CatalogItems { | |
| name = 'CATALOGITEMS' | |
| collection = [] | |
| constructor(items) { | |
| this.collection = items.map(i => { return new CatalogItem(i); }) | |
| } | |
| } | |
| class CatalogItemResource { | |
| constructor(Model, options) { | |
| this.model = Model; | |
| Object.assign(this, options); | |
| } | |
| request(query) { | |
| return axios.get(`${this.resource}?${qs.stringify(query)}`) | |
| .then(({ data }) => data) | |
| } | |
| handleResponse(request, name) { | |
| return request | |
| .then((items) => store.dispatch({ type: `${name}_SUCCESS`, items })) | |
| .catch(error => store.dispatch({ type: `${name}_ERROR`, error })) | |
| } | |
| get(action) { | |
| return this.handleResponse( | |
| this.request({ | |
| cmd: 'getsingleitemdetail', | |
| id: action.id | |
| }, 'SEARCH_ITEMS') | |
| .then((data) => { | |
| return (new CatalogItems([data])).collection; | |
| })) | |
| } | |
| post() {} | |
| update() {} | |
| delete() {} | |
| } | |
| const MapEventToResource = (Resource) => { | |
| return store => next => action => { | |
| switch (action.type) { | |
| case `GET_${Resource.model.name}`: | |
| if (Resource.get) Resource.get(action) | |
| break; | |
| case `POST_${Resource.model.name}`: | |
| if (Resource.post) Resource.post(action) | |
| break; | |
| case `UPDATE_${Resource.model.name}`: | |
| if (Resource.update) Resource.update(action) | |
| break; | |
| case `DELETE_${Resource.model.name}`: | |
| if (Resource.delete) Resource.delete(action) | |
| break; | |
| } | |
| return next(action); | |
| } | |
| } | |
| export default MapEventToResource(CatalogItemResource(CatalogItem, { | |
| resource: '/Custom/Services/Commerce/Items.ashx' | |
| })) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment