0

I'm building a web app using Ember 1.5 and I use Ember Model 0.0.11 to link the app to an API. I'm currently having trouble getting Ember Model to use nested API endpoints.

For instance, my app has a User model, which has a hasMany relationship with a Post model. Now, when I want to load the posts for a certain user, I'd like the Post.findQuery('user_id', {user_id}); method to access the GET /users/{user_id}/posts endpoint. Instead, it seems that the Ember Model solution prefers to send the query as a parameter to the GET /posts endpoint.

Ember Model's RESTAdapter does allow for easy customization, but before I start coding a completely custom RESTAdapter I'd love to know if someone has already done this and how they solved the problem.

MdeWit
  • 1
  • 1

1 Answers1

0

The solution for us to handle nested API routes was to have a links hash returned with the requested payload. If you can change the API output, this is the way to go for now. For example, when requesting a workspace, the returned JSON looks like this (excuse the escaped characters):

{
   "data":
      {
         "object":"workspace",
         "id":"wrk_krVZWGaJ",
         "organization_name":"Legros, Klein and Boehm",
         "workspace_name":"Legros, Klein and Boehm",
         "workspace_path":"legros, klein and boehm",
         "status":true,
         "credit_production":7,
         "credit_revision":16,
         "links":{
            "projects":"\/v1\/workspaces\/wrk_krVZWGaJ\/projects",
            "productions":"\/v1\/workspaces\/wrk_krVZWGaJ\/productions",
            "subscription":"\/v1\/workspaces\/wrk_krVZWGaJ\/subscription",
            "assets":"\/v1\/workspaces\/wrk_krVZWGaJ\/assets",
            "descriptions":"\/v1\/workspaces\/wrk_krVZWGaJ\/descriptions",
            "roles":"\/v1\/workspaces\/wrk_krVZWGaJ\/roles",
            "registrations":"\/v1\/workspaces\/wrk_krVZWGaJ\/registrations",
            "users":"\/v1\/workspaces\/wrk_krVZWGaJ\/users"
         }
      }
}

The model defines the links as async hasMany relationships, i.e. DS.attr('projects', {async: true}). When the workspace is loaded from the store, the linked projects aren't included. When you use {{#each workspace.projects}} or workspace.get('projects') anywhere else, ember-data will make a GET request to /v1/workspaces/wrk_krVZWGaJ/projects/, rather than the default route of /projects/. Neato, eh?

More details on the RESTAdapter findHasMany method.

ToddSmithSalter
  • 715
  • 6
  • 20