@drupal-api-client/json-api-client
v1.5.0
Published
A package to simplify the process of interacting with Drupal's JSON:API endpoints
Readme
jsonapi-client
This package contains the JsonApiClient class which extends the base ApiClient class from the @drupal-api-client/api-client package. See https://www.drupal.org/project/api_client for more information about this project.
Installation
npm i @drupal-api-client/json-api-clientUsage
import {
JsonApiClient,
createCache,
DefaultSerializer,
} from "@drupal-api-client/json-api-client";
import Jsona from "jsona";
// the baseUrl to fetch data from
const myDrupalUrl = process.env.MY_DRUPAL_SITE || "https://drupal.example.com";
const nodeCache = new NodeCache();
const client = new JsonApiClient(myDrupalUrl, {
// supply a custom fetch method in order to add certain headers to each request
// or any other logic you may need before the fetch call
customFetch: (input: RequestInfo | URL, init?: RequestInit) => {
const newHeaders = new Headers(init?.headers);
newHeaders.set("X-Custom-Header", "my-custom-value");
const newInit = {
...init,
headers: newHeaders,
};
return fetch(input, newInit);
},
// the optional cache will cache a request and return the cached data if the request
// is made again with the same type same data.
// The cache must implement the `Cache` interface.
// The `createCache` method provides a default cache that satisfies this interface.
cache: createCache(),
// the optional authentication object will be used to authenticate requests.
// Currently Basic auth is supported.
authentication: {
type: "Basic",
// It is recommended to store sensitive information in environment variables that
// are not checked in to the source code.
credentials: {
username: process.env.MY_USERNAME,
password: process.env.MY_SECRET_PASSWORD,
},
},
// The language used for any request that does not pass its own `locale`
// option (a per-request `locale` always wins). The language is sent as a
// `/{locale}/` URL prefix (how stock Drupal negotiates, see
// languagePathPrefix below) and as a `langCode` query parameter (the only
// language selector of the jsonapi_multilingual module; stock Drupal
// ignores it), so the same request works on either kind of backend.
// With jsonapi_multilingual, a read of a translation that does not exist
// is a strict 404 advertising the existing translations (see
// getAvailableTranslations); pass the `includeFallback: true` read option
// to defer to the site's language fallback chain instead.
// example read: https://drupal.example.com/en/jsonapi/node/article?langCode=en
// Omit it to let the backend serve its own default language.
defaultLocale: "en",
// The `/{locale}/` prefix is sent for backwards compatibility with URL
// path-prefix negotiation (stock Drupal). For a backend using the
// jsonapi_multilingual module, setting this to false is recommended:
// langCode then carries the language on the canonical URL. This includes
// the decoupled_router hop of getResourceByPath — a translated alias
// resolves from the path alone, and the module reports the resolved
// language as entity.langcode, which getResourceByPath passes to the
// follow-up read. On a backend without the module, leave this on if
// translated path aliases must resolve.
languagePathPrefix: true,
// the optional serializer will be used to serialize and deserialize data.
// DefaultSerializer (from this package) extends Jsona and adds getMeta()/getLinks() for
// JSON:API top-level meta and links; otherwise use Jsona() or another compatible serializer.
serializer: new DefaultSerializer(),
// when set to true, verbose logging will be output to the console,
// helpful for debugging errors.
debug: true,
});
try {
// fetch a single resource
const article = await client.getResource("node--article", "1234");
// fetch a collection of nodes
const articles = await client.getCollection("node--article");
} catch (error) {
// errors will be bubbled up from the `getCollection` and `getResource` methods.
// if `debug` is set to true in the options, the error will be logged to the console.
// You can handle the error here as you see fit.
}