Final Class: RESTDataProvider

Oracle® JavaScript Extension Toolkit (JET)
16.1.0

F92237-01

Since:
  • 11.0.0
Module:
  • ojrestdataprovider

QuickNav

Description

This class implements DataProvider. Object representing data available from a JSON-based REST service. This dataprovider can be used by ListView, NavigationList, TabBar, and Table.

RESTDataProvider is an implementation of DataProvider for fetching data from a JSON-based REST API using the Fetch API . RESTDataProvider fetch calls are based on transforms which are specified as an option to the RESTDataProvider constructor. For each fetch method (fetchFirst, fetchByOffset and fetchByKeys), they define the following functions:

  • request : function that returns a Promise that resolves to a Request object to use for the Fetch API call to the the REST API. This is where any required query parameters for paging, filtering, sorting and more can be applied to the URL which can then be used to create a request. Other request options, such as headers , body and method can also be added to the request if needed. If written in Typescript, the function can be defined using async which automatically wraps the return value in a Promise . Otherwise, a Promise has to be explicitly returned e.g return Promise.resolve(new Request(...)) .
  • response : function that extracts the data and other relevant values from the response body and returns a Promise that resolves to those values. The function must at least return an object with a data property that is an array of items of shape D (generic passed into RESTDataProvider class). If written in Typescript, the function can be defined using async which automatically wraps the return value in a Promise . Otherwise, a Promise has to be explicitly returned e.g return Promise.resolve({ data }) .
Please navigate to the corresponding demos for details of how to define transforms to accomplish various fetch tasks.

Events

Consumers can add event listeners to listen for the following event types.

mutate

This event is fired when the mutate method is called.

Event payload is found under event.detail, which implements the DataProviderMutationEventDetail interface.

refresh

This event is fired when the refresh method is called.

This event contains no additional event payload.

Example of consumer listening for the "mutate" event type:
var listener = function(event) {
  if (event.detail.remove) {
    var removeDetail = event.detail.remove;
    // Handle removed items
  }
};
dataProvider.addEventListener("mutate", listener);


Usage

Signature:

final class RESTDataProvider<K, D> implements DataProvider<K, D>

Typescript Import Format
//To import this class, use the format below.
import {RESTDataProvider} from "ojs/ojrestdataprovider";

For additional information visit:


Final classes in JET

Classes in JET are generally final and do not support subclassing. At the moment, final is not enforced. However, this will likely change in an upcoming JET release.


Constructor

new RESTDataProvider(options)

Parameters:
Name Type Description
options RESTDataProvider.Options.<K, D> options for the RESTDataProvider
Example
// First create an options object with the minimum fields
const options = {
 url: 'url/to/rest/endpoint',
 transforms: {
  // fetchByOffset and fetchByKeys delegate to fetchFirst if their capabilities are not defined
  // so at minimum we must specify transforms for fetchFirst
  fetchFirst: {
    request: async (options) => {
      // Use size and offset to set the expected paging parameters and create a request.
      // In this example, "size" corresponds to the endpoint' "limit"
      // parameter and "offset" corresponds to the endpoint' "offset" parameter for the mock
      // server. Note that the function needs to return a Promise, hence the use of async which
      // automatically wraps the return value in one
      const url = new URL(options.url);
      const { size, offset } = options.fetchParameters;
      url.searchParams.set("limit", String(size));
      url.searchParams.set("offset", String(offset));
      return new Request(url.href);
    },
    response: async ({ body }) => {
      // The mock server sends back a response body with shape { hasMore, keys, totalSize, data} so
      // we need to extract and return them. "keys" is optional, it is needed when the REST endpoint
      // returns the set of keys associated with the data. When not available, RESTDataProvider generates
      // the keys from the data based on keyAttributes. Again, note that the function needs to return a
      // Promise hence the use of async which automatically wraps the return value in one
      const { data, keys, totalSize, hasMore } = body;
      return { data, keys, totalSize, hasMore };
    }
  }
 }
};
// Then create an RESTDataProvider object with the options
const dataprovider = new RESTDataProvider(options);

Methods

addEventListener(eventType: string, listener: EventListener): void

Add a callback function to listen for a specific event type.
Parameters:
Name Type Description
eventType string The event type to listen for.
listener EventListener The callback function that receives the event notification.

containsKeys(parameters : FetchByKeysParameters<K>) : Promise<ContainsKeysResults<K>>

Check if there are rows containing the specified keys. The resulting key map will only contain keys which were actually found.
Parameters:
Name Type Description
parameters FetchByKeysParameters contains by key parameters
Since:
  • 4.2.0
Returns:

Returns Promise which resolves to ContainsKeysResults.

Type
Promise.<ContainsKeysResults>
Example

Check if keys 1001 and 556 are contained

let keySet = new Set();
keySet.add(1001);
keySet.add(556);

let value = await dataprovider.containsKeys({keys: keySet});
let results = value['results'];
if (results.has(1001)) {
  console.log('Has key 1001');
} else if (results.has(556)) {
  console.log('Has key 556');
}

createOptimizedKeyMap(initialMap?: Map<K, D>): Map<K, D>

Return an empty Map which is optimized to store key value pairs

Optionally provided by certain DataProvider implementations for storing key/value pairs from the DataProvider in a performant fashion. Sometimes components will need to temporarily store a Map of keys provided by the DataProvider, for example, in the case of maintaining a Map of selected keys. Only the DataProvider is aware of the internal structure of keys such as whether they are primitives, Strings, or objects and how to do identity comparisons. Therefore, the DataProvider can optionally provide a Map implementation which can performantly store key/value pairs surfaced by the DataProvider.

Parameters:
Name Type Argument Description
initialMap Map.<any> <optional>
Optionally specify an initial map of key/values for the Map. If not specified, then return an empty Map.
Since:
  • 6.2.0
Returns:

Returns a Map optimized for handling keys from the DataProvider.

Type
Map.<any>
Example

create empty key Map

// create optional parameter
let initMap = new Map();
initMap.set('a', 'apple');
let keyMap = dataprovider.createOptimizedKeyMap(initMap);

createOptimizedKeySet(initialSet?: Set<K>): Set<K>

Return an empty Set which is optimized to store keys

Optionally provided by certain DataProvider implementations for storing keys from the DataProvider in a performant fashion. Sometimes components will need to temporarily store a Set of keys provided by the DataProvider, for example, in the case of maintaining a Set of selected keys. Only the DataProvider is aware of the internal structure of keys such as whether they are primitives, Strings, or objects and how to do identity comparisons. Therefore, the DataProvider can optionally provide a Set implementation which can performantly store keys surfaced by the DataProvider.

Parameters:
Name Type Argument Description
initialSet Set.<any> <optional>
Optionally specify an initial set of keys for the Set. If not specified, then return an empty Set.
Since:
  • 6.2.0
Returns:

Returns a Set optimized for handling keys from the DataProvider.

Type
Set.<any>
Example

create empty key Set

// create optional initial parameter
let initSet = new Set();
initSet.add('a');
let keySet = dataprovider.createOptimizedKeySet(initSet);

dispatchEvent(evt: Event): boolean

Dispatch an event and invoke any registered listeners.
Parameters:
Name Type Description
event Event The event object to dispatch.
Returns:

Return false if a registered listener has cancelled the event. Return true otherwise.

Type
boolean

fetchByKeys(parameters : FetchByKeysParameters<K>) : Promise<FetchByKeysResults<K, D>>

Fetch rows by keys. The resulting key map will only contain keys which were actually found. Fetch can be aborted if an AbortSignal is specified when calling fetchByKeys.
Parameters:
Name Type Description
parameters FetchByKeysParameters fetch by key parameters
Since:
  • 4.2.0
Returns:

Returns Promise which resolves to FetchByKeysResults.

Type
Promise.<FetchByKeysResults>
Examples

Fetch for keys 1001 and 556

let keySet = new Set();
keySet.add(1001);
keySet.add(556);

let value = await dataprovider.fetchByKeys({keys: keySet});
// get the data for key 1001
console.log(value.results.get(1001).data);

How to abort fetchByKeys

// abort on an AbortController instance will abort all requests that are associated
// with the signal from that abortController.
const abortController = new AbortController();
let keySet = new Set();
keySet.add(1001);
keySet.add(556);
// component passes AbortSignal as part of FetchByKeysParameters to fetchByKeys
// on dataProvider
try {
 let value = await dataprovider.fetchByKeys({keys: keySet, signal: abortController.signal});
} catch (err) {
 // if the data fetch has been aborted, retrieving data from the fetched result
 // will be rejected with DOMException named AbortError
}
// later when abort is desired, component can invoke abort() on the cached
// abort controller to abort any outstanding data retrieval it requested
// on asyncIterator.
if (abort_is_desired) {
  abortController.abort();
}

fetchByOffset(parameters: FetchByOffsetParameters<D>): Promise<FetchByOffsetResults<K, D>>

Fetch rows by offset. Fetch can be aborted if an AbortSignal is specified when calling fetchByOffset.

A generic implementation of this method is available from FetchByOffsetMixin. It is for convenience and may not provide the most efficient implementation for your data provider. Classes that implement the DataProvider interface are encouraged to provide a more efficient implementation.

Parameters:
Name Type Description
parameters FetchByOffsetParameters fetch by offset parameters. If an unsupported matchBy value is included in FetchByOffsetParameters, an error will be thrown.
Since:
  • 4.2.0
Returns:

Returns Promise which resolves to FetchByOffsetResults.

Type
Promise.<FetchByOffsetResults>
Examples

Fetch by offset 5 rows starting at index 2

let result = await dataprovider.fetchByOffset({size: 5, offset: 2});
let results = result['results'];
let data = results.map(function(value) {
  return value['data'];
});
let keys = results.map(function(value) {
  return value['metadata']['key'];
});

How to abort fetchByOffset

// abort on an AbortController instance will abort all requests that are associated
// with the signal from that abortController.
const abortController = new AbortController();
// component passes AbortSignal as part of FetchByOffsetParameters to fetchByOffset
// on dataProvider

try {
 let value = await dataprovider.fetchByOffset({
                 size: 5,
                 offset: 2,
                 signal: abortController.signal
             });
} catch (err) {
 // if the data fetch has been aborted, retrieving data from the fetched result
 // will be rejected with DOMException named AbortError
}
// later when abort is desired, component can invoke abort() on the cached
// abort controller to abort any outstanding data retrieval it requested
// on asyncIterator.
if (abort_is_desired) {
  abortController.abort();
}

fetchFirst(parameters?: FetchListParameters<D>): AsyncIterable<FetchListResult<K, D>>

Get an AsyncIterable object for iterating the data. Iterating data on this AsyncIterable object can be aborted if an AbortSignal is specified when getting this AsyncIterable object.

AsyncIterable contains a Symbol.asyncIterator method that returns an AsyncIterator. AsyncIterator contains a “next” method for fetching the next block of data.

The "next" method returns a promise that resolves to an object, which contains a "value" property for the data and a "done" property that is set to true when there is no more data to be fetched. The "done" property should be set to true only if there is no "value" in the result. Note that "done" only reflects whether the iterator is done at the time "next" is called. Future calls to "next" may or may not return more rows for a mutable data source.

In order for JET components to work correctly, DataProvider implementations should ensure that:

  • The iterator accounts for data mutations when returning the next block of data, and that no row is duplicated or skipped. For example, an offset-based implementation may need to adjust the offset from which the next block of data starts if rows have been added or removed in the returned data.
  • JET components may call "next" on the iterator even after the iterator has returned done:true. If new data is available after the last returned row, the iterator is expected to return the new data and set "done" to false. This differs from the AsyncIterator spec for performance reasons.

Please see the DataProvider documentation for more information on custom implementations.

Parameters:
Name Type Argument Description
params FetchListParameters <optional>
fetch parameters. If an unsupported matchBy value is included in FetchListParameters, an error will be thrown.
Since:
  • 4.2.0
See:
Returns:

AsyncIterable with FetchListResult

Type
AsyncIterable.<FetchListResult>
Examples

Get an asyncIterator and then fetch first block of data by executing next() on the iterator. Subsequent blocks can be fetched by executing next() again.

let asyncIterator = dataprovider.fetchFirst(options)[Symbol.asyncIterator]();
let result = await asyncIterator.next();
let value = result.value;
let data = value.data;
let keys = value.metadata.map(function(val) {
  return val.key;
});
// true or false for done
let done = result.done;

How to abort fetchFirst

// abort on an AbortController instance will abort all requests that are associated
// with the signal from that abortController.
const abortController = new AbortController();
// component passes AbortSignal as part of FetchListParameters to fetchFirst
// on dataProvider to get an iterator that carries AbortSignal in it.
const asyncIterator = dataprovider
       .fetchFirst({
          size: this.size,
          signal: abortController.signal,
           ...
        })[Symbol.asyncIterator]();
try {
 const result = await asyncIterator.next();
} catch (err) {
 // if the data fetch has been aborted, retrieving data from the fetched result
 // will be rejected with DOMException named AbortError
}
// later when abort is desired, component can invoke abort() on the cached
// abort controller to abort any outstanding data retrieval it requested
// on asyncIterator.
if (abort_is_desired) {
  abortController.abort();
}

getCapability(capabilityName: string): any

Determines whether this DataProvider defines a certain feature.
Parameters:
Name Type Description
capabilityName string capability name. Defined capability names are: "dedup", "eventFiltering", "fetchByKeys", "fetchByOffset", "fetchCapability", "fetchFirst", "filter", and "sort".
Since:
  • 4.2.0
Returns:

capability information or null if undefined

Type
Object
Example

Check what kind of fetchByKeys is defined.

let capabilityInfo = dataprovider.getCapability('fetchByKeys');
if (capabilityInfo.implementation == 'iteration') {
  // the DataProvider supports iteration for fetchByKeys
  ...

getTotalSize : {Promise.<number>}

Return the total number of rows in this dataprovider
Returns:

Returns a Promise which resolves to the total number of rows. -1 is unknown row count.

Type
Promise.<number>
Example

Get the total rows

let value = await dataprovider.getTotalSize();
if (value === -1) {
  // we don't know the total row count
} else {
  // the total count
  console.log(value);
}

isEmpty(): 'yes' | 'no' | 'unknown'

Returns a string that indicates if this data provider is empty. Valid values are:
  • "yes": this data provider is empty.
  • "no": this data provider is not empty.
  • "unknown": it is not known if this data provider is empty until a fetch is made.
Since:
  • 4.2.0
Returns:

string that indicates if this data provider is empty

Type
"yes" | "no" | "unknown"
Example

Check if empty

let isEmpty = dataprovider.isEmpty();
console.log('DataProvider is empty: ' + isEmpty);

mutate(detail : DataProviderMutationEventDetail<K, D>) : void

Triggers a "mutate" event, with the passed in mutation detail, for listening dataprovider consumers. RESTDataProvider does not support CRUD operations and as such, applications are responsible for calling this method when a change happens to notify consumers.
Parameters:
Name Type Description
detail DataProviderMutationEventDetail mutation detail
Since:
  • 11.0.0
Example

Trigger "mutate" event with passed in mutation detail

dataprovider.mutate({
  add: {
    data: [row],
    indexes: [rowIndex],
    keys: new Set([rowKey]),
    metadata: [{ key: rowKey }]
  }
});

refresh() : void

Triggers a "refresh" event for listening dataprovider consumers.
Since:
  • 11.0.0
Example

Trigger "refresh" event

dataprovider.refresh();

removeEventListener(eventType: string, listener: EventListener): void

Remove a listener previously registered with addEventListener.
Parameters:
Name Type Description
eventType string The event type that the listener was registered for.
listener EventListener The callback function that was registered.

Type Definitions

Capabilities

Properties:
Name Type Argument Description
fetchByKeys FetchByKeysCapability <optional>
Optional FetchByKeysCapability object. If not set or if the implementation is "iteration", fetchByKeys calls will delegate to fetchFirst which is not efficient. If the implementation is "lookup", individual requests will be made for each key and then combined. If the implementation is "batchLookup", a single request will be made for all keys. Please see RESTDataProvider.Transforms for how requests should be transformed for fetchByKeys calls.
fetchByOffset FetchByOffsetCapability <optional>
Optional FetchByOffsetCapability object. If not set or if the implementation is "iteration", fetchByOffset calls will delegate to fetchFirst which is not efficient. When implementation is "randomAccess", data can be fetched from any offset and in order and not just from sequentially from the beginning.
filter FilterCapability <optional>
Optional FilterCapability object which specifies the type of filtering supported by the REST service.
sort SortCapability <optional>
Optional SortCapability object which specifies the type of sorting supported by the REST service.

FetchByKeysRequestTransform<K>

Signature:

(options: RESTDataProvider.FetchByKeysRequestTransformOptions<K>) => Promise<Request>

FetchByKeysRequestTransformOptions<K>

Properties:
Name Type Description
fetchParameters FetchByKeysParameters.<K> fetch parameters of the called fetch method
fetchType 'fetchByKeys' fetch method called
url string url to use for fetch call

FetchByKeysTransforms<K, D>

Properties:
Name Type Argument Description
request RESTDataProvider.FetchByKeysRequestTransform<K> <optional>
Object which specifies request transforms
response RESTDataProvider.FetchResponseTransform<K, D> <optional>
Object which specifies response transforms

FetchByOffsetRequestTransform<K, D>

Signature:

(options: RESTDataProvider.FetchByOffsetRequestTransformOptions<K, D>) => Promise<Request>

FetchByOffsetRequestTransformOptions<K, D>

Properties:
Name Type Description
fetchOptions { textFilterAttributes?: RESTDataProvider.Options<K, D>['textFilterAttributes'] } fetch options passed into constructor such as textFilterAttributes
fetchParameters FetchByOffsetParameters.<D> fetch parameters of the called fetch method
fetchType 'fetchFirst' | 'fetchByOffset' fetch method called
url string url to use for fetch call

FetchByOffsetTransforms<K, D>

Properties:
Name Type Argument Description
request RESTDataProvider.FetchByOffsetRequestTransform<K, D> <optional>
Object which specifies request transforms
response RESTDataProvider.FetchResponseTransform<K, D> <optional>
Object which specifies response transforms

FetchErrorDetail<K, D>

This type will be returned to the error callback when underlying fetch call has resulted in a type error.
Properties:
Name Type Description
err TypeError TypeError returned from fetch call (Deprecated use error instead)
Deprecated:
Since Description
15.1.0 Use Error instead.
error TypeError TypeError returned from fetch call
fetchParameters FetchListParameters<D> | FetchByKeysParameters<K> | FetchByOffsetParameters.<D> FetchParams passed into the fetch call
fetchType 'fetchFirst' | 'fetchByKeys' | 'fetchByOffset' Type of fetch that was made
options RESTDataProvider.Options.<K, D> Options passed in to RESTDataProvider

FetchResponseErrorDetail<K, D>

This type will be returned to the error callback when underlying fetch call has resulted in an response with response.ok = false.
Properties:
Name Type Description
fetchParameters FetchListParameters<D> | FetchByKeysParameters<K> | FetchByOffsetParameters.<D> FetchParams passed into the fetch call
fetchType 'fetchFirst' | 'fetchByKeys' | 'fetchByOffset' Type of fetch that was made
options RESTDataProvider.Options.<K, D> Options passed in to RESTDataProvider
response RESTDataProvider.FetchResponseOptions Response returned from server

FetchResponseOptions

Properties:
Name Type Description
body any response body
headers Headers response headers object
status number response status number

FetchResponseTransform<K, D>

Signature:

(options: RESTDataProvider.FetchResponseTransformOptions) => Promise<RESTDataProvider.FetchResponseTransformResult<K, D>>

FetchResponseTransformOptions

Properties:
Name Type Description
body any response body
headers Headers response headers object
status number response status number

FetchResponseTransformResult<K, D>

Properties:
Name Type Argument Description
data D[] fetched data
hasMore boolean <optional>
whether there are more rows available to be fetched
keys K[] <optional>
keys associated with fetched data. If keys is returned but not metadata, the metadata will be generated from the keys
metadata ItemMetadata<K>[] <optional>
metadata associated with fetched data. If metadata is returned but not keys, the keys will be extracted from the metadata
totalSize number <optional>
total number of rows available

Options<K, D>

Properties:
Name Type Argument Description
capabilities Capabilities <optional>
Object which defines the capabilities of the RESTDataProvider instance based on the REST service is fetches data from.
error ?((response: RESTDataProvider.FetchErrorDetail<K,D > | RESTDataProvider.FetchResponseErrorDetail<K,D>) => void) Callback function that is executed when a fetch error has occurred.
implicitSort Array.<SortCriterion.<D>> <optional>
Array of SortCriterion used to specify sort information when the fetched data is already sorted. For example, ojTable will display the column sort indicator for the corresponding column in either ascending or descending order upon initial render. This option is not used for cases where we want the RESTDataProvider to apply a sort on initial fetch.
iterationLimit number <optional>
Specify the maximum number of rows to fetch when iterating through the data. This is particularly useful when fetchByKeys delegates to fetchFirst (because the fetchByKeys capability has not be set with an implementation of "lookup" or "batchLookup"). In the fetchByKeys case, fetchFirst has to iterate through all the data in search of rows corresponding to the provided keys. Without an iteration limit, the iteration can continue for a long time if the provided keys are invalid or the corresponding rows are at the end of the dataset.
keyAttributes string | string[] The field name which stores the key in the data. Can be a string denoting a single key attribute or an array of strings for multiple key attributes.
textFilterAttributes string[] <optional>
Specify which attributes the filter should be applied on when a TextFilter filterCriteria is specified.
transforms RESTDataProvider.Transforms<K, D> Object which defines functions that transform the request when fetchFirst, fetchByOffset and fetchByKeys are called.
url string URL of the REST endpoint to fetch data from.

Transforms<K, D>

Properties:
Name Type Argument Description
fetchByKeys RESTDataProvider.FetchByKeysTransforms<K, D> <optional>
Object which specifies transforms for fetchByKeys calls
fetchByOffset RESTDataProvider.FetchByOffsetTransforms<K, D> <optional>
Object which specifies transforms for fetchByOffset calls
fetchFirst RESTDataProvider.FetchByOffsetTransforms<K, D> <optional>
Object which specifies transforms for fetchFirst calls