Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using Backbone Relational to handle JSON-API Data #530

Open
newtonianb opened this issue Jun 2, 2015 · 1 comment
Open

Using Backbone Relational to handle JSON-API Data #530

newtonianb opened this issue Jun 2, 2015 · 1 comment
Labels

Comments

@newtonianb
Copy link

We've been using Backbone Relational to model our ORM relationship in the front end for instance:

{
  id: 2
  username: "bob"
  comments: [
     {
        id:5,
        comment: "hi",
        user: {
           username: 'Bob'
        }
     }

  ]
}

That has been working great using models such as this in the front end:

  class User extends App.RelationalModel
    relations: [{
      type: Backbone.HasMany,
      key: 'comments',
      relatedModel: 'Comment',
      collectionType: 'CommentCollection'
    }]

However now our api has changed and respecting more of the JSON-API Spec so the data from the back end is encapsulated inside of 'data'.

{
  data: {
    id: 2
    username: "bob"
    data: {
      comments: [
         {
            id:5,
            comment: "hi",
            user: {
               username: 'Bob'
            }
         }
      ]
    },
    meta: {
    }
  }
}

How can we instruct backbone relational to get the data for the 'comments' relation from .data instead of mapping the json structure directly?

For the ''class User'' we can implement the parse method like so

class User
  parse: (response) ->
    response.data

But how do we do this for the comments relation??

@bpatram
Copy link
Collaborator

bpatram commented Mar 27, 2016

Your data sample does not come close to representing what the JSON-API spec defines.

You'll most likely want to create a parse function on your Comment model that would transform user: { username: 'Bob' } into { user: { id: 2 } } then where you create the relation between User and Comment set parse: true OR you could set the idAttribute on your User model to be username which may cause issues elsewhere when fetching/saving.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants