Skip to content
On this page

Messenger (graphql_messenger)

Adds a messengerMessages query field to fetch all Drupal messenger messages collected during resolving.

Schema

Base

graphql
# Custom scalar for messenger messages.
# Resolves to an untyped object.
scalar MessengerMessage

Extension

graphql
extend type Query {
  # Resolves the messenger messages for the current session.
  messengerMessages: MessengerMessage
}

extend type Mutation {
  # Resolves the messenger messages for the current session.
  messengerMessages: MessengerMessage
}

Examples

We assume this custom mutation adds a message using Drupal's Messenger. These messages are collected across multiple requests until they are fetched. Normally this results in these messages collecting until a page rendered by Drupal is visited.

graphql
mutation {
  messengerMessages
  customMutationThatAddsMessages
}
json
{
  "data": {
    "messengerMessages": [
      {
        "type": "error",
        "message": "This error is added by something we have no control over."
      }
    ],
    "customMutationThatAddsMessages": true
  }
}

How it works

The resolver returns an instance of a special class that implements a jsonSerialize() method. Here the messages are deleted and returned.

php
<?php

namespace Drupal\graphql_messenger;

use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Xss;

/**
 * Wrapper for collecting messenger messages.
 */
class MessageWrapper implements \JsonSerializable {

  public function jsonSerialize(): mixed {
    $messenger = \Drupal::messenger();
    $messages = $messenger->deleteAll();
    $messagesParsed = [];

    foreach ($messages as $type => $typeMessages) {
      foreach ($typeMessages as $message) {
        $messagesParsed[] = [
          'type' => $type,
          'message' => $message,
          'escaped' => Html::escape($message),
          'safe' => Xss::filter($message),
        ];
      }
    }
    return $messagesParsed;
  }

}