Skip to main content

Javascript connector

In frontend applications, the connection to the API is created using a javascript library that incorporates the necessary logic and prevents the need to define complicated methods for data retrieval. The library, available on npm as @discoverycms/connector, only requires axios as a dependency and exposes a set of methods that can be used in any JS application, and some hooks for JS based applications on ReactJS.

Setup

First you need to install the library with npm:

npm i @discoverycms/connector --save

Once the installation is complete, you can now initialize the connector. To do this you need to call the setupDiscoveryCms() method as follows:

import ComponentRenderer from 'some-path';

setupDiscoveryCms({
apiRoot: 'https://some_url/API/v1/',
apiToken: '123456789',
propertyTitle: 'mywebsite',
components: {
ComponentTypeName: ComponentRenderer
},
enableConnectorScript: true,
disableCache: true
})

The method is passed an options object:

  • apiRoot: (required) root of the cloud API;
  • apiToken: (required) token used by default to retrieve content from the CloudAPI;
  • propertyTitle: the name that was assigned to the property on the CMS upon creation;
  • components: object in which it is possible to associate a JSX component with a key, defined on the Discovery side;
  • enableConnectorScript: true|false, enables the graphical connector for the connection between the components and the page editor;
  • disableCache: true|false, disables both Cloudfront and lambda caching.

Finally, you need to copy the discovery-cms-connector.js file into your project, in the public folder, taking it from node_modules/@discoverycms/connector.

In order to make the connector available across the entire application and to avoid having to replicate this initialization in several points, it is convenient to call the method in a js file that is loaded at each request, such as the App.js file of a React application.

Methods to Recover Individual Contents

After initializing the connector, you can recover it using the getDiscoveryCms() method. The method returns an object of class DiscoveryCms that exposes various methods. Among these, the main ones are:

  • getPage(slug: string, options: DiscoveryRequestOptions): retrieve a page from the API using its slug;
  • getPageById(discoveryId: string, options: DiscoveryRequestOptions): Retrieve a page from the API using its identifier;
  • getContent(slug: string, options: DiscoveryRequestOptions): retrieve a structured content from the API using its slug;
  • getContentById(discoveryId: string, options: DiscoveryRequestOptions): retrieve a structured content from the API using its identifier;
  • getAsset(discoveryId: string, options: DiscoveryRequestOptions): allows you to recover a digital asset using its identifier. See Filtering Digital Assets.

These methods are encapsulated in the following React hooks:

  • useDiscoveryContent(slug: string, options: DiscoveryRequestOptions, errorCallback: (error) => any): encapsulates the getContent method, described above, in a useEffect, reloading the component when the API call returns the data. In case of error in the API call, it is possible to pass a callback to define the behavior;
  • useDiscoveryContentById(id: string, options: DiscoveryRequestOptions, errorCallback: (error) => any): same as useDiscoveryContent but use the id of the Content.
  • useDiscoveryPage(slug: string, options: DiscoveryRequestOptions, errorCallback: (error) => any): hook that encapsulates the getPage method, described above, in a useEffect, reloading the component when the API call returns the data. In case of error in the API call, it is possible to pass a callback to define the behavior;
  • useDiscoveryPageById(id: string, options: DiscoveryRequestOptions, errorCallback: (error) => any): same as useDiscoveryPage but use the Page id.
  • useDiscoveryAsset(id: string, options: DiscoveryRequestOptions, errorCallback: (error) => any): encapsulates the getAsset method, described above, in a useEffect, reloading the component when the API call returns the data. If the API call fails, you can pass a callback to define the behavior;
  • usePalette(): returns the current page palette, if set. As fallback, it tries to retrieve the palette from the layout page linked to the current page.
  • usePageData(): returns the whole object returned by the Content API for this page.
  • useLayoutComponentData(id: string): for pages having a linked layout, it returns the component of the layout page whose ID matches the passed ID. Advanced usage only.

The use of Context is strongly recommended within React applications. This in fact enables two additional classes and an additional hook:

  • DiscoveryComponents: retrieves the context defined in the connector and creates an instance of each object in the array components. It is therefore possible to initialize the context in the padata, so as to be able to propagate them to its members;
  • DiscoveryComponent: using the component map defined during setup, creates an instance of a component React starting from a simple Javascript object in which two attributes must be defined:
    • _id
    • type: if no component has been defined for type, an error message is shown instead of the component. If instead a React object has been defined by type, the object is created by passing it the componentId parameter and the create-discovery-component event is dispatched;
  • useComponentData(id: string): retrieve a component's data from the Context via its uuid;
  • usePageData(): retrieves all data of the current page. The returned object contains the details (page settings) sections, components (tree of page components) and, optionally, layout (data of any page layout).

Methods to Recover Multiple Contents

Below are the methods by which you can query the repository to obtain lists of results:

  • getContents(options: DiscoveryContentsRequestOptions): retrieves a set of structured contents by applying the criteria provided in the options parameter; for details, see section getContents() method;
  • getAssets(options: DiscoveryContentsRequestOptions): retrieves a set of digital assets by applying the criteria provided in the options parameter; for details, see section getContents() method and Filtering Digital Assets;
  • getFiltersFromQueryParams(queryParams: any): allows you to transform the query params retrieved for a request in a filters object that can be used in type optionsDiscoveryRequestOptions to filter the results obtained. The method filters the provided query params and apply the following logic:
    • Retrieve parameters whose key begins with filter_. Example: filter_price=...;
    • Check if an operator is provided. If it is provided, it must be specified in square brackets after the name of the field on which the filter is to be applied. Example: filter_price[bt]=.... If no operator is provided, example: filter_title=Title, the default operator is [eq];
    • Composes a filters object containing the converted criteria. Example: url...?filter_title=DemoTitle&filter_price[bt]=10 is converted to
      {
      title: 'DemoTitle',
      'price[bt]': 10
      }

To simplify usage in React the following hook is available:

  • useDiscoveryContents(options: DiscoveryContentsRequestOptions, errorCallback: (error) => any): hook that encapsulates the getContents method, described above, in a useEffect, updating the DOM when the API call returns the data. In case of error in the API call, it is possible to pass a callback to define the behavior;
  • useDiscoveryAssets(options: DiscoveryContentsRequestOptions, errorCallback: (error) => any): hook that encapsulates the getAssets method, described above, in a useEffect, updating the DOM when the API call returns the data. In case of error in the API call, it is possible to pass a callback to define the behavior;

Other Methods

  • getToken(): returns the token provided to setup;
  • getComponents(): returns the Components map defined during setup;
  • getPathList(options: DiscoveryContentsRequestOptions): returns an array containing the content slug which match the conditions specified in the options object to implement the SSG.
  • getContext(): Returns the React context used in dynamic pages.

DiscoveryRequestOptions

The DiscoveryRequestOptions class defines options that can be passed to the connector methods explained in the Retrieve Multiple Contents section.

Where indicated, it is recommended to use the DiscoveryConstants class instead of entering string values manually.

The possible options are:

  • token: token to pass to the API, instead of the one defined during setup, to retrieve other versions of the data, for example preview or production;
  • authToken: (optional) in case the API is behind an authentication service, such as AWS Cognito, this property can be set in order to pass an "Authorization: ..." HTTP Header to authenticate the endpoint invocation.
  • children: allows you to define the expansion policy of the references contained in the entity. Accepts one of 3 values:
    • DiscoveryConstants.CHILDREN.NONE: the references are not expanded and only the relative id is provided;
    • DiscoveryConstants.CHILDREN.SUMMARY: references are expanded using the summary payload;
    • DiscoveryConstants.CHILDREN.DETAILS: references are expanded using the detail payload.
  • fields: defines which fields are provided when retrieving Content or a Page;
  • key_type: when retrieving a page, it isit is possible to indicate which field the query should be made on;
  • disable_cache: allows you to disable the API cache;
  • response_type: allows you to choose between two types of response:
    • DiscoveryConstants.RESPONSE_TYPE.SUMMARY: the response is created using the summary payload;
    • DiscoveryConstants.RESPONSE_TYPE.DETAILS: the response is created using the detail payload;

getContents() method

The DiscoveryContentsRequestOptions class defines the options that can be provided when searching for Contents. In addition to those defined in DiscoveryRequestOptions, the options are:

  • type: defines the reference content type and must be specified for each request; applies to private types. (in roadmap) if you want to refer to a global type, you need to indicate globalType instead of type;
  • start: index of the first element returned from the result array retrieved from the API;
  • limit: maximum number of results provided by the request;
  • sort: defines the sorting of results based on an attribute, for example: title asc or title desc. It is possible to use either an API field, such as title if this is in the response payload, or (for advanced users) a Solr field, if known. IMPORTANT: to sort on titles the special field title_sortable_str asc must be used;
  • filters: object containing the filters to pass to the search engine. See section Filtering Contents
  • last_deploy_timestamp: allows you to recover only the contents that have been modified after a certain date/time;
  • fq: (advanced) allows you to pass an array of strings corresponding to filter queries to be used on the search engine;