Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add methods to support App Router #716

Merged
merged 6 commits into from
Apr 18, 2024
Merged

Add methods to support App Router #716

merged 6 commits into from
Apr 18, 2024

Conversation

JohnAlbin
Copy link
Collaborator

@JohnAlbin JohnAlbin commented Mar 7, 2024

This pull request is for:

  • packages/next-drupal

GitHub Issue: #665

Describe your changes

The DrupalClient class has been renamed to NextDrupalPages and refactored to inherit from 2 base classes. All the methods that were in DrupalClient have been distributed amongst these 3 classes.

NextDrupalPages (includes Pages Router methods)
inherits from
NextDrupal (includes App Router methods and JSON:API methods)
inherits from
NextDrupalBase (includes Fetch method, authentication methods and basic helper methods)

DrupalClient v1.6 methods moved to v2.0 class
fetch() NextDrupalBase

The FetchOptions Type definition said that a Headers object could be passed to headers but this wasn't true in v1.6. This has been fixed in v2.0.
buildUrl() NextDrupalBase
private _debug() NextDrupalBase

Renamed to debug() and made public. See #668
getAccessToken() NextDrupalBase
private handleJsonApiErrors() NextDrupalBase

Made public and renamed to throwIfJsonErrors() since it handles both regular JSON error messages and JSON:API errors. It's included in NextDrupalBase since it is used by getAccessToken().
private getErrorsFromResponse() NextDrupalBase

To support inheritance, this method is now public. It's included in NextDrupalBase since it is used by getAccessToken().
createResource() NextDrupal
createFileResource() NextDrupal
updateResource() NextDrupal
deleteResource() NextDrupal
getResource() NextDrupal
getResourceByPath() NextDrupal
getResourceCollection() NextDrupal
translatePath() NextDrupal
getIndex() NextDrupal
getMenu() NextDrupal
buildMenuTree() NextDrupalPages

This method has been refactored to be a wrapper around new DrupalMenuTree(items).
getView() NextDrupal
getSearchIndex() NextDrupal
deserialize() NextDrupal
private throwError() NextDrupal

Made public and renamed to logOrThrowError to better reflect its purpose.
getEntryForResourceType() NextDrupalPages
getResourceFromContext() NextDrupalPages
getResourceCollectionFromContext() NextDrupalPages
getPathsFromContext() NextDrupalPages
getStaticPathsFromContext() NextDrupalPages
buildStaticPathsFromResources() NextDrupalPages
buildStaticPathsParamsFromPaths() NextDrupalPages
translatePathFromContext() NextDrupalPages
getPathFromContext() NextDrupalPages
preview() NextDrupalPages
getSearchIndexFromContext() NextDrupalPages
private formatJsonApiErrors()

Removed; any internal usage was replaced with the public static method JsonApiErrors.formatMessage()
private getAuthFromContextAndOptions() NextDrupalPages

Made public.

The following new methods are available. New methods that don't mention a separate issue number were added with this PR.

New Methods Class
buildEndpoint() NextDrupalBase and NextDrupal

Builds an endpoint URL using apiPrefix. The NextDrupal version adds additional JSON:API-specific options. This method is a better version of the old getEntryForResourceType() method.
fetchResourceEndpoint() NextDrupal

Helper method to lookup the endpoint URL instead of constructing it.
getAuthorizationHeader() NextDrupalBase

See #707.
constructPathFromSegment() NextDrupalBase

Replaces the getPathFromContext() method for App Router use cases.
getResourceCollectionPathSegments() NextDrupal

For use with Next.js' generateStaticParams(). Replaces Pages Router's getStaticProps() and DrupalClient.getStaticPathsFromContext() method.
addLocalePrefix() NextDrupalBase

Helper method that conditionally adds a locale prefix to a Drupal path.
validateDraftUrl() NextDrupalBase

Helper method used by the "next-drupal/draft" functions and DrupalClient.preview(). See #670.

getResourceCollectionPathSegments()

The new getResourceCollectionPathSegments() method supports Next.js' generateStaticParams() function. It returns an array of Drupal path-related data that can be used to provide a static list for use in Next.js Dynamic Segments.

Each item in the returned array looks like this:

{
  path: "/blog/some-category/a-blog-post", // The unaltered Drupal path alias
  type: "node--article",
  locale: "en", // or `undefined` if no `locales` requested.
  segments: ["blog", "some-category", "a-blog-post"],
}

In many cases, the segments array will the only item needed. But the other properties of the object will allow more advanced use-cases.

Examples:

When used in a app/[...slug]/page.tsx file, the [...slug] Dynamic Segment indicates that generateStaticParams() is expected to return an array of objects with a slug property containing an array of strings.

export async function generateStaticParams(): Promise<NodePageParams[]> {
  const resources = await drupal.getResourceCollectionPathSegments(
    ["node--page", "node--article"]
  );

  return resources.map((resource) => {
    return {
      slug: resource.segments,
    }
  });
}

When used in a app/[lang]/blog/[category]/[...slug]/page.tsx file, generateStaticParams() is expected to return an array of objects with a lang string, a category string and a slug array of strings.

export async function generateStaticParams(): Promise<NodePageParams[]> {
  const resources = await drupal.getResourceCollectionPathSegments(
   ["node--article"],
    {
      // The pathPrefix will be removed from the returned path segments array.
      pathPrefix: "/blog",
      // The list of locales to return.
      locales: ["en", "es"],
      // The default locale.
      defaultLocale: "en",
    }
  );

  return resources.map((resource) => {
    // NOTE: Because `pathPrefix` was set to "/blog",
    // "blog" will not be included in the segments array.

    // Grab the first item from the segments array to get
    // the needed "category" param.
    const category = resource.segments.unshift();

    return {
      lang: resource.locale,
      category,
      slug: resource.segments, 
    };
  })
}

Copy link

vercel bot commented Mar 7, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
next-drupal ❌ Failed (Inspect) Apr 18, 2024 0:24am

@JohnAlbin JohnAlbin force-pushed the 665-app-router-methods branch from 3796ef2 to 661cae1 Compare March 8, 2024 10:00
@JohnAlbin JohnAlbin marked this pull request as ready for review March 8, 2024 10:01
@JohnAlbin JohnAlbin mentioned this pull request Mar 8, 2024
@JohnAlbin JohnAlbin force-pushed the 665-app-router-methods branch 2 times, most recently from 1107112 to bcc17d4 Compare March 8, 2024 17:30
@JohnAlbin JohnAlbin force-pushed the 665-app-router-methods branch 4 times, most recently from 149cab0 to e3ea377 Compare March 11, 2024 11:51
@JohnAlbin JohnAlbin mentioned this pull request Mar 11, 2024
2 tasks
@JohnAlbin JohnAlbin force-pushed the 665-app-router-methods branch 5 times, most recently from 56d03c6 to 1bd09ff Compare April 2, 2024 01:58
@JohnAlbin JohnAlbin force-pushed the 665-app-router-methods branch 2 times, most recently from 6b47ab2 to 9856af9 Compare April 14, 2024 10:34
@JohnAlbin JohnAlbin force-pushed the 665-app-router-methods branch 6 times, most recently from e582f5b to 177c4a7 Compare April 15, 2024 17:16
@JohnAlbin
Copy link
Collaborator Author

JohnAlbin commented Apr 16, 2024

Blocked by #740

And… unblocked now.

The DrupalClient class has been renamed to NextDrupalPages and has been
refactored to inherit from the NextDrupalBase (base class) and NextDrupal
(JsonAPI/App Router class). NextDrupalPages class contains the methods that are
only needed to support Next.js' Pages Router. NextDrupalPages is also available
as "DrupalClient" for backwards-compatibility.

The getPathFromContext() method has been replaced with the
constructPathFromSegment() method for App Router usages.

Issue #665
…ticParams()

The App Router's new generateStaticParams() replaces Pages Router's
getStaticProps(). The new getResourceCollectionPathSegments() method supports
generateStaticParams() by returning a list of path segments. This new method
replaces the old getStaticPathsFromContext() method.

Fixes #665
@JohnAlbin JohnAlbin merged commit 499d023 into main Apr 18, 2024
10 of 11 checks passed
@JohnAlbin JohnAlbin deleted the 665-app-router-methods branch April 18, 2024 17:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants