next-drupal
Version:
Helpers for Next.js + Drupal.
1,076 lines (1,055 loc) • 42.8 kB
text/typescript
export { J as JsonApiError, b as JsonApiErrors, a as JsonApiLinks } from './jsonapi-errors-kdi3GZQy.cjs';
import { a as NextDrupalBaseOptions, b as NextDrupalAuth, c as NextDrupalAuthUsernamePassword, d as NextDrupalAuthClientIdSecret, e as NextDrupalAuthAccessToken, N as NextDrupalBase, B as BaseUrl, J as JsonApiOptions, f as JsonApiWithNextFetchOptions, g as JsonApiWithCacheOptions, P as PathPrefix, h as JsonApiParams, i as JsonApiWithAuthOption, L as Locale, A as AccessToken } from './next-drupal-base--c-pwndh.cjs';
export { m as AccessTokenScope, E as EndpointSearchParams, o as FetchOptions, F as Fetcher, n as Logger, k as isAccessTokenAuth, j as isBasicAuth, l as isClientIdSecretAuth } from './next-drupal-base--c-pwndh.cjs';
import * as jsona_lib_JsonaTypes from 'jsona/lib/JsonaTypes';
import { TJsonaModel } from 'jsona/lib/JsonaTypes';
import { J as JsonApiResource, a as JsonApiCreateResourceBody, D as DrupalFile, b as JsonApiCreateFileResourceBody, c as JsonApiUpdateResourceBody, d as DrupalTranslatedPath, e as JsonApiResponse, f as DrupalMenuItem, g as DrupalView, h as DrupalMenuItemId, i as DrupalPathAlias } from './drupal-DDU-cwpz.cjs';
export { j as DrupalBlock, k as DrupalFileMeta, l as DrupalMedia, m as DrupalNode, n as DrupalParagraph, p as DrupalSearchApiFacet, o as DrupalSearchApiJsonApiResponse, q as DrupalTaxonomyTerm, r as DrupalUser, s as JsonApiResourceBodyRelationship, t as JsonApiResourceWithPath } from './drupal-DDU-cwpz.cjs';
import { GetStaticPropsContext, GetStaticPathsContext, GetStaticPathsResult, NextApiRequest, NextApiResponse } from 'next';
type NextDrupalOptions = NextDrupalBaseOptions & {
/**
* Override the default cache.
*
* * **Default value**: `node-cache`
* * **Required**: *No*
*
* [Documentation](https://next-drupal.org/docs/client/configuration#cache)
*/
cache?: DataCache;
/**
* Override the default data deserializer. You can use this to add your own JSON:API data deserializer.
*
* * **Default value**: `(new jsona()).deserialize`
* * **Required**: *No*
*
* [Documentation](https://next-drupal.org/docs/client/configuration#deserializer)
*/
deserializer?: JsonDeserializer;
/**
* If set to true, JSON:API errors are thrown in non-production environments. The errors are shown in the Next.js overlay.
*
* **Default value**: `true`
* **Required**: *No*
*
* [Documentation](https://next-drupal.org/docs/client/configuration#throwjsonapierrors)
*/
throwJsonApiErrors?: boolean;
/**
* By default, the resource endpoint will be based on the resource name. If you turn this off, a JSON:API request will retrieve the resource's endpoint url.
*
* * **Default value**: `true`
* * **Required**: *No*
*
* [Documentation](https://next-drupal.org/docs/client/configuration#usedefaultendpoints)
*/
useDefaultEndpoints?: boolean;
};
type JsonDeserializer = (body: Record<string, unknown>, options?: Record<string, unknown>) => TJsonaModel | TJsonaModel[];
interface DataCache {
get(key: any): Promise<unknown>;
set(key: any, value: any, ttl?: number): Promise<unknown>;
del?(keys: any): Promise<unknown>;
}
type DrupalClientOptions = NextDrupalOptions & {
/**
* Override the default data serializer. You can use this to add your own JSON:API data deserializer.
*
* * **Default value**: `jsona`
* * **Required**: *No*
*
* [Documentation](https://next-drupal.org/docs/client/configuration#serializer)
*/
serializer?: Serializer;
/**
* By default, the client will make a request to JSON:API to retrieve the endpoint url. You can turn this off and use the default endpoint based on the resource name.
*
* * **Default value**: `false`
* * **Required**: *No*
*
* [Documentation](https://next-drupal.org/docs/configuration#usedefaultresourcetypeentry)
*/
useDefaultResourceTypeEntry?: boolean;
};
type DrupalClientAuth = NextDrupalAuth;
type DrupalClientAuthUsernamePassword = NextDrupalAuthUsernamePassword;
type DrupalClientAuthClientIdSecret = NextDrupalAuthClientIdSecret;
type DrupalClientAuthAccessToken = NextDrupalAuthAccessToken;
interface Serializer {
deserialize: JsonDeserializer;
}
declare const DRAFT_DATA_COOKIE_NAME = "next_drupal_draft_data";
declare const DRAFT_MODE_COOKIE_NAME = "__prerender_bypass";
declare function useJsonaDeserialize(): (body: Parameters<JsonDeserializer>[0], options: Parameters<JsonDeserializer>[1]) => jsona_lib_JsonaTypes.TJsonaModel | jsona_lib_JsonaTypes.TJsonaModel[];
/**
* The NextDrupal class extends the NextDrupalBase class and provides methods
* for interacting with a Drupal backend.
*/
declare class NextDrupal extends NextDrupalBase {
cache?: NextDrupalOptions["cache"];
deserializer: JsonDeserializer;
throwJsonApiErrors: boolean;
useDefaultEndpoints: boolean;
/**
* Instantiates a new NextDrupal.
*
* const client = new NextDrupal(baseUrl)
*
* @param {baseUrl} baseUrl The baseUrl of your Drupal site. Do not add the /jsonapi suffix.
* @param {options} options Options for NextDrupal.
*/
constructor(baseUrl: BaseUrl, options?: NextDrupalOptions);
/**
* Creates a new resource of the specified type.
*
* @param {string} type The type of the resource. Example: `node--article`, `taxonomy_term--tags`, or `block_content--basic`.
* @param {JsonApiCreateResourceBody} body The body payload with data.
* @param {JsonApiOptions & JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<T>} The created resource.
* @example
* 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",
* },
* },
* },
* })
* ```
*/
createResource<T extends JsonApiResource>(type: string, body: JsonApiCreateResourceBody, options?: JsonApiOptions & JsonApiWithNextFetchOptions): Promise<T>;
/**
* Creates a new file resource for the specified media type.
*
* @param {string} type The type of the resource. In most cases this is `file--file`.
* @param {JsonApiCreateFileResourceBody} body 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
* @param {JsonApiOptions} options Options for the request.
* @returns {Promise<T>} The created file resource.
* @example
* Create a file resource for a media--image entity
* ```ts
* 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:
* ```ts
* 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,
* },
* },
* },
* },
* })
* ```
*/
createFileResource<T = DrupalFile>(type: string, body: JsonApiCreateFileResourceBody, options?: JsonApiOptions & JsonApiWithNextFetchOptions): Promise<T>;
/**
* Updates an existing resource of the specified type.
*
* @param {string} type The type of the resource. Example: `node--article`, `taxonomy_term--tags`, or `block_content--basic`.
* @param {string} uuid The resource id. Example: `a50ffee7-ba94-46c9-9705-f9f8f440db94`.
* @param {JsonApiUpdateResourceBody} body The body payload with data.
* @param {JsonApiOptions & JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<T>} The updated resource.
* @example
* Update a node--page resource
* ```ts
* 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
* ```ts
* import { DrupalNode } from "next-drupal"
*
* const page = await drupal.updateResource<DrupalNode>(
* "node--page",
* "a50ffee7-ba94-46c9-9705-f9f8f440db94",
* {
* data: {
* attributes: {
* title: "Updated Title",
* },
* },
* }
* )
* ```
*/
updateResource<T extends JsonApiResource>(type: string, uuid: string, body: JsonApiUpdateResourceBody, options?: JsonApiOptions & JsonApiWithNextFetchOptions): Promise<T>;
/**
* Deletes an existing resource of the specified type.
*
* @param {string} type The type of the resource. Example: `node--article`, `taxonomy_term--tags`, or `block_content--basic`.
* @param {string} uuid The resource id. Example: `a50ffee7-ba94-46c9-9705-f9f8f440db94`.
* @param {JsonApiOptions & JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<boolean>} True if the resource was deleted, false otherwise.
* @example
* Delete a node--page resource
* ```ts
* const isDeleted = await drupal.deleteResource(
* "node--page",
* "a50ffee7-ba94-46c9-9705-f9f8f440db94"
* )
* ```
*/
deleteResource(type: string, uuid: string, options?: JsonApiOptions & JsonApiWithNextFetchOptions): Promise<boolean>;
/**
* Fetches a resource of the specified type by its UUID.
*
* @param {string} type The resource type. Example: `node--article`, `taxonomy_term--tags`, or `block_content--basic`.
* @param {string} uuid The id of the resource. Example: `15486935-24bf-4be7-b858-a5b2de78d09d`.
* @param {JsonApiOptions & JsonApiWithCacheOptions & JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<T>} The fetched resource.
* @examples
* Get a page by uuid.
* ```ts
* const node = await drupal.getResource(
* "node--page",
* "07464e9f-9221-4a4f-b7f2-01389408e6c8"
* )
* ```
* Get the es translation for a page by uuid.
* ```ts
* const node = await drupal.getResource(
* "node--page",
* "07464e9f-9221-4a4f-b7f2-01389408e6c8",
* {
* locale: "es",
* defaultLocale: "en",
* }
* )
* ```
* Get the raw JSON:API response.
* ```ts
* const { data, meta, links } = await drupal.getResource(
* "node--page",
* "07464e9f-9221-4a4f-b7f2-01389408e6c8",
* {
* deserialize: false,
* }
* )
* ```
* Get a node--article resource using cache.
* ```ts
* 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.
* ```ts
* const node = await drupal.getResource(
* "node--page",
* "07464e9f-9221-4a4f-b7f2-01389408e6c8",
* { next: { revalidate: 3600 } }
* )
* ```
* Get a page resource with tag-based revalidation.
* ```ts
* 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.
* ```ts
* 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.
* ```ts
* import { DrupalTaxonomyTerm } from "next-drupal"
*
* const term = await drupal.getResource<DrupalTaxonomyTerm>(
* "taxonomy_term--tags",
* "7b47d7cc-9b1b-4867-a909-75dc1d61dfd3"
* )
* ```
*/
getResource<T extends JsonApiResource>(type: string, uuid: string, options?: JsonApiOptions & JsonApiWithCacheOptions & JsonApiWithNextFetchOptions): Promise<T>;
/**
* Fetches a resource of the specified type by its path.
*
* @param {string} path The path of the resource. Example: `/blog/slug-for-article`.
* @param { { isVersionable?: boolean } & JsonApiOptions & JsonApiWithNextFetchOptions} options 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.
* @requires Decoupled Router module
* @example
* 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"
* )
* ```
*/
getResourceByPath<T extends JsonApiResource>(path: string, options?: {
isVersionable?: boolean;
} & JsonApiOptions & JsonApiWithNextFetchOptions): Promise<T>;
/**
* Fetches a collection of resources of the specified type.
*
* @param {string} type The type of the resources. Example: `node--article` or `user--user`.
* @param {JsonApiOptions & JsonApiWithNextFetchOptions} options Options for the request.
* - deserialize: Set to false to return the raw JSON:API response
* @returns {Promise<T>} The fetched collection of resources.
* @example
* 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")
* ```
*/
getResourceCollection<T = JsonApiResource[]>(type: string, options?: {
deserialize?: boolean;
} & JsonApiOptions & JsonApiWithNextFetchOptions): Promise<T>;
/**
* Fetches path segments for a collection of resources of the specified types.
*
* @param {string | string[]} types The types of the resources.
* @param {JsonApiOptions & JsonApiWithAuthOption & JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<{ path: string, type: string, locale: Locale, segments: string[] }[]>} The fetched path segments.
*/
getResourceCollectionPathSegments(types: string | string[], options?: {
pathPrefix?: PathPrefix;
params?: JsonApiParams;
} & JsonApiWithAuthOption & JsonApiWithNextFetchOptions & ({
locales: Locale[];
defaultLocale: Locale;
} | {
locales?: undefined;
defaultLocale?: never;
})): Promise<{
path: string;
type: string;
locale: Locale;
segments: string[];
}[]>;
/**
* Translates a path to a DrupalTranslatedPath object.
*
* @param {string} path The resource path. Example: `/blog/slug-for-article`.
* @param {JsonApiWithAuthOption & JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<DrupalTranslatedPath | null>} The translated path.
* @requires Decoupled Router module
* @example
* Get info about a `/blog/slug-for-article` path
* ```ts
* const path = await drupal.translatePath("/blog/slug-for-article")
* ```
*/
translatePath(path: string, options?: JsonApiWithAuthOption & JsonApiWithNextFetchOptions): Promise<DrupalTranslatedPath | null>;
/**
* Fetches the JSON:API index.
*
* @param {Locale} locale The locale for the request.
* @param {JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<JsonApiResponse>} The JSON:API index.
*/
getIndex(locale?: Locale, options?: JsonApiWithNextFetchOptions): Promise<JsonApiResponse>;
/**
* Builds an endpoint URL for the specified parameters.
*
* @param {Parameters<NextDrupalBase["buildEndpoint"]>[0] & { resourceType?: string }} params The parameters for the endpoint.
* @returns {Promise<string>} The built endpoint URL.
*/
buildEndpoint({ locale, resourceType, path, searchParams, }?: Parameters<NextDrupalBase["buildEndpoint"]>[0] & {
resourceType?: string;
}): Promise<string>;
/**
* Fetches the endpoint URL for the specified resource type.
*
* @param {string} type The type of the resource.
* @param {Locale} locale The locale for the request.
* @returns {Promise<URL>} The fetched endpoint URL.
*/
fetchResourceEndpoint(type: string, locale?: Locale): Promise<URL>;
/**
* Fetches a menu by its name.
*
* @param {string} menuName The name of the menu. Example: `main` or `footer`.
* @param {JsonApiOptions & JsonApiWithCacheOptions & JsonApiWithNextFetchOptions} options Options for the request.
* @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
* @requires JSON:API Menu Items module
* @example
* Get the `main` menu
* ```ts
* const { menu, items } = await drupal.getMenu("main")
* ```
*
* Get the `main` menu using cache
* ```ts
* const menu = await drupal.getMenu("main", {
* withCache: true,
* cacheKey: "menu--main",
* })
* ```
*/
getMenu<T = DrupalMenuItem>(menuName: string, options?: JsonApiOptions & JsonApiWithCacheOptions & JsonApiWithNextFetchOptions): Promise<{
items: T[];
tree: T[];
}>;
/**
* Fetches a view by its name.
*
* @param {string} name The name of the view and the display id. Example: `articles--promoted`.
* @param {JsonApiOptions & JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<DrupalView<T>>} The fetched view.
* @requires JSON:API Views module
* @example
* Get a view named `articles` and display id `promoted`
* ```ts
* const view = await drupal.getView("articles--promoted")
* ```
*
* Using sparse fieldsets to only fetch the title and body fields
* ```ts
* const view = await drupal.getView("articles--promoted", {
* params: {
* fields: {
* "node--article": "title,body",
* },
* },
* })
* ```
*
* Using TypeScript with DrupalNode for a node entity type
* ```ts
* import { DrupalNode } from "next-drupal"
*
* const view = await drupal.getView<DrupalNode>("articles--promoted")
* ```
*/
getView<T = JsonApiResource>(name: string, options?: JsonApiOptions & JsonApiWithNextFetchOptions): Promise<DrupalView<T>>;
/**
* Fetches a search index by its name.
*
* @param {string} name The name of the search index.
* @param {JsonApiOptions & JsonApiWithNextFetchOptions} options Options for the request.
* @returns {Promise<T>} The fetched search index.
* @requires JSON:API Search API module
* @example
* Get search results from an index named `articles`
* ```ts
* const results = await drupal.getSearchIndex("articles")
* ```
*
* Using TypeScript with DrupalNode for a node entity type
* ```ts
* import { DrupalNode } from "next-drupal"
*
* const results = await drupal.getSearchIndex<DrupalNode>("articles")
* ```
*/
getSearchIndex<T = JsonApiResource[]>(name: string, options?: JsonApiOptions & JsonApiWithNextFetchOptions): Promise<T>;
/**
* Deserializes the response body.
*
* @param {any} body The response body.
* @param {any} options Options for deserialization.
* @returns {any} The deserialized response body.
* @remarks
* To provide your own custom deserializer, see the serializer docs.
* @example
* ```ts
* 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)
* ```
*/
deserialize(body: any, options?: any): jsona_lib_JsonaTypes.TJsonaModel | jsona_lib_JsonaTypes.TJsonaModel[];
/**
* Logs or throws an error based on the throwJsonApiErrors flag.
*
* @param {Error} error The error to log or throw.
*/
logOrThrowError(error: Error): void;
}
declare class DrupalMenuTree<T extends {
id: DrupalMenuItemId;
parent: DrupalMenuItemId;
items?: T[];
} = DrupalMenuItem> extends Array {
parentId: DrupalMenuItemId;
depth: number;
constructor(menuItems: T[], parentId?: DrupalMenuItemId, depth?: number);
build(menuItems: T[], parentId: DrupalMenuItemId): void;
}
/**
* The NextDrupalPages class extends the NextDrupal class and provides methods
* for interacting with a Drupal backend in the context of Next.js pages.
*/
declare class NextDrupalPages extends NextDrupal {
private serializer;
/**
* Instantiates a new NextDrupalPages.
*
* const client = new NextDrupalPages(baseUrl)
*
* @param {baseUrl} baseUrl The baseUrl of your Drupal site. Do not add the /jsonapi suffix.
* @param {options} options Options for the client. See Experiment_DrupalClientOptions.
*/
constructor(baseUrl: BaseUrl, options?: DrupalClientOptions);
/**
* Get the JSON:API entry for a resource type.
*
* @param {string} resourceType The resource type. Example: `node--article`.
* @param {Locale} locale Optional. The locale to fetch the index. Example: `es` or `fr`.
* @returns {Promise<string>} The entry point URL.
* @remarks
* By default, when retrieving resources in `getResource` or `getResourceCollection`,
* the `DrupalClient` make a request to Drupal to fetch the JSON:API resource entry.
*
* Example: if you provide `node--article`, `DrupalClient` will make a request to
* `http://example.com/jsonapi/node/article`.
*
* If you would like to infer the entry from the resource type, use the useDefaultResourceTypeEntry option:
* ```ts
* const drupal = new DrupalClient(process.env.NEXT_PUBLIC_DRUPAL_BASE_URL, {
* useDefaultResourceTypeEntry: true,
* })
* ```
* @example
* ```ts
* // https://example.com/jsonapi/node/article
* const url = await drupal.getEntryForResourceType(`node--article`)
* ```
*/
getEntryForResourceType(resourceType: string, locale?: Locale): Promise<string>;
buildMenuTree(links: DrupalMenuItem[], parent?: DrupalMenuItemId): DrupalMenuTree<DrupalMenuItem>;
/**
* Gets a resource from the context.
*
* @param {string | DrupalTranslatedPath} input Either a resource type (e.g. "node--article") or a translated path from translatePath().
* @param {GetStaticPropsContext} context The Next.js context from getStaticProps.
* @param {Object} options Options for the request.
* @param {PathPrefix} [options.pathPrefix] The path prefix to use for the request (defaults to "/").
* @param {boolean} [options.isVersionable] Whether the resource is versionable (defaults to false for all entity types except nodes).
* @returns {Promise<T>} The fetched resource.
* @remarks
* The localized resource will be fetched based on the `locale` and `defaultLocale` values from `context`.
*
* If you pass in a `DrupalTranslatedPath` for input, `getResourceFromContext` will take the `type` and `id` from the path and make a `getResource` call to Drupal:
* ```ts
* export async function getStaticProps(context) {
* const path = await drupal.translatePathFromContext(context)
*
* const node = await drupal.getResourceFromContext(path, context)
*
* return {
* props: {
* node,
* },
* }
* }
* ```
*
* If you pass in a `string` input, such as `node--article`, `getResourceFromContext` will make a subrequest call to Drupal to translate the path and then fetch the resource.
* You will need both the [Subrequests](https://drupal.org/project/subrequests) and [Decoupled Router](https://drupal.org/project/decoupled_router) modules:
* ```ts
* export async function getStaticProps(context) {
* const node = await drupal.getResourceFromContext("node--article", context)
*
* return {
* props: {
* node,
* },
* }
* }
* ```
* @examples
* Fetch a resource from context.
* ```ts title=pages/[[...slug]].tsx
* export async function getStaticProps(context) {
* const node = await drupal.getResourceFromContext("node--page", context)
*
* return {
* props: {
* node,
* },
* }
* }
* ```
* Fetch a resource from context in a sub directory.
* ```ts title=pages/articles/[[...slug]].tsx
* export async function getStaticProps(context) {
* const node = await drupal.getResourceFromContext("node--page", context, {
* pathPrefix: "/articles",
* })
*
* return {
* props: {
* node,
* },
* }
* }
* ```
* Using DrupalNode type:
* ```ts
* import { DrupalNode } from "next-drupal"
*
* const node = await drupal.getResourceFromContext<DrupalNode>(
* "node--page",
* context
* )
* ```
* Using DrupalTaxonomyTerm type:
* ```ts
* import { DrupalTaxonomyTerm } from "next-drupal"
*
* const term = await drupal.getResourceFromContext<DrupalTaxonomyTerm>(
* "taxonomy_term--tags",
* context
* )
* ```
* @see {@link https://next-drupal.org/docs/typescript} for more built-in types.
*/
getResourceFromContext<T extends JsonApiResource>(input: string | DrupalTranslatedPath, context: GetStaticPropsContext, options?: {
pathPrefix?: PathPrefix;
isVersionable?: boolean;
} & JsonApiOptions): Promise<T>;
/**
* Gets a collection of resources from the context.
*
* @param {string} type The type of the resources. Example: `node--article` or `user--user`.
* @param {GetStaticPropsContext} context The static props context from getStaticProps or getServerSideProps.
* @param {Object} options Options for the request.
* - deserialize: Set to false to return the raw JSON:API response
* @returns {Promise<T>} The fetched collection of resources.
* @remarks
* The localized resources will be fetched based on the `locale` and `defaultLocale` values from `context`.
* @example
* Get all articles from context
* ```
* export async function getStaticProps(context) {
* const articles = await drupal.getResourceCollectionFromContext(
* "node--article",
* context
* )
*
* return {
* props: {
* articles,
* },
* }
* }
* ```
* Using TypeScript with DrupalNode for a node entity type
* ```
* import { DrupalNode } from "next-drupal"
* const nodes = await drupal.getResourceCollectionFromContext<DrupalNode[]>(
* "node--article",
* context
* )
* ```
*/
getResourceCollectionFromContext<T = JsonApiResource[]>(type: string, context: GetStaticPropsContext, options?: {
deserialize?: boolean;
} & JsonApiOptions): Promise<T>;
/**
* Gets a search index from the context.
*
* @param {string} name The name of the search index.
* @param {GetStaticPropsContext} context The static props context.
* @param {Object} options Options for the request.
* @returns {Promise<T>} The fetched search index.
*/
getSearchIndexFromContext<T = JsonApiResource[]>(name: string, context: GetStaticPropsContext, options?: JsonApiOptions): Promise<T>;
/**
* Translates a path from the context.
*
* @param {GetStaticPropsContext} context The context from `getStaticProps` or `getServerSideProps`.
* @param {Object} options Options for the request.
* @returns {Promise<DrupalTranslatedPath | null>} The translated path.
* @requires Decoupled Router module
* @example
* Get info about a path from `getStaticProps` context
* ```ts
* export async function getStaticProps(context) {
* const path = await drupal.translatePathFromContext(context)
* }
* ```
*/
translatePathFromContext(context: GetStaticPropsContext, options?: {
pathPrefix?: PathPrefix;
} & JsonApiWithAuthOption): Promise<DrupalTranslatedPath | null>;
/**
* Return the path (slug) from getStaticProps or getServerSideProps context.
*
* @param {GetStaticPropsContext} context The context from `getStaticProps` or `getServerSideProps`.
* @param {Object} options Options for the request.
* @returns {string} The constructed path.
* @example
* Get the path (slug) from `getStaticProps` context
* ```ts
* export async function getStaticProps(context) {
* const slug = await drupal.getPathFromContext(context)
* }
* ```
*/
getPathFromContext(context: GetStaticPropsContext, options?: {
pathPrefix?: PathPrefix;
}): string;
getPathsFromContext: (types: string | string[], context: GetStaticPathsContext, options?: {
params?: JsonApiParams;
pathPrefix?: PathPrefix;
} & JsonApiWithAuthOption) => Promise<GetStaticPathsResult<{
slug: string[];
}>["paths"]>;
/**
* Gets static paths from the context.
*
* @param {string | string[]} types The resource types. Example: `node--article` or `["taxonomy_term--tags", "user--user"]`.
* @param {GetStaticPathsContext} context The context from `getStaticPaths`.
* @param {object} options Options for the request.
* @returns {Promise<GetStaticPathsResult<{ slug: string[] }>["paths"]>} The static paths.
* @example
* Return static paths for `node--page` resources
* ```ts
* export async function getStaticPaths(context) {
* return {
* paths: await drupal.getStaticPathsFromContext("node--page", context),
* fallback: "blocking",
* }
* }
* ```
*
* Return static paths for `node--page` and `node--article` resources
* ```ts
* export async function getStaticPaths(context) {
* return {
* paths: await drupal.getStaticPathsFromContext(
* ["node--page", "node--article"],
* context
* ),
* fallback: "blocking",
* }
* }
* ```
*/
getStaticPathsFromContext(types: string | string[], context: GetStaticPathsContext, options?: {
params?: JsonApiParams;
pathPrefix?: PathPrefix;
} & JsonApiWithAuthOption): Promise<GetStaticPathsResult<{
slug: string[];
}>["paths"]>;
/**
* Builds static paths from resources.
*
* @param {Object[]} resources The resources.
* @param {Object} options Options for the request.
* @returns {Object[]} The built static paths.
*/
buildStaticPathsFromResources(resources: {
path: DrupalPathAlias;
}[], options?: {
pathPrefix?: PathPrefix;
locale?: Locale;
}): {
params: {
slug: string[];
};
}[];
/**
* Builds static paths parameters from paths.
*
* @param {string[]} paths The paths.
* @param {Object} options Options for the request.
* @returns {Object[]} The built static paths parameters.
*/
buildStaticPathsParamsFromPaths(paths: string[], options?: {
pathPrefix?: PathPrefix;
locale?: Locale;
}): {
params: {
slug: string[];
};
}[];
/**
* Handle preview mode for resources.
*
* @param {NextApiRequest} request The `request` from an API route.
* @param {NextApiResponse} response The `response` from an API route.
* @param {Object} options Options for the request.
* @returns {Promise<void>}
* @remarks
* The `preview` method should be called in an API route.
* Remember to set a `previewSecret` on the client.
* ```ts
* // lib/drupal.ts
* export const drupal = new DrupalClient(
* process.env.NEXT_PUBLIC_DRUPAL_BASE_URL,
* {
* previewSecret: process.env.DRUPAL_PREVIEW_SECRET,
* }
* )
* ```
* @example
* ```ts
* // pages/api/preview.ts
* import { drupal } from "lib/drupal"
*
* export default async function handler(req, res) {
* return await drupal.preview(req, res)
* }
* ```
*/
preview(request: NextApiRequest, response: NextApiResponse, options?: Parameters<NextApiResponse["setDraftMode"]>[0]): Promise<void | NextApiResponse>;
/**
* Disables preview mode.
*
* @param {NextApiRequest} request The API request.
* @param {NextApiResponse} response The API response.
*/
previewDisable(request: NextApiRequest, response: NextApiResponse): Promise<void>;
/**
* Gets the authentication configuration from the context and options.
*
* @param {GetStaticPropsContext} context The static props context.
* @param {JsonApiWithAuthOption} options Options for the request.
* @returns {NextDrupalAuth} The authentication configuration.
*/
getAuthFromContextAndOptions(context: GetStaticPropsContext, options: JsonApiWithAuthOption): boolean | NextDrupalAuth;
}
/** @deprecated */
declare function getAccessToken(): Promise<AccessToken>;
type JsonApiWithLocaleOptions = Omit<JsonApiOptions, "withAuth">;
type DrupalMenuLinkContent = DrupalMenuItem;
declare function getMenu<T extends DrupalMenuItem>(name: string, options?: {
deserialize?: boolean;
accessToken?: AccessToken;
} & JsonApiWithLocaleOptions): Promise<{
items: T[];
tree: T[];
}>;
declare function getPathsFromContext(types: string | string[], context: GetStaticPathsContext, options?: {
params?: JsonApiParams;
accessToken?: AccessToken;
}): Promise<GetStaticPathsResult["paths"]>;
declare function getResourceCollection<T = JsonApiResource[]>(type: string, options?: {
deserialize?: boolean;
accessToken?: AccessToken;
} & JsonApiWithLocaleOptions): Promise<T>;
declare function getResourceCollectionFromContext<T = JsonApiResource[]>(type: string, context: GetStaticPropsContext, options?: {
deserialize?: boolean;
params?: JsonApiParams;
}): Promise<T>;
interface PreviewOptions {
errorMessages?: {
secret?: string;
slug?: string;
};
}
declare function DrupalPreview(options?: PreviewOptions): (request: any, response: any) => Promise<void | NextApiResponse>;
declare function PreviewHandler(request?: NextApiRequest, response?: NextApiResponse, options?: PreviewOptions): Promise<void | NextApiResponse>;
type GetResourcePreviewUrlOptions = JsonApiWithLocaleOptions & {
isVersionable?: boolean;
};
declare function getResourcePreviewUrl(slug: string, options?: GetResourcePreviewUrlOptions): Promise<any>;
declare function getResourceTypeFromContext(context: GetStaticPropsContext, options?: {
accessToken?: AccessToken;
prefix?: string;
}): Promise<string>;
declare function getResourceFromContext<T extends JsonApiResource>(type: string, context: GetStaticPropsContext, options?: {
prefix?: string;
deserialize?: boolean;
params?: JsonApiParams;
accessToken?: AccessToken;
isVersionable?: boolean;
}): Promise<T>;
declare function getResourceByPath<T extends JsonApiResource>(path: string, options?: {
accessToken?: AccessToken;
deserialize?: boolean;
isVersionable?: boolean;
} & JsonApiWithLocaleOptions): Promise<T>;
declare function getResource<T extends JsonApiResource>(type: string, uuid: string, options?: {
accessToken?: AccessToken;
deserialize?: boolean;
} & JsonApiWithLocaleOptions): Promise<T>;
declare function getSearchIndex<T = JsonApiResource[]>(name: string, options?: {
deserialize?: boolean;
accessToken?: AccessToken;
} & JsonApiWithLocaleOptions): Promise<T>;
declare function getSearchIndexFromContext<T = JsonApiResource[]>(name: string, context: GetStaticPropsContext, options?: {
deserialize?: boolean;
accessToken?: AccessToken;
} & JsonApiWithLocaleOptions): Promise<T>;
declare function getView<T>(name: string, options?: {
deserialize?: boolean;
accessToken?: AccessToken;
} & JsonApiWithLocaleOptions): Promise<{
results: T;
meta: Record<string, any>;
links: {
[key in "next" | "prev" | "self"]?: {
href: "string";
};
};
}>;
declare function translatePath(path: string, options?: {
accessToken?: AccessToken;
}): Promise<DrupalTranslatedPath>;
declare function translatePathFromContext(context: GetStaticPropsContext, options?: {
accessToken?: AccessToken;
prefix?: string;
}): Promise<DrupalTranslatedPath>;
declare function deserialize(body: any, options?: any): jsona_lib_JsonaTypes.TJsonaModel | jsona_lib_JsonaTypes.TJsonaModel[];
declare function getJsonApiPathForResourceType(type: string, locale?: Locale): Promise<string>;
declare function getJsonApiIndex(locale?: Locale, options?: {
accessToken?: AccessToken;
}): Promise<{
links: {
[type: string]: {
href: string;
};
};
}>;
declare function buildUrl(path: string, params?: string | Record<string, string> | URLSearchParams): URL;
declare function syncDrupalPreviewRoutes(path: any): void;
declare const DrupalClient: typeof NextDrupalPages;
export { AccessToken, BaseUrl, DRAFT_DATA_COOKIE_NAME, DRAFT_MODE_COOKIE_NAME, type DataCache, DrupalClient, type DrupalClientAuth, type DrupalClientAuthAccessToken, type DrupalClientAuthClientIdSecret, type DrupalClientAuthUsernamePassword, type DrupalClientOptions, DrupalFile, DrupalMenuItem, DrupalMenuItemId, type DrupalMenuLinkContent, DrupalPathAlias, DrupalPreview, DrupalTranslatedPath, DrupalView, JsonApiCreateFileResourceBody, JsonApiCreateResourceBody, JsonApiOptions, JsonApiParams, JsonApiResource, JsonApiResponse, JsonApiUpdateResourceBody, JsonApiWithAuthOption, JsonApiWithCacheOptions, type JsonApiWithLocaleOptions, JsonApiWithNextFetchOptions, type JsonDeserializer, Locale, NextDrupal, NextDrupalAuth, NextDrupalAuthAccessToken, NextDrupalAuthClientIdSecret, NextDrupalAuthUsernamePassword, NextDrupalBase, NextDrupalBaseOptions, type NextDrupalOptions, NextDrupalPages, PathPrefix, PreviewHandler, type Serializer, buildUrl, deserialize, getAccessToken, getJsonApiIndex, getJsonApiPathForResourceType, getMenu, getPathsFromContext, getResource, getResourceByPath, getResourceCollection, getResourceCollectionFromContext, getResourceFromContext, getResourcePreviewUrl, getResourceTypeFromContext, getSearchIndex, getSearchIndexFromContext, getView, syncDrupalPreviewRoutes, translatePath, translatePathFromContext, useJsonaDeserialize };