Score:0

How to return different entity reference fields from multiple bundles using the same name with JSON:API?

cn flag

The Goal

My site structure looks like this:

  • Node content type A with entity reference field groupA pointing to a term with field groupAfield
  • Node content type B with entity reference field groupB pointing to a term with field groupBfield

I want to be able to get content types A and B from a single JSON:API endpoint, and I want this endpoint to return groupB as groupA (rename groupB to groupA for nodes of content type B in the output).

This is to simplify the output for clients consuming JSON:API.

What I have tried

JSON:API usually only returns one bundle at a time. However, using the JSON:API Resources module, you can create your own custom resource that returns multiple entity types (using an entity query).

So I made a custom resource type.

I need to include the field values for both groupA and groupB, which I did like this:

$request->query->set('include', 'nodeTypeA.groupA.groupAfield','nodeTypeB.groupB.groupBfield');

This correctly gets all the data I need. So the last step is to rename groupB to groupA in the output. This is where I'm having trouble.

Normally, I would use the JSON:API Extras module to rename groupB to groupA for content type B. However, I cannot do this for my custom resource because then the include statement will break (because nodeTypeA's group does not have groupBField, and nodeTypeB's group does not have groupAField).

So, I need to do the renaming after JSON:API has done its processing:

$data = $this->loadResourceObjectDataFromEntityQuery($entity_query, $cacheability);
$response = $this->createJsonapiResponse($data, $request, 200, []);

But, this seems to be too late to change the output. Is there some way I can rename groupB to groupA just before returning the response?

Score:1
cn flag

From a #decoupled Slack conversation, bbrala (JSON:API maintainer) stated:

Don't think there is a supported way to do that other than extending and overwriting the controller that handles responses. Other modules do that too, but this will make the maintenance burden of you application higher and probably break some modules you might use.

One way to work around this would be to use Dynamic Entity Reference, but there are several issues that must be solved before DER and JSON:API can be used together.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.