SeyZ / jsonapi-serializer

A Node.js framework agnostic library for (de)serializing your data to JSON API

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Why deserialize relationships into objects?

JakeDluhy opened this issue · comments

I guess I don't get why the deserialization works the way it does. If I'm posting the body of an entity I want to create, any relationships that I post with it I would expect to be deserialized into a format that is convenient for foreign keys. Instead, I must include an included payload which will have the information of the relationship. I can see the use for easy validation, although tbh I think I'd still want to pull the database record in order to make sure my information is up-to-date. Here's an example of what I mean:

I tried to send the payload

{
	"data": {
		"type": "moves",
		"attributes": {
			"from": "(-2)-(1)",
			"to": "(-1)-(1)"
		},
		"relationships": {
			"player-map": {
				"data": {
					"type": "player-maps",
					"id": 1
				}
			}
		}
	}
}

Which deserializes to

{ from: '(-2)-(1)', to: '(-1)-(1)' }

Investigating a little further, I realized I needed to add

"included": [
	{
		"type": "player-maps",
		"id": 1
	}
]

which deserializes to

{ from: '(-2)-(1)', to: '(-1)-(1)', playerMap: { id: 1 } }

But really, what I would like is to not have to add included, and have it automatically deserialize to

{ from: '(-2)-(1)', to: '(-1)-(1)', playerMapId: 1 }

for my foreign keys. I wrote a little function below to extract the data, so it's not a big deal, but I'm curious to hear the use case for deserializing to an object

const relObj = _.mapValues(
      _.mapKeys(ctx.request.body.data.relationships, (val, key) => `${_.camelCase(key)}Id`),
      (val) => _.get(val, 'data.id'),
);