PaulUithol / Backbone-relational

Get and set relations (one-to-one, one-to-many, many-to-one) for Backbone models
http://backbonerelational.org
MIT License
2.34k stars 330 forks source link

Using Backbone Relational to handle JSON-API Data #530

Open newtonianb opened 9 years ago

newtonianb commented 9 years ago

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 commented 8 years ago

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.