DruxtClient
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
- DruxtClient
- new DruxtClient(baseUrl, [options])
- .axios :
object - .index :
object - .cacheGeneration :
number - .clearCache()
- .processCache(scope) ⇒
object - .cacheLifetime(document) ⇒
number - .addHeaders(headers)
- .buildQueryUrl(url, [query]) ⇒
string - .createResource(resource, [prefix]) ⇒
object - .error(err, context)
- .get(url, [options]) ⇒
object - .getCollection(type, [query], [prefix], [options]) ⇒
object - .getCollectionAll(type, [query], [prefix], [options]) ⇒
Array.<object> - .getIndex([resource], [prefix]) ⇒
object - .getRelated(type, id, related, [query], [prefix]) ⇒
object - .getResource(type, id, [query], [prefix], [options]) ⇒
object|boolean - .updateResource(resource, [prefix]) ⇒
object
new DruxtClient(baseUrl, [options])
DruxtClient constructor.
- Validates module options.
- Sets up Axios instance.
- Sets up options.
| Param | Type | Description |
|---|---|---|
| baseUrl | string | The Drupal base URL. |
| [options] | DruxtClientOptions | The 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.
| Param | Type | Description |
|---|---|---|
| scope | string | The 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.
| Param | Type | Description |
|---|---|---|
| document | object | A JSON:API document returned by this client. |
.addHeaders(headers)
Add headers to the Axios instance.
Kind: instance method of DruxtClient
| Param | Type | Description |
|---|---|---|
| headers | object | An 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.
| Param | Type | Description |
|---|---|---|
| url | string | The base query URL. |
| [query] | DruxtClientQuery | A 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
| Param | Type | Description |
|---|---|---|
| resource | object | The 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:
ErrorA formatted error.
| Param | Type | Description |
|---|---|---|
| err | object | The error object |
| context | object | The 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.
| Param | Type | Description |
|---|---|---|
| url | string | The URL to GET. |
| [options] | object | An Axios options object. |
| [options.bypassCache] | boolean | Fetch 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.
| Param | Type | Description |
|---|---|---|
| type | string | The JSON:API Resource type. |
| [query] | DruxtClientQuery | A 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] | boolean | Fetch 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.
| Param | Type | Description |
|---|---|---|
| type | string | The JSON:API Resource type. |
| [query] | DruxtClientQuery | A 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.
| Param | Type | Description |
|---|---|---|
| [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')
.getRelated(type, id, related, [query], [prefix]) ⇒ object
Get the related resources from a specified JSON:API resource.
Kind: instance method of DruxtClient
Returns: object - The related JSON:API resource(s).
| Param | Type | Description |
|---|---|---|
| type | string | The JSON:API Resource type. |
| id | string | The Drupal resource UUID. |
| related | string | The relationship name. |
| [query] | DruxtClientQuery | A 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.
| Param | Type | Description |
|---|---|---|
| type | string | The JSON:API Resource type. |
| id | string | The Drupal resource UUID. |
| [query] | DruxtClientQuery | A 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] | boolean | Fetch 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
| Param | Type | Description |
|---|---|---|
| resource | object | The 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
| Param | Type | Default | Description |
|---|---|---|---|
| [axios] | object | Axios instance settings. | |
| [cache] | object | Server-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] | boolean | false | Also keep entities, collections, views and route lookups, not only the index and menus. |
| [cache.maxSize] | number | 52428800 | Bytes of responses each cache area keeps, measured as stored JSON. |
| [cache.ttl] | number | Seconds 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] | boolean | false | Enable 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)