Skip to content

The core module, DruxtClient, DruxtStore and the DruxtModule base component.

DruxtClient

View source on GitHub

DruxtClient

The Druxt JSON:API client.

Communicates with the Drupal JSON:API to fetch, create and update resources.

Kind: global class
See: Druxt module guide


new DruxtClient(baseUrl, [options])

DruxtClient constructor.

  • Validates module options.
  • Sets up Axios instance.
  • Sets up options.
ParamTypeDescription
baseUrlstringThe Drupal base URL.
[options]DruxtClientOptionsThe DruxtClient options object.

Example

const DruxtClient = require('druxt').DruxtClient
const druxt = new DruxtClient('https://api.umami.demo.druxtjs.org', {})

.axios : object

The Axios instance.

Kind: instance property of DruxtClient
See: https://github.com/axios/axios#instance-methods


.index : object

JSON:API Index.

Shared between clients on the same Axios instance with the same base URL, endpoint and resource config.

Kind: instance property of DruxtClient


.cacheGeneration : number

Moves on each time clearCache() runs, so caches keyed by this client know to empty.

Kind: instance property of DruxtClient


.clearCache()

Clear the caches this client holds, and the server's process cache.

Empties the JSON:API index and the process cache, and moves cacheGeneration on so results cached per client, such as menus, are fetched again.

Kind: instance method of DruxtClient
Example

this.$druxt.clearCache()

.processCache(scope) ⇒ object

Get the process cache for a scope.

The cache holds server-side responses between requests, each for as long as its Cache-Control header allows. It is off unless the cache option is set, and it is skipped for any request that sends an Authorization header, basic auth or a session cookie.

The content scope, which holds every other GET response, is also off unless cache.content is set.

Kind: instance method of DruxtClient
Returns: object - The cache, or null when it must not be used.

ParamTypeDescription
scopestringThe cache scope, e.g. 'index', 'menu' or 'content'.

.cacheLifetime(document) ⇒ number

How long a document this client fetched may be cached.

Kind: instance method of DruxtClient
Returns: number - Seconds, from the response's Cache-Control. 0 when it may not be cached or is unknown.

ParamTypeDescription
documentobjectA JSON:API document returned by this client.

.addHeaders(headers)

Add headers to the Axios instance.

Kind: instance method of DruxtClient

ParamTypeDescription
headersobjectAn object containing HTTP headers.

Example

this.$druxt.addHeaders({ 'Authorization': `Basic ${token}` })

.buildQueryUrl(url, [query]) ⇒ string

Build query URL.

Kind: instance method of DruxtClient
Returns: string - The URL with query string.

ParamTypeDescription
urlstringThe base query URL.
[query]DruxtClientQueryA correctly formatted JSON:API query string or object.

Example

const query = new DrupalJsonApiParams()
query.addFilter('status', '1')
const queryUrl = this.$druxt.buildQueryUrl(resourceUrl, query)

.createResource(resource, [prefix]) ⇒ object

Create a JSON:API resource.

Kind: instance method of DruxtClient
Returns: object - The response data

ParamTypeDescription
resourceobjectThe JSON:API resource object
[prefix]string(Optional) The JSON:API endpoint prefix or langcode.

Example

await this.$druxt.createResource(
  {
    type: 'node--page',
    attributes: {},
    relationships: {}
  },
  'en'
)

.error(err, context)

Throw a formatted error.

Kind: instance method of DruxtClient
Throws:

  • Error A formatted error.
ParamTypeDescription
errobjectThe error object
contextobjectThe error context; the requested URL.

Example

try {
  await this.$druxt.axios.get(url)
} catch (err) {
  this.$druxt.error(err, { url })
}

.get(url, [options]) ⇒ object

Execute an Axios GET request, with permission checking and error handling.

With cache.content set, a response to a request without credentials is kept in the process cache for as long as its Cache-Control allows, and the next server request for the same URL is answered from it.

Kind: instance method of DruxtClient
Returns: object - The Axios response.

ParamTypeDescription
urlstringThe URL to GET.
[options]objectAn Axios options object.
[options.bypassCache]booleanFetch from Drupal even when the process cache holds the URL, and store the fresh response.

Example

const res = await this.$druxt.get('/jsonapi/node/article')

.getCollection(type, [query], [prefix], [options]) ⇒ object

Get a collection of resources from the JSON:API server.

Kind: instance method of DruxtClient
Returns: object - The JSON:API collection response.

ParamTypeDescription
typestringThe JSON:API Resource type.
[query]DruxtClientQueryA correctly formatted JSON:API query string or object.
[prefix]string(Optional) The JSON:API endpoint prefix or langcode.
[options]object(Optional) Request options.
[options.bypassCache]booleanFetch from Drupal even when the process cache holds the collection.

Example

const collection = await this.$druxt.getCollection(
  'node--recipe',
  undefined,
  'en'
)

.getCollectionAll(type, [query], [prefix], [options]) ⇒ Array.<object>

Get all resources of a collection.

Kind: instance method of DruxtClient
Returns: Array.<object> - An array of JSON:API collections.

ParamTypeDescription
typestringThe JSON:API Resource type.
[query]DruxtClientQueryA correctly formatted JSON:API query string or object.
[prefix]string(Optional) The JSON:API endpoint prefix or langcode.
[options]object(Optional) Request options, as getCollection() takes them, used for every page.

Example

const collections = await this.$druxt.getCollectionAll(
  'node--recipe',
  'fields[node--recipe]=title',
  'en'
)

.getIndex([resource], [prefix]) ⇒ object

Get index of all available resources, or the optionally specified resource.

Kind: instance method of DruxtClient
Returns: object - The resource index object or the specified resource.

ParamTypeDescription
[resource]string(Optional) A specific resource to query.
[prefix]string(Optional) The JSON:API endpoint prefix or langcode.

Example

const { href } = await this.$druxt.getIndex('node--article', 'en')

Get the related resources from a specified JSON:API resource.

Kind: instance method of DruxtClient
Returns: object - The related JSON:API resource(s).

ParamTypeDescription
typestringThe JSON:API Resource type.
idstringThe Drupal resource UUID.
relatedstringThe relationship name.
[query]DruxtClientQueryA correctly formatted JSON:API query string or object.
[prefix]string(Optional) The JSON:API endpoint prefix or langcode.

Example

const related = this.$druxt.getRelated(
  'node--page',
  id, 'uid',
  undefined,
  'en'
)

.getResource(type, id, [query], [prefix], [options]) ⇒ object | boolean

Get a JSON:API resource by type and ID.

Kind: instance method of DruxtClient
Returns: object | boolean - The full JSON:API document; the requested resource is on the data property, e.g. result.data.attributes. Returns false if either type or id is missing.

ParamTypeDescription
typestringThe JSON:API Resource type.
idstringThe Drupal resource UUID.
[query]DruxtClientQueryA correctly formatted JSON:API query string or object.
[prefix]string(Optional) The JSON:API endpoint prefix or langcode.
[options]object(Optional) Request options.
[options.bypassCache]booleanFetch from Drupal even when the process cache holds the resource.

Example

const data = await this.$druxt.getResource(
  'node--article',
  id,
  undefined,
  'en'
)

.updateResource(resource, [prefix]) ⇒ object

Update a JSON:API resource.

Kind: instance method of DruxtClient
Returns: object - The response data

ParamTypeDescription
resourceobjectThe JSON:API resource object
[prefix]string(Optional) The JSON:API endpoint prefix or langcode.

Example

await this.$druxt.updateResource(
  {
    type: 'node--page',
    id,
    attributes: {},
    relationships: {}
  },
  'en'
)

DruxtClientOptions : object

DruxtClient options object.

Kind: global typedef
See: https://github.com/axios/axios#request-config

ParamTypeDefaultDescription
[axios]objectAxios instance settings.
[cache]objectServer-side cache shared between requests that do not send credentials, each response kept for as long as its Cache-Control allows. Off by default. The Nuxt module turns it on in production.
[cache.content]booleanfalseAlso keep entities, collections, views and route lookups, not only the index and menus.
[cache.maxSize]number52428800Bytes of responses each cache area keeps, measured as stored JSON.
[cache.ttl]numberSeconds a cached response may live at most. It never extends Cache-Control.
[cache.sessionCookie]string"S?SESS[0-9a-f]+"A pattern for the session cookie name.
[debug]booleanfalseEnable Debug mode for verbose console log messages.
[endpoint]string"jsonapi"The JSON:API endpoint.
[jsonapiResourceConfig]string"jsonapi_resource_config--jsonapi_resource_config"The JSON:API resource config type, used for JSON:API Extras support.

Example

{
  // Axios instance settings.
  axios: {
    // Set axios headers.
    headers: { 'X-Custom-Header': true },
  },
  // Enable debug console log messages.
  debug: true,
  // JSON:API endpoint.
  endpoint: 'api',
}

DruxtClientQuery : string | object

A correctly formatted JSON:API query string or object.

Kind: global typedef
See: https://www.npmjs.com/package/drupal-jsonapi-params
Example

'page[limit]=5&page[offset]=5'

Example

new DrupalJsonApiParams().addPageLimit(5)