drupal-graphql / graphql

GraphQL integration for Drupal 9/10
287 stars 202 forks source link

How to create or use union types #990

Open hiwllc opened 4 years ago

hiwllc commented 4 years ago

Hi,

I want to create a union type for a specific field but, I don't find any examples of documentation about this, there's an example of how to do this?

pmaidminutes commented 3 years ago

I am looking for an example too

dottodot commented 2 years ago

Yes an example would be very helpful as it not very clear on how to implement it.

ChexWarrior commented 2 years ago

Adding what I discovered while implementing a Union type:

I'm assuming you've already implemented your union type like so:

union ModalContent = ParagraphImage | TextImage | BodyText

And there is another type referencing that union type:

type PopOut {
  linkText: String
  title: String
  modalContent(lang: String!): [ModalContent]
}

You need to resolve whatever fields are using the union type:

$registry->addFieldResolver('PopOut', 'modalContent',
      $builder->produce('entity_reference_revisions')
        ->map('entity', $builder->fromParent())
        ->map('field', $builder->fromValue('field_modal_content'))
        ->map('language', $builder->fromArgument('lang'))
    );

And critically you need to add a type resolver so the code can figure out which underlying type each instance of the union type should resolve to:

$registry->addTypeResolver('ModalContent', function(Paragraph $paragraph) {
      $bundle = $paragraph->bundle();
      return match($bundle) {
          'full_width_image', 'image_collection' => 'ParagraphImage',
          'text_image' => 'TextImage',
          'body_text' => 'BodyText'
      };
    });

At this point each instance of the union type will resolve based on it's matching underlying type. I'm far from an expert on this but I felt I should add what I discovered up here to help anyone else out that's looking.