Skip to content

Instantly share code, notes, and snippets.

@dannyc5
Last active April 28, 2016 20:13
Show Gist options
  • Save dannyc5/6fc1be724643aac47599fb00f3c6b5cc to your computer and use it in GitHub Desktop.
Save dannyc5/6fc1be724643aac47599fb00f3c6b5cc to your computer and use it in GitHub Desktop.
Allow app to fetch resources with syntactic sugar ~~ client.resource('user.company').get
// client.js
import resourceRoutes from 'resource-routes'
export default {
resource(resourceName, params) {
let formattedResourceName = this._parseName(resourceName)
let resourceURIs = resourceRoutes.urlFor(formattedResourceName, params)
return this._withResourceURIs(resourceURIs);
},
_parseName(resourceName) {
return resourceName.split('.');
},
_withResourceURIs(uris) {
this.currentResourceURIs = uris;
return this;
},
get(uri, params) {
if (!!uri && this.currentResourceURIs) {
let currentUri = currentResourceURIs.get;
this.currentResourceURIs = null
this.get(currentUri, params)
} else {
// fetch uri w params
}
}
}
// resource-routes.js
export default {
urlFor(resourceNames, params) {
resourceNames.unshift(this.routes)
let uri = resourceNames.reduce( function(previousValue, currentValue) {
return previousValue[currentValue]
})
for (var param in params) {
uri = uri.split(':' + param).join(params[param])
}
return uri;
}
routes: {
user: {
company: {
get: '/users/:id/company'
}
}
}
}
client.resource('user.company', {id: 1}).get
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment