I’m using mongodb, node.js and backbone.js to build an app that will serve as a learning experience for me. I’m interested to know what is best practice for fetching related objects from a REST API for this sort of thing.
Let’s say we have “post” objects and “user” objects, with posts having a “userId” property that links them to users.
Should you:
- Fetch a post object on the client side. Inspect the “userId” property of the post and then separately fetch that user. This seems to be nice and simple in terms of server-side code, but could end up making lots of requests if things get complicated further down the line.
- Fetch a post object, and have the server “make the join” and give you the related user object, in the same request.
Does anyone have some experience that they could share?
Thanks
It’s hard to answer this without a specific UI story, but based on what you have provided, I’d say #1 is closer to the approach I would take. However, instead of ‘inspecting’ the post for the userId, provide the link to the user with the
rel=userand simply follow that link for your user resource. I prefer the HATEOAS paradigm where these resources are navigated through explicit links constructed by the server, not the client.This obviously will result in more XHR’s but if that is a concern then I’d suggest that your view is requiring a view model which serves it without joins. This is done by exposing a dedicated model that serves the client simply without making the client responsible for constructing data it needs.
hth,
mike