Final Class: RESTDataProvider

Oracle® JavaScript Extension Toolkit (JET)
11.0.0

F37993-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.

See the RESTDataProvider demos for examples.

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, totalSzie, 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 avaialbe, 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.
Parameters:
Name Type Description
parameters FetchByKeysParameters fetch by key parameters
Since:
  • 4.2.0
Returns:
Returns Promise which resolves to FetchByKeysResults.
Type
Promise.<FetchByKeysResults>
Example

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);

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

Fetch rows by offset

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
Since:
  • 4.2.0
Returns:
Returns Promise which resolves to FetchByOffsetResults.
Type
Promise.<FetchByOffsetResults>
Example

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'];
});

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

Get an AsyncIterable object for iterating the data.

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
Since:
  • 4.2.0
See:
Returns:
AsyncIterable with FetchListResult
Type
AsyncIterable.<FetchListResult>
Example

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;

getCapability(capabilityName: string): any

Determines whether this DataProvider defines a certain feature.
Parameters:
Name Type Description
capabilityName string capability name. Defined capability names are: "fetchByKeys", "fetchByOffset", "sort", "fetchCapability" and "filter".
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

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
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.
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 ared 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