Imagine you have Posts, which can have many Likes. If a user is logged in and has previously liked a post, you want to include that like, though not all likes for that post.
So far, the only way I can think of expressing this through JSON API is:
include: post, post.current_user_like, and then have the API return just the current user’s like as a pseudo-relationship.
I’m curious how other people approach this problem.
Is this the default scenario, or an edge case you would like to support? If it is an edge case, you can simply add my-likes relationship. If this is the default behavior, why not just include it by default with that relationship?
Good point. This could totally be included by default, and now that you mention it, that’s exactly what I’ll do. After thinking about this for awhile though, I’m still curious how I would express this with {json-api}, if anyone else has come up with an approach they’re happy with.
That is completely legitimate {json:api}, I’m not sure what else you’re looking for. You could add some kind of filter alias and use that as a search term for it on the front end, but it’s completely valid design as far as the spec is concerned.
I’ve been scratching my head over this use-case as well and I have a few questions:
Is there no issue with having a relationship for “current-user-like” or “my-like” on the post resource that has a different value depending on what user is authenticated? That would also result in the posts/1/my-like endpoint representing a different resource depending on who is authenticated. I’ve read in some places that resources should have the same representation regardless of who is viewing them.
If that’s not an issue, then does it go for attributes as well? Could you simply have an “isLiked” attribute on the post resource which is true/false depending on if the authenticated user has liked it?
@Toby I think your point is valid and I would never implement the feature discussed here this way. Authentication should only impact your permission to make a certain request. It’s a yes or no. You either can or can’t.
I’m not saying it’s not valid JSON:API. It’s a personal choice.
If I couldn’t find a nice way to implement this feature without avoiding this, I would just make the client do two requests.