Class NextDrupal

The NextDrupal class extends the NextDrupalBase class and provides methods for interacting with a Drupal backend.

Hierarchy (View Summary)

Constructors

Properties

accessToken?: AccessToken
baseUrl: string
cache?: DataCache
deserializer: JsonDeserializer
fetcher?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>

Type declaration

    • (input: RequestInfo | URL, init?: RequestInit): Promise<Response>
    • Parameters

      • input: RequestInfo | URL
      • Optionalinit: RequestInit

      Returns Promise<Response>

frontPage: string
isDebugEnabled: boolean
logger: Logger
throwJsonApiErrors: boolean
useDefaultEndpoints: boolean
withAuth: boolean

Accessors

  • get apiPrefix(): string
  • Returns string

  • set apiPrefix(apiPrefix: string): void
  • Parameters

    • apiPrefix: string

    Returns void

  • get auth(): NextDrupalAuth
  • Returns NextDrupalAuth

  • set auth(auth: NextDrupalAuth): void
  • Parameters

    Returns void

  • get headers(): HeadersInit
  • Returns HeadersInit

  • set headers(headers: HeadersInit): void
  • Parameters

    • headers: HeadersInit

    Returns void

  • get token(): AccessToken
  • Returns AccessToken

  • set token(token: AccessToken): void
  • Parameters

    Returns void

Methods

  • Adds a locale prefix to the given path.

    Parameters

    • path: string

      The path.

    • options: { defaultLocale?: string; locale?: string } = {}

      The options for adding the locale prefix.

      • OptionaldefaultLocale?: string

        The default locale.

      • Optionallocale?: string

        The locale.

    Returns string

    The path with the locale prefix.

  • Builds an endpoint URL for the specified parameters.

    Parameters

    • params: { locale?: string; path?: string; searchParams?: EndpointSearchParams } & {
          resourceType?: string;
      } = {}

      The parameters for the endpoint.

    Returns Promise<string>

    The built endpoint URL.

  • Builds a URL with the given path and search parameters.

    Parameters

    • path: string

      The path for the url. Example: "/example"

    • OptionalsearchParams: EndpointSearchParams

      Optional query parameters.

    Returns URL

    The constructed URL.

    const drupal = new DrupalClient("https://example.com")

    // https://drupal.org
    drupal.buildUrl("https://drupal.org").toString()

    // https://example.com/foo
    drupal.buildUrl("/foo").toString()

    // https://example.com/foo?bar=baz
    client.buildUrl("/foo", { bar: "baz" }).toString()

    Build a URL from DrupalJsonApiParams

    const params = {
    getQueryObject: () => ({
    sort: "-created",
    "fields[node--article]": "title,path",
    }),
    }

    // https://example.com/jsonapi/node/article?sort=-created&fields%5Bnode--article%5D=title%2Cpath
    drupal.buildUrl("/jsonapi/node/article", params).toString()
  • Constructs a path from the given segment and options.

    Parameters

    • segment: string | string[]

      The path segment.

    • options: { defaultLocale?: string; locale?: string; pathPrefix?: string } = {}

      The options for constructing the path.

      • OptionaldefaultLocale?: string

        The default locale.

      • Optionallocale?: string

        The locale.

      • OptionalpathPrefix?: string

        The path prefix.

    Returns string

    The constructed path.

  • Creates a new file resource for the specified media type.

    Type Parameters

    Parameters

    • type: string

      The type of the resource. In most cases this is file--file.

    • body: JsonApiCreateFileResourceBody

      The body payload with data.

      • type: The resource type of the host entity. Example: media--image
      • field: The name of the file field on the host entity. Example: field_media_image
      • filename: The name of the file with extension. Example: avatar.jpg
      • file: The file as a Buffer
    • Optionaloptions: JsonApiOptions & JsonApiWithNextFetchOptions

      Options for the request.

    Returns Promise<T>

    The created file resource.

    Create a file resource for a media--image entity

    const file = await drupal.createFileResource("file--file", {
    data: {
    attributes: {
    type: "media--image", // The type of the parent resource
    field: "field_media_image", // The name of the field on the parent resource
    filename: "filename.jpg",
    file: await fs.readFile("/path/to/file.jpg"),
    },
    },
    })

    You can then use this to create a new media--image with a relationship to the file:

    const media = await drupal.createResource<DrupalMedia>("media--image", {
    data: {
    attributes: {
    name: "Name for the media",
    },
    relationships: {
    field_media_image: {
    data: {
    type: "file--file",
    id: file.id,
    },
    },
    },
    },
    })
  • Creates a new resource of the specified type.

    Type Parameters

    Parameters

    Returns Promise<T>

    The created resource.

    Create a node--page resource

    const page = await drupal.createResource("node--page", {
    data: {
    attributes: {
    title: "Page Title",
    body: {
    value: "<p>Content of body field</p>",
    format: "full_html",
    },
    },
    },
    })

    Create a node--article with a taxonomy term

    const article = await drupal.createResource("node--article", {
    data: {
    attributes: {
    title: "Title of Article",
    body: {
    value: "<p>Content of body field</p>",
    format: "full_html",
    },
    },
    relationships: {
    field_category: {
    data: {
    type: "taxonomy_term--category",
    id: "28ab9f26-927d-4e33-9510-b59a7ccdafe6",
    },
    },
    },
    },
    })

    Using filters

    const page = await drupal.createResource(
    "node--page",
    {
    data: {
    attributes: {
    title: "Page Title",
    body: {
    value: "<p>Content of body field</p>",
    format: "full_html",
    },
    },
    },
    },
    {
    params: {
    "fields[node--page]": "title,path",
    },
    }
    )

    Using TypeScript with DrupalNode

    import { DrupalNode } from "next-drupal"
    const page = await drupal.createResource<DrupalNode>("node--page", {
    data: {
    attributes: {
    title: "Page Title",
    body: {
    value: "<p>Content of body field</p>",
    format: "full_html",
    },
    },
    },
    })
  • Logs a debug message if debug mode is enabled.

    Parameters

    • message: any

      The debug message.

    Returns void

  • Deletes an existing resource of the specified type.

    Parameters

    • type: string

      The type of the resource. Example: node--article, taxonomy_term--tags, or block_content--basic.

    • uuid: string

      The resource id. Example: a50ffee7-ba94-46c9-9705-f9f8f440db94.

    • Optionaloptions: JsonApiOptions & JsonApiWithNextFetchOptions

      Options for the request.

    Returns Promise<boolean>

    True if the resource was deleted, false otherwise.

    Delete a node--page resource

    const isDeleted = await drupal.deleteResource(
    "node--page",
    "a50ffee7-ba94-46c9-9705-f9f8f440db94"
    )
  • Deserializes the response body.

    Parameters

    • body: any

      The response body.

    • Optionaloptions: any

      Options for deserialization.

    Returns TJsonaModel | TJsonaModel[]

    The deserialized response body.

    To provide your own custom deserializer, see the serializer docs.

    const url = drupal.buildUrl("/jsonapi/node/article", {
    sort: "-created",
    "fields[node--article]": "title,path",
    })

    const response = await drupal.fetch(url.toString())
    const json = await response.json()

    const resource = drupal.deserialize(json)
  • Fetches a resource from the given input URL or path.

    Parameters

    • input: RequestInfo

      The url to fetch from.

    • init: FetchOptions = {}

      The fetch options with withAuth. If withAuth is set, fetch will fetch an Authorization header before making the request.

    Returns Promise<Response>

    The fetch response.

    To provide your own custom fetcher, see the fetcher docs.

    const url = drupal.buildUrl("/jsonapi/node/article", {
    sort: "-created",
    "fields[node--article]": "title,path",
    })

    const response = await drupal.fetch(url.toString())
  • Fetches the endpoint URL for the specified resource type.

    Parameters

    • type: string

      The type of the resource.

    • Optionallocale: string

      The locale for the request.

    Returns Promise<URL>

    The fetched endpoint URL.

  • Retrieve an access token.

    Parameters

    Returns Promise<AccessToken>

    The access token.

    If options is not provided, DrupalClient will use the clientId and clientSecret configured in auth.

    const accessToken = await drupal.getAccessToken({
    clientId: "7034f4db-7151-466f-a711-8384bddb9e60",
    clientSecret: "d92Fm^ds",
    })
  • Gets the authorization header value based on the provided auth configuration.

    Parameters

    Returns Promise<string>

    The authorization header value.

  • Extracts errors from the fetch response.

    Parameters

    • response: Response

      The fetch response.

    Returns Promise<string | JsonApiError[]>

    The extracted errors.

  • Fetches a menu by its name.

    Type Parameters

    Parameters

    Returns Promise<{ items: T[]; tree: T[] }>

    The fetched menu.

    • items: An array of DrupalMenuLinkContent
    • tree: An array of DrupalMenuLinkContent with children nested to match the hierarchy from Drupal

    JSON:API Menu Items module

    Get the main menu

    const { menu, items } = await drupal.getMenu("main")
    

    Get the main menu using cache

    const menu = await drupal.getMenu("main", {
    withCache: true,
    cacheKey: "menu--main",
    })
  • Fetches a resource of the specified type by its UUID.

    Type Parameters

    Parameters

    Returns Promise<T>

    The fetched resource.

    Get a page by uuid.

    const node = await drupal.getResource(
    "node--page",
    "07464e9f-9221-4a4f-b7f2-01389408e6c8"
    )

    Get the es translation for a page by uuid.

    const node = await drupal.getResource(
    "node--page",
    "07464e9f-9221-4a4f-b7f2-01389408e6c8",
    {
    locale: "es",
    defaultLocale: "en",
    }
    )

    Get the raw JSON:API response.

    const { data, meta, links } = await drupal.getResource(
    "node--page",
    "07464e9f-9221-4a4f-b7f2-01389408e6c8",
    {
    deserialize: false,
    }
    )

    Get a node--article resource using cache.

    const id = "07464e9f-9221-4a4f-b7f2-01389408e6c8"

    const article = await drupal.getResource("node--article", id, {
    withCache: true,
    cacheKey: `node--article:${id}`,
    })

    Get a page resource with time-based revalidation.

    const node = await drupal.getResource(
    "node--page",
    "07464e9f-9221-4a4f-b7f2-01389408e6c8",
    { next: { revalidate: 3600 } }
    )

    Get a page resource with tag-based revalidation.

    const {slug} = params;
    const path = drupal.translatePath(slug)

    const type = path.jsonapi.resourceName
    const tag = `${path.entity.type}:${path.entity.id}`

    const node = await drupal.getResource(path, path.entity.uuid, {
    params: params.getQueryObject(),
    tags: [tag]
    })

    Using DrupalNode for a node entity type.

    import { DrupalNode } from "next-drupal"

    const node = await drupal.getResource<DrupalNode>(
    "node--page",
    "07464e9f-9221-4a4f-b7f2-01389408e6c8"
    )

    Using DrupalTaxonomyTerm for a taxonomy term entity type.

    import { DrupalTaxonomyTerm } from "next-drupal"

    const term = await drupal.getResource<DrupalTaxonomyTerm>(
    "taxonomy_term--tags",
    "7b47d7cc-9b1b-4867-a909-75dc1d61dfd3"
    )
  • Fetches a resource of the specified type by its path.

    Type Parameters

    Parameters

    • path: string

      The path of the resource. Example: /blog/slug-for-article.

    • Optionaloptions: { isVersionable?: boolean } & (JsonApiOptions & JsonApiWithNextFetchOptions)

      Options for the request.

      • isVersionable: Set to true if you're fetching the revision for a resource. Automatically set to true for node entity types

    Returns Promise<T>

    The fetched resource.

    Decoupled Router module

    Get a page by path

    const node = await drupal.getResourceByPath("/blog/slug-for-article")
    

    Get the raw JSON:API response

    const { data, meta, links } = await drupal.getResourceByPath(
    "/blog/slug-for-article",
    {
    deserialize: false,
    }
    )

    Using DrupalNode for a node entity type

    import { DrupalNode } from "next-drupal"
    const node = await drupal.getResourceByPath<DrupalNode>(
    "/blog/slug-for-article"
    )
  • Fetches a collection of resources of the specified type.

    Type Parameters

    Parameters

    • type: string

      The type of the resources. Example: node--article or user--user.

    • Optionaloptions: { deserialize?: boolean } & (JsonApiOptions & JsonApiWithNextFetchOptions)

      Options for the request.

      • deserialize: Set to false to return the raw JSON:API response

    Returns Promise<T>

    The fetched collection of resources.

    Get all articles

    const articles = await drupal.getResourceCollection("node--article")
    

    Using filters

    const publishedArticles = await drupal.getResourceCollection("node--article", {
    params: {
    "filter[status]": "1",
    },
    })

    Get the raw JSON:API response

    const { data, meta, links } = await drupal.getResourceCollection("node--page", {
    deserialize: false,
    })

    Using TypeScript with DrupalNode for a node entity type

    import { DrupalNode } from "next-drupal"
    const nodes = await drupal.getResourceCollection<DrupalNode[]>("node--article")
  • Fetches path segments for a collection of resources of the specified types.

    Parameters

    • types: string | string[]

      The types of the resources.

    • Optionaloptions: { params?: JsonApiParams; pathPrefix?: string } & JsonApiWithAuthOption & (
          JsonApiWithNextFetchOptions & ({ locales: string[]; defaultLocale: string; } | { locales?: undefined; defaultLocale?: never; })
      )

      Options for the request.

    Returns Promise<{ locale: string; path: string; segments: string[]; type: string }[]>

    The fetched path segments.

  • Fetches a search index by its name.

    Type Parameters

    Parameters

    Returns Promise<T>

    The fetched search index.

    JSON:API Search API module

    Get search results from an index named articles

    const results = await drupal.getSearchIndex("articles")
    

    Using TypeScript with DrupalNode for a node entity type

    import { DrupalNode } from "next-drupal"

    const results = await drupal.getSearchIndex<DrupalNode>("articles")
  • Fetches a view by its name.

    Type Parameters

    Parameters

    Returns Promise<DrupalView<T>>

    The fetched view.

    JSON:API Views module

    Get a view named articles and display id promoted

    const view = await drupal.getView("articles--promoted")
    

    Using sparse fieldsets to only fetch the title and body fields

    const view = await drupal.getView("articles--promoted", {
    params: {
    fields: {
    "node--article": "title,body",
    },
    },
    })

    Using TypeScript with DrupalNode for a node entity type

    import { DrupalNode } from "next-drupal"

    const view = await drupal.getView<DrupalNode>("articles--promoted")
  • Logs or throws an error based on the throwJsonApiErrors flag.

    Parameters

    • error: Error

      The error to log or throw.

    Returns void

  • Throws an error if the response contains JSON:API errors.

    Parameters

    • response: Response

      The fetch response.

    • messagePrefix: string = ""

      The error message prefix.

    Returns Promise<void>

    The JSON:API errors.

  • Updates an existing resource of the specified type.

    Type Parameters

    Parameters

    Returns Promise<T>

    The updated resource.

    Update a node--page resource

    const page = await drupal.updateResource(
    "node--page",
    "a50ffee7-ba94-46c9-9705-f9f8f440db94",
    {
    data: {
    attributes: {
    title: "Updated Title",
    },
    },
    }
    )

    Using TypeScript with DrupalNode for a node entity type

    import { DrupalNode } from "next-drupal"

    const page = await drupal.updateResource<DrupalNode>(
    "node--page",
    "a50ffee7-ba94-46c9-9705-f9f8f440db94",
    {
    data: {
    attributes: {
    title: "Updated Title",
    },
    },
    }
    )
  • Validates the draft URL using the provided search parameters.

    Parameters

    • searchParams: URLSearchParams

      The search parameters.

    Returns Promise<Response>

    The validation response.