In the process of building a Backbone.js SPA that talks to a RESTful (hopefully) API. I've tried to design the API around resources, using hypermedia to link the resources together. As I've begun implementing things in Backbone, I'm starting to realize that accomplishing true hypermedia with Backbone may not be a good fit.
The main issue is backbone routers wanting to have their paths declared up-front. With a good Hypermedia API, resource URIs should not be hard-coded in the client, to allow for flexibility in adding new features and (gasp) changing resource locations.
I'm playing with the idea of decoupling client-level Page Resources from API-level Object Resources. Somebody scream if this is nuts. Basically, this would mean defining routes to resources within my backbone app (think a discrete page), which would then retrieve one or more API-level resources.
This leads to some interesting questions:
Is this even a good idea? Should I do my best to re-use the API-level resource URIs within my app such that the routes are 1-to-1.
- I realize that a page and an api object are just different representations of the same resource, but in most cases, a page is a composite of multiple resources. Or I'm just crazy :)
What happens with page-refreshes in the middle of a series of navigations. How do I know the location of the API-level resources if they aren't the same?
It seems to me that RESTful design emphasizes discovery over knowing things up front. Am I right in assuming this? Is this what code download is all about? Can someone point me to further reading if I'm going the right direction.
Most of the resources are read-only, and so only use the GET verb, but I do have a few scenarios that use POST/PUT (DELETE really isn't in the domain of this particular client, except for possibly aborting an order before it's placed fully).
*Let me just say that I am by no means a REST guru. I'm still in the process of learning, so feel free to tell me I'm off base completely. No feelings will be hurt.
Edit:
I've been thinking more about code download in relationship to SPAs. A few more options:
Define your resource URIs in an 'API' resource or similar, that is loaded dynamically (code download). Here's an example:
// this object downloaded along with the application code, on a refresh Framework.API.Resources = { Tasks: { uri: '/tasks', rel: 'self' }, Users: { uri: '/users', rel: 'self' }, // ... etc } // then in a collection var TaskCollection = Backbone.Collection.extend( uri: Framework.API.Resources.Tasks.uri // implementation details );
Dynamically define your routes as you navigate through resources, using the "root" resource uri as your route. I believe this is possible with Backbone.Router.route, but I'm not sure if it's possible to do on-the-fly. Has anyone tried this?