Skip to content

Instantly share code, notes, and snippets.

@thecolorblue
Created October 27, 2017 17:02
Show Gist options
  • Select an option

  • Save thecolorblue/0853fe8ede3b4b10eea3954c86276a8b to your computer and use it in GitHub Desktop.

Select an option

Save thecolorblue/0853fe8ede3b4b10eea3954c86276a8b to your computer and use it in GitHub Desktop.
First attempt at creating re-usable redux resources.
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 this.model(data)];
}))
}
post() {}
update() {}
delete() {}
}
const MapEventToResource = (Resource) => {
return store => next => action => {
switch (action.type) {
case `GET_${Resource.name}`:
if (Resource.get) Resource.get(action)
break;
case `POST_${Resource.name}`:
if (Resource.post) Resource.post(action)
break;
case `UPDATE_${Resource.name}`:
if (Resource.update) Resource.update(action)
break;
case `DELETE_${Resource.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