SeyZ / jsonapi-serializer

A Node.js framework agnostic library for (de)serializing your data to JSON API
MIT License
735 stars 196 forks source link

Nested relationships are not deserialized properly if resource has multiple relations #141

Open Skysplit opened 7 years ago

Skysplit commented 7 years ago

There's a problem with includes reusability. It seems that once resource is included, it is no longer available to deserializer

Input

{
  data: [
    {
      type: 'posts',
      id: 1,
      attributes: {
        name: 'foo',
      },
      relationships: {
        author: {
          data: {
            type: 'users',
            id: 1,
          }
        },
        comments: {
          data: [
            {
              type: 'comments',
              id: 1
            }, {
              type: 'comments',
              id: 2,
            }, {
              type: 'comments',
              id: 3
            },
          ]
        },
      },
    },
  ],
  included: [
    {
      type: 'users',
      id: 1,
      attributes: {
        name: 'John',
      },
    },
    {
      type: 'users',
      id: 2,
      attributes: {
        name: 'Jane'
      },
    },
    {
      type: 'comments',
      id: 1,
      attributes: {
        content: 'lorem',
      },
      relationships: {
        author: {
          data: {
            type: 'users',
            id: 1,
          },
        },
      }
    },
    {
      type: 'comments',
      id: 2,
      attributes: {
        content: 'ipsum',
      },
      relationships: {
        author: {
          data: {
            type: 'users',
            id: 2,
          },
        },
      }
    },
    {
      type: 'comments',
      id: 3,
      attributes: {
        content: 'dolor',
      },
      relationships: {
        author: {
          data: {
            type: 'users',
            id: 2,
          },
        },
      }
    },
  ],
}

Expected output

[
  {
    name: 'foo',
    id: 1,
    author: {
      name: 'John', id: 1
    },
    comments: [
      { content: 'lorem', id: 1, author: { name: 'John', id: 1 } },
      { content: 'ipsum', id: 2, author: { name: 'Jane', id: 2 } },
      { content: 'dolor', id: 3, author: { name: 'Jane', id: 2 } }
    ]
  }
]

Actual output

[
  {
    name: 'foo',
    id: 1,
    author: { name: 'John', id: 1 },
    comments: [
      { content: 'lorem', id: 1 },
      { content: 'ipsum', id: 2, author: { name: 'Jane', id: 2 } },
      { content: 'dolor', id: 3 }
    ]
  }
]
leoskyrocker commented 7 years ago

+1

olosegres commented 7 years ago

This problem solved in similar lib

charly-palencia commented 6 years ago

jsona is amazing! it solved my issue, thanks @olosegres ! bye bye jsonapi-serializer

AELSchauer commented 6 years ago

Hey all, I solved this issue with my PR #170. I'm not sure when (or if) it will be merged, but you can access my forked repo here -- https://github.com/AELSchauer/jsonapi-serializer