Final Class: RESTTreeDataProvider

Oracle® JavaScript Extension Toolkit (JET)
11.1.0

F37999-01

Since:
  • 11.1.0
Module:
  • ojresttreedataprovider

QuickNav

Description

This class implements TreeDataProvider and is used to represent hierachical data from a JSON-based REST service. RESTTreeDataProvider is based on RESTDataProvider so if you are not familiar with it, we strongly encourage you to review its documentation and demos before proceeding.

For a given set of hierarchical data, a collection of RESTTreeDataProvider's are responsible for loading data at each level. Take the following example used in the RESTTreeDataProvider demos:

News
Blogs/
  Today
  Yesterday
  Archive
Links/
  Oracle/
    USA/
      Northeast
      Midwest
      South
      West
    Europe
    Asia/
      Japan
      China
      India
  IBM
  Microsoft


The top level RESTTreeDataProvider is responsible for only loading the nodes corresponding to "News", "Blogs" and "Links". The child RESTTreeDataProvider of the node corresponding to "Blogs" is responsible for loading "Today", "Yesterday" and "Archive" and so on.

Child data providers are created via a constructor option called getChildDataProvider. The option is a function which is invoked by the instance's getChildDataProvider method. It takes an Item corresponding to the provided parentKey and returns a DataProvider instance that will load the children of the corresponding node or null if the node cannot have children (i.e. is a leaf). The Item passed to getChildDataProvider has two fields: data which contains the node and metadata which contains the node's metadata. The metadata field can be populated from your application's server via the fetch response transform (which also supports returning data, keys, hasMore, and totalSize) with useful data for use in getChildDataProvider. Such data could include a boolen field such as "leaf" which indicates whether a node is a leaf, for example.

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 RESTTreeDataProvider<K, D> implements TreeDataProvider<K, D>

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

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 RESTTreeDataProvider(options)

Parameters:
Name Type Description
options RESTTreeDataProvider.Options.<K, D> options for the RESTTreeDataProvider

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
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 containsKeys = [1001, 556];
let value = await dataprovider.containsKeys({keys: containsKeys});
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

let keyMap = dataprovider.createOptimizedKeyMap();

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

let keySet = dataprovider.createOptimizedKeySet();

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
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 fetchKeys = [1001, 556];
let value = await dataprovider.fetchByKeys({keys: fetchKeys});
// 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;
});

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

getChildDataProvider(parentKey: K): TreeDataProvider<K, D> | null

Get the data provider for the children of the row identified by parentKey.
Parameters:
Name Type Description
parentKey any key of the row to get child data provider for.
Since:
  • 5.1.0
Returns:
A TreeDataProvider if the row can (but doesn't have to) have children; or null if the row cannot have children. Use the isEmpty method on the returned TreeDataProvider to determine if it currently has children.
Type
TreeDataProvider | null

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. RESTTreeDataProvider 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.1.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.1.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 RESTTreeDataProvider.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: RESTTreeDataProvider.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 RESTTreeDataProvider.FetchByKeysRequestTransform<K> <optional>
Object which specifies request transforms
response RESTTreeDataProvider.FetchResponseTransform<K, D> <optional>
Object which specifies response transforms

FetchByOffsetRequestTransform<K, D>

Signature:

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

FetchByOffsetRequestTransformOptions<K, D>

Properties:
Name Type Description
fetchOptions { textFilterAttributes?: RESTTreeDataProvider.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 RESTTreeDataProvider.FetchByOffsetRequestTransform<K, D> <optional>
Object which specifies request transforms
response RESTTreeDataProvider.FetchResponseTransform<K, D> <optional>
Object which specifies response transforms

FetchResponseTransform<K, D>

Signature:

(options: RESTTreeDataProvider.FetchResponseTransformOptions) => Promise<RESTTreeDataProvider.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 RESTTreeDataProvider instance based on the REST service is fetches data from.
getChildDataProvider (item: Item<K, D>) => DataProvider<K, D> | null Function that creates a DataProvider that will fetch the children of the node identified by "item". If the node does not exist or cannot have children, null should be returned. If the data provider returned is not a TreeDataProvider, RESTTreeDataProvider will wrap it in simple TreeDataProvider implementation whose getChildDataProvider method always returns null.
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 RESTTreeDataProvider 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.
rootDataProvider RESTTreeDataProvider.<K, D> <optional>
Root RESTDataTreeDataProvider that fetches the top-level data in the hierarchy. RESTTreeDataProvider's created by getChildDataProvider are required to specify this option.
textFilterAttributes string[] <optional>
Specify which attributes the filter should be applied on when a TextFilter filterCriteria is specified.
transforms RESTTreeDataProvider.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 RESTTreeDataProvider.FetchByKeysTransforms<K, D> <optional>
Object which specifies transforms for fetchByKeys calls
fetchByOffset RESTTreeDataProvider.FetchByOffsetTransforms<K, D> <optional>
Object which specifies transforms for fetchByOffset calls
fetchFirst RESTTreeDataProvider.FetchByOffsetTransforms<K, D> <optional>
Object which specifies transforms for fetchFirst calls