You are here

public function GatsbyInstantPreview::gatsbyPrepareData in Gatsby Live Preview & Incremental Builds 8

Same name and namespace in other branches
  1. 2.0.x modules/gatsby_instantpreview/src/GatsbyInstantPreview.php \Drupal\gatsby_instantpreview\GatsbyInstantPreview::gatsbyPrepareData()

Prepares Gatsby Data to send to the preview and build servers.

By preparing the data in a separate step we prevent multiple requests from being sent to the preview or incremental builds servers if multiple Drupal entities are update/inserted/deleted in a single request.

Overrides GatsbyPreview::gatsbyPrepareData

File

modules/gatsby_instantpreview/src/GatsbyInstantPreview.php, line 67

Class

GatsbyInstantPreview
Defines a class to extend the default preview system with an instant preview.

Namespace

Drupal\gatsby_instantpreview

Code

public function gatsbyPrepareData(ContentEntityInterface $entity = NULL, string $action = 'update') {
  $json = $this
    ->getJson($entity);
  if (!$json) {
    return;
  }
  $json['id'] = $entity
    ->uuid();
  $json['action'] = $action;

  // If there is a secret key, we decode the json, add the key, then encode.
  $settings = $this->configFactory
    ->get('gatsby.settings');
  if ($settings
    ->get('secret_key')) {
    $json['secret'] = $settings
      ->get('secret_key');
  }
  $preview_url = $settings
    ->get('preview_callback_url');
  if ($preview_url) {
    $json = $this
      ->bundleData('preview', $preview_url, $json);
    $this
      ->updateData('preview', $preview_url, $json);
  }
  $incrementalbuild_url = $settings
    ->get('incrementalbuild_url');
  if (!$incrementalbuild_url) {
    return;
  }
  if ($settings
    ->get('build_published')) {
    if (!$entity instanceof NodeInterface || !$entity
      ->isPublished()) {
      return;
    }
    if (empty($json['data']['relationships'])) {
      return;
    }

    // Generate JSON for all related entities to send to Gatsby.
    $entity_data = [];
    $included_types = $settings
      ->get('preview_entity_types') ?: [];
    $this
      ->buildRelationshipJson($json['data']['relationships'], $entity_data, array_values($included_types));
    if (!empty($entity_data)) {

      // Remove the uuid keys from the array.
      $entity_data = array_values($entity_data);
      $original_data = $json['data'];
      $entity_data[] = $original_data;
      $json['data'] = $entity_data;
    }
  }
  $json = $this
    ->bundleData('incrementalbuild', $incrementalbuild_url, $json);
  $this
    ->updateData('incrementalbuild', $incrementalbuild_url, $json);
}