JSON:API Client class provides functionality specific to JSON:API server.

See

  • ApiClientOptions
  • BaseUrl

Hierarchy

  • ApiClient
    • JsonApiClient

Constructors

  • Creates a new instance of the JsonApiClient.

    Parameters

    • baseUrl: string

      The base URL of the API. BaseUrl

    • Optional options: ApiClientOptions

      (Optional) Additional options for configuring the API client. JsonApiClientOptions

    Returns JsonApiClient

Properties

#private: any
apiPrefix: undefined | string

ApiClientOptions.apiPrefix

authentication: undefined | Authentication

ApiClientOptions.authentication

baseUrl: string

BaseUrl

cache: undefined | Cache

ApiClientOptions.cache

customFetch: undefined | ((input, init?) => Promise<Response>)

ApiClientOptions.customFetch

Type declaration

debug: undefined | boolean

ApiClientOptions.debug

defaultLocale: undefined | string

ApiClientOptions.defaultLocale

logger: undefined | {
    debug: undefined | LogMethod;
    error: undefined | LogMethod;
    http: undefined | LogMethod;
    info: undefined | LogMethod;
    silly: undefined | LogMethod;
    verbose: undefined | LogMethod;
    warn: undefined | LogMethod;
}

ApiClientOptions.logger

Type declaration

  • debug: undefined | LogMethod
  • error: undefined | LogMethod
  • http: undefined | LogMethod
  • info: undefined | LogMethod
  • silly: undefined | LogMethod
  • verbose: undefined | LogMethod
  • warn: undefined | LogMethod
router: DecoupledRouterClient

link DecoupledRouterClient

serializer: undefined | Serializer

ApiClientOptions.serializer

Methods

  • Adds an authorization header to the provided RequestInit options if authentication of type "Basic" is configured. If the authentication type is "OAuth", it will fetch a new access token or use the stored access token if it exists and is still valid. if the authentication type is "Custom", it will use the provided value.

    Parameters

    • options: undefined | RequestInit

      The RequestInit options to which the authorization header should be added.

    Returns Promise<RequestInit>

    The updated RequestInit options with the authorization header, if applicable.

  • Create a resource of the specified type using the provided body.

    Parameters

    • type: `${string}--${string}`

      The type of the entity with bundle information.

    • body: string | object

      The body of the request.

    Returns Promise<Response>

    A Promise that resolves to a Response object.

    Remarks

    This method initiates the creation of a resource by sending a POST request to the API.

    Example

    const response = await createResource("node--page", `{
    "data": {
    "type": "node--page",
    "attributes": {
    "title": "My custom title",
    "body": {
    "value": "Custom value",
    "format": "plain_text"
    }
    }
    }
    }`);
  • Generates an endpoint URL based on the provided parameters.

    Parameters

    Returns string

    The endpoint URL as a string.

    Params

    params - The parameters to use for creating the URL. EndpointUrlSegments

  • Deletes a resource of the specified type using the provided resource ID.

    Parameters

    • type: `${string}--${string}`

      The type of the entity with bundle information.

    • resourceId: string

      The ID of the resource to be deleted.

    Returns Promise<boolean>

    A boolean indicating whether the resource deletion was successful.

    Remarks

    This method initiates the deletion of a resource by sending a DELETE request to the API. If the deletion is successful (HTTP status 204), it returns true; otherwise, it returns false.

    Example

    const success = await deleteResource("node--page", "7cbb8b73-8bcb-4008-874e-2bd496bd419d");
    if (success) {
    console.log("Resource deleted successfully.");
    } else {
    console.error("Failed to delete resource.");
    }
  • Uses customFetch if it is set, otherwise uses the default fetch

    Parameters

    • input: RequestInfo | URL

      RequestInfo

    • Optional init: RequestInit

      RequestInit

    Returns Promise<FetchReturn>

    a response wrapped in a promise

  • Fetch the OAuth token from the BaseUrl

    Parameters

    • __namedParameters: {
          clientId: string;
          clientSecret: string;
      }
      • clientId: string
      • clientSecret: string

    Returns Promise<OAuthTokenResponse>

    Param0

    the Client ID

    Param1

    the Client secret

  • Retrieves a cached response from the cache.

    Type Parameters

    • T

    Parameters

    • cacheKey: string

      The cache key to use for retrieving the cached response.

    Returns Promise<null | NonNullable<Awaited<T>>>

    A promise wrapping the cached response as a generic type.

  • Retrieves a collection of data of a specific entity type and bundle from the JSON:API.

    Type Parameters

    • T

    Parameters

    • type: `${string}--${string}`

      The type of resource to retrieve, in the format "entityType--bundle". For example, "node--page". EntityTypeWithBundle

    • Optional options: GetOptions

      (Optional) Additional options for customizing the request. GetOptions

    Returns Promise<any>

    A Promise that resolves to the JSON data of the requested resource.

    Example

    Using JSONAPI.CollectionResourceDoc type from the jsonapi-typescript package

    const collection = await jsonApiClient.get<JSONAPI.CollectionResourceDoc<string, Recipe>>("node--recipe");
    
  • Retrieves data for a resource by ID of a specific entity type and bundle from the JSON:API.

    Type Parameters

    • T

    Parameters

    • type: `${string}--${string}`

      The type of resource to retrieve, in the format "entityType--bundle". For example, "node--page". EntityTypeWithBundle

    • resourceId: string

      The ID of the individual resource to retrieve.

    • Optional options: GetOptions

      (Optional) Additional options for customizing the request. GetOptions

    Returns Promise<any>

    A Promise that resolves to the JSON data of the requested resource.

    Example

    Using JSONAPI.CollectionResourceDoc type from the jsonapi-typescript package

    const collection = await jsonApiClient.get<JSONAPI.CollectionResourceDoc<string, Recipe>>("node--recipe");
    
  • Attempts to resolve a path to a resource and then fetches the resolved resource.

    Parameters

    • path: string

      The path to resolve and fetch.

    • Optional options: GetOptions

      (Optional) Additional options for customizing the request. GetOptions

    Returns Promise<any>

    • A promise that resolves to either the JSON data of the requested resource or an UnResolvedPath if the path could not be resolved.

    Example

    const article = await jsonApiClient.getResourceByPath("/articles/give-it-a-go-and-grow-your-own-herbs");
    
  • Calls the appropriate logger method based on level

    Parameters

    • level: LogLevels

      level based on npm log levels

    • message: string

      the message to log

    Returns void

  • Updates a resource of the specified type using the provided resource ID.

    Parameters

    • type: `${string}--${string}`

      The type of the entity with bundle information.

    • resourceId: string

      The ID of the resource to be updated.

    • body: string | object

      The body of the request.

    Returns Promise<Response>

    A Promise that resolves to a Response object.

    Remarks

    This method initiates the update of a resource by sending a PATCH request to the API.

    Example

    const response = await updateResource("node--page", "7cbb8b73-8bcb-4008-874e-2bd496bd419d", `{
    "data": {
    "type": "node--page",
    "id": "11fc449b-aca0-4b74-bc3b-677da021f1d7",
    "attributes": {
    "drupal_internal__nid": 2,
    "drupal_internal__vid": 3,
    "langcode": "en",
    "revision_log": null,
    "status": true,
    "title": "test 2"
    }
    }
    }`);
  • Generates a cache key based on the provided parameters.

    Parameters

    Returns Promise<string>

    A promise wrapping the generated cache key as a string.

    Params

    params - The parameters to use for generating the cache key. EndpointUrlSegments

    Example

    // Generate a cache key with entityTypeId and bundleId only
    const key1 = await MyClass.createCacheKey('entity1', 'bundle1');
    // key1: 'entity1--bundle1'

    Example

    // Generate a cache key with entityTypeId, bundleId, localeSegment, and queryString
    const key2 = await MyClass.createCacheKey('entity2', 'bundle2', 'en-US', 'param1=value1&param2=value2');
    // key2: 'en-US--entity2--bundle2--<sha256_hash_of_query_string>'
  • Parameters

    • type: `${string}--${string}`

    Returns {
        bundleId: string;
        entityTypeId: string;
    }

    • bundleId: string
    • entityTypeId: string

Generated using TypeDoc