Skip to content

Included relationships of relationships in JSONAPI serialization #132

@joanromano

Description

@joanromano

Given this model:

    struct Dog: JSONAPIEntity {
        let id: String
        let name: String
        let cat: Cat?
    }

    struct Cat: JSONAPIEntity {
        let id: String
        let name: String
    }

    struct User: JSONAPIEntity {
        let id: String
        let name: String
        let dog: Dog
        let cats: [Cat]
    }

And the serialization:

let cats = [Cat(id: "33", name: "Stancho"), Cat(id: "44", name: "Hez")]
let dog = Dog(id: "22", name: "Joan", cat: Cat(id: "55", name: "Max"))
let user = User(id: "11", name: "Alex", dog: dog, cats: cats)
JSONAPISerializer(user, includingChildren: true)

What we get back is the following JSON:

{
  "included" : [
    {
      "id" : "55",
      "type" : "cat",
      "attributes" : {
        "name" : "Max"
      }
    },
    {
      "id" : "33",
      "type" : "cat",
      "attributes" : {
        "name" : "Stancho"
      }
    },
    {
      "id" : "22",
      "type" : "dog",
      "attributes" : {
        "name" : "Joan"
      }
    },
    {
      "id" : "44",
      "type" : "cat",
      "attributes" : {
        "name" : "Hez"
      }
    }
  ],
  "data" : {
    "attributes" : {
      "name" : "Alex"
    },
    "id" : "11",
    "type" : "user",
    "relationships" : {
      "cats" : {
        "data" : [
          {
            "id" : "33",
            "type" : "cat"
          },
          {
            "id" : "44",
            "type" : "cat"
          }
        ]
      },
      "dog" : {
        "data" : {
          "id" : "22",
          "type" : "dog"
        }
      }
    }
  }
}

Where the dog object in included is missing his relationships attributes, so should be like:

{
      "id" : "22",
      "type" : "dog",
      "attributes" : {
        "name" : "Joan"
      },
      "relationships" : {
        "cat" : {
          "data" : {
            "id" : "55",
            "type" : "cat"
          }
        }
      }
}

So this should be fixed on JSONAPISerializable's func includedRelationships(includingChildren: Bool, transformingKeys keyTransformer: KeyTransformer?) -> [Any]?

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions