# Drupal Message Support

The Drupal `graphql_code_schema` module comes with a
[submodule to support Drupal messages](https://graphql-core-schema.netlify.app/modules/messenger.html). It adds a
messengerMessages query field to fetch all Drupal messenger messages collected during resolving.

## Queries
This is an example of a mutation that fetches all messages created by Drupal during execution.

```graphql
mutation {
  messengerMessages
  youCustomMutationThatAddsMessages
}
```

## 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;
  }

}
```
