While working on #3104957: Fire an event to allow modules to react to user registration, I needed the top level JSON:API document to receive some metadata. Alas, I could not. After speaking with @gabesullice, we have an idea.

The DocumentExtractor service. This takes a request object and returns a JSON:API document. This extracts logic currently in the DocumentResolver argument resolver and moves it to a service that supports caching based on requests.

We currently do something like this in Commerce for resolving the current store per request with \SplObjectStorage.

https://git.drupalcode.org/project/commerce/blob/8.x-2.x/modules/store/s...

    $request = $this->requestStack->getCurrentRequest();
    if (!$this->stores->contains($request)) {
      $this->stores[$request] = $this->chainResolver->resolve();
    }

The DocumentExtractor can check if the request exists in cache and then return the extracted document, otherwise it can perform actions. This makes it possible for anyone to take a request and receive a JSON:API documentation! (for better or worse!)

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

mglaman created an issue. See original summary.

mglaman’s picture

Assigned: Unassigned » mglaman
Status: Active » Needs review
FileSize
14.87 KB

🙈 WIP patch at EOD and I did not run tests locally. I'll pick this up tomorrow.

mglaman’s picture

😱 they passed

mglaman’s picture

mglaman’s picture

Status: Needs work » Needs review
FileSize
24.57 KB

Rerolled!

mglaman’s picture

+++ b/src/Unstable/DocumentExtractor.php
@@ -0,0 +1,285 @@
+   * @param \Symfony\Component\HttpFoundation\Request $request
+   *   The request.
+   * @return \Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel
+   *   The document.
...
+   * @param \Symfony\Component\HttpFoundation\Request $request
+   *   The request.
+   * @return \Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel
+   *   The document.

Forgot newline, fix on commit.

mglaman’s picture

Assigned: mglaman » Unassigned
FileSize
27.63 KB
5.4 KB

This adds the getDocumentFromRequest method to ResourceBase as an API method for retrieving the document in subclasses.

mglaman’s picture

Crediting gabesullice for review and discussions.

  • mglaman committed f673fa2 on 8.x-1.x
    Issue #3104972 by mglaman, gabesullice: Move extracting documents from...
mglaman’s picture

Status: Needs review » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.