Class: Query

Query

Represents a subset of the data at a given node in the Webcom database.

By default, all data of the data node are included. Filter functions (Query#startAt, Query#endAt, Query#limit) may be chained to select a smaller subset of these data.

The Query#get, Query#on, Query#off functions make it possible to read, watch or unwatch the subset of data represented by this Query instance.

This class is abstract, instances of this class are built using the concrete Webcom sub-class or the filter functions.

Extends

Members

(static, constant) FORGET :number

Constant returned by a Query~completionCallback to require removing (forgetting) the data of the corresponding unwatched data node from the local cache.

Type:
  • number

(static, constant) KEEP :number

Constant returned by a Query~completionCallback to require keeping the data of the corresponding unwatched data node within the local cache.

Type:
  • number

(static, constant) KEEP_UPDATING :number

Constant returned by a Query~completionCallback to require keeping the data of the corresponding unwatched data node within the local cache, and keeping on updating them, even if the data node is no longer explicitly watched.

Type:
  • number

authenticator :AuthenticationService

Authentication service that manages this instance.

Type:
Overrides:

datasync :DatasyncService

Datasync service that manages this instance.

Type:
Overrides:

Methods

child(pathString) → {Webcom}

Gets a Webcom instance that refers to a specific data node within the application data tree, specified as a relative path to the data node referred to by this Query instance.

Parameters:
Name Type Description
pathString string

Data path, relative to the location of this Query instance:

  • It may include several segments separated by slashes ("/")
  • Path is always interpreted relatively to the current data node, even with a leading slash
  • Path-segments "." and ".." are interpreted as "same node" and "parent node". Warning: ".." on the root data node returns itself (and not null as the Query#parent method)
  • Path-segments starting with "#" or ".hash." generate hashed-paths, with 3 additional sub-levels, which make it possible to handle large lists of items (see Manage long lists)
  • Path-segments starting with ".list." give a hint to the Webcom back end that these nodes are intended to have many children (as a list) so that it optimises the individual retrieval of their children, preventing retrieving the nodes as a whole when the data of all their children become too big
Returns:

A Webcom instance that refers to the specified path.

Type
Webcom
Example
// Get a reference to the "friends" data node
var ref = new Webcom("contacts").child("friends");

var johnRef = ref.child("john");
console.log(johnRef.name());
// ==> "/https/io.datasync.orange.com/contacts//friends/john"

var maryRef = ref.child("/mary");
console.log(maryRef.toString());
// ==> "/https/io.datasync.orange.com/contacts//friends/mary"

var maryRef2 = johnRef.child("../mary");
console.log(maryRef2.toString());
// ==> "/https/io.datasync.orange.com/contacts//friends/mary"

var nameThenLastRef = johnRef.child("name").child("last");
console.log(nameThenLastRef.toString());
// ==> "/https/io.datasync.orange.com/contacts//friends/john/name/last"

var lastNameRef = johnRef.child("name/last");
console.log(lastNameRef.toString());
// ==> "/https/io.datasync.orange.com/contacts//friends/john/name/last"

var rootRef = ref.child("../..");
console.log(rootRef.toString());
// ==> "/https/io.datasync.orange.com/contacts/"

var hashedRef = ref.child("#john");
console.log(hashedRef.toString());
// ==> "/https/io.datasync.orange.com/contacts//friends/.list.pR/3a/fH/john"

endAt(nameopt) → {Query}

Creates a Query object that returns children beginning at a specific ending point.

Parameters:
Name Type Attributes Description
name string <optional>

The child name to end at

Since:
  • 2.2
Returns:
  • Generated query
Type
Query
Example
// Get a reference to friends
var ref = new Webcom("/base/contacts/friends");

// Display friends whose names (keys) come before john
ref.endAt("john").on("value", function(snapshot){
     console.log(snapshot.val());
});

equalTo(nameopt) → {Query}

Creates a Query object that returns children matching a specific value.

Parameters:
Name Type Attributes Description
name string <optional>

The child name to match for.

Since:
  • 2.2
Returns:
  • Generated query
Type
Query
Example
// Get a reference to friends
var ref = new Webcom("/base/contacts/friends");

// Display friends whose names (keys) is exactly john
ref.equalTo("john").on("value", function(snapshot){
     console.log(snapshot.val());
});

get() → {Promise.<DataSnapshot>}

Gets the data at the data node referred to by this Query instance.

This method works asynchronously. It will actually involve an exchange with the Webcom back end only if the requested data are not in the local cache.

Since:
  • 2.14
Returns:

A promise that will be resolved with the read data.

Type
Promise.<DataSnapshot>
Example
// Get a reference on the "friends" node of the "contacts" application
const friendsNode = new Webcom("contacts").child("friends");
// Read the value of this node
friendsNode.get()
    .then(data => {
        console.log("The 'friends' data are:", JSON.stringify(data.val()));
        console.log("They are", data.acknowledged() ? "acknowledged" : "not yet acknowledged", "by the back end");
    })
    .catch(error => console.log("Could not read data:", error.message);

getCache() → {DataSnapshot}

Returns (synchronously) the value stored in the local cache at the data node represented by this Query instance. The returned value is of the same type than the one passed to watch callbacks.

Since:
  • 2.15
Returns:
Type
DataSnapshot

limit(lim) → {Query}

Create Query object to limit the number of children.

Parameters:
Name Type Description
lim number

Number of items

Since:
  • 2.2
Returns:

new limited Query object.

Type
Query
Examples

Last

// Get a reference to friends
var ref = new Webcom("/base/contacts/friends");

var lastFriends = ref.endAt().limit(5);
// Display the 5 last friends
lastFriends.on("value", function(snapshot){
     console.log(snapshot.val());
});

First

// Get a reference to friends
var ref = new Webcom("/base/contacts/friends");

var lastFriends = ref.startAt().limit(5);
// Display the 5 first friends
lastFriends.on("value", function(snapshot){
     console.log(snapshot.val());
});

First starting at some key

// Get a reference to friends
var ref = new Webcom("/base/contacts/friends");

var lastFriends = ref.startAt("john").limit(5);
// Display friends whose names (keys) come after john display the following 5
lastFriends.on("value", function(snapshot){
     console.log(snapshot.val());
});

name() → (nullable) {string}

Returns the name of the data node this Query instance refers to.

Returns:

The name of the data node or null if this instance refers to the root node of the application.

Type
string
Example
// Get a reference to the "john" data node
var ref = new Webcom("contacts").child("friends/john");

console.log(ref.name());
// ==> "john"

console.log(ref.child("name").name());
// ==> "name"

console.log(ref.root().name());
// ==> null

off(eventTypesopt, callbackopt, contextopt)

Unwatches data changes at the data node referred to by this Query instance.

It actually unregisters a callback function (or all ones) previously registered on the data node referred to by this Query instance using the Query#on method.

As a side effect, all data previously watched will be removed from the local cache. If you want to keep these data in the local cache in order to work offline for example, use the Query#offPreservingOfflineData method instead.

Note: unregistering all callback functions attached to a data node doesn't unregister callback functions attached to its child nodes. The Query#off method must be called on all the data nodes that the Query#on method has been called on.

Parameters:
Name Type Attributes Description
eventTypes string | Array.<string> <optional>

The type of event to unwatch. It can be either a single value among "value", "child_added", "child_changed" or "child_removed", or a list of them.
If not specified, all callbacks previously registered on the data node are unregistered.

callback Query~watchCallback <optional>

Reference to the callback function to unregister (previously passed to or returned by the Query#on method).
If not set, all callbacks of type eventTypes previously registered on the data node are unregistered.

context Object <optional>

Context object for callback binding, passed to previous call to Query#on.

Examples

Unregister a single callback

// Get a reference to the "friends" node of the "contacts" application
var ref = new Webcom("contacts").child("friends");

var onChange = ref.on("value", function(snapshot) {
  // your handler
});

// later...
ref.off("value", onChange);

Unregister several callbacks

// Get a reference to the "friends" node of the "contacts" application
var ref = new Webcom("contacts").child("friends");

var onChanged = function(snapshot) {
  // your first handler
});
var onAdded = function(snapshot) {
  // your second handler
});

ref.on("value", onChanged);
ref.on("child_added", onAdded);

// later...

// Unregister all callback functions from ref...
ref.off();
// ...or all callback function associated to a specific kind of event
ref.off("value"); // onChanged is unregistered while onAdded remains registered

offPreservingOfflineData(eventTypeopt, callbackopt, contextopt)

Unwatches data changes at the data node referred to by this Query instance, similarly to the Query#off method. The difference is that this method additionally preserves the previously watched data within the local cache and maintains them up-to-date.

As a consequence, unwatched data remain available if the network becomes down, and it is possible to use them offline. As soon as the network becomes up, they will be automatically re-synchronised.

In order to definitely remove some unwatched data from the local cache, use the DatasyncService#cleanOfflineData method.

Parameters:
Name Type Attributes Description
eventType string | Array.<string> <optional>

The type of event to unwatch. It can be either a single value among "value", "child_added", "child_changed" or "child_removed", or a list of values among the same constants.
If not specified, all callbacks previously registered on the data node are unregistered.

callback Query~watchCallback <optional>

Reference to the callback function to unregister (previously passed to or returned by the Query#on method).
If not set, all callbacks of type eventType previously registered on the data node are unregistered.

context Object <optional>

Context object for callback binding, passed to previous call to Query#on.

Since:
  • 2.11
Deprecated:

on(eventTypes, callback, completionCallbackopt, contextopt) → {Query~watchCallback}

Watches data changes at the data node referred to by this Query instance.

It actually registers a callback function on the data node referred to by this Query instance for a given type of event to watch or a given set of types of events to watch.

The specified callback may be called initially (when the on method is called) with respect to the data currently stored at this node (depending on the requested event type). And then, it will be called whenever the data change. The notifications can be stopped using the Query#off method.
Several kinds of callback are available depending on the kind of event to watch:

  • value event

    The callback is called initially once with the current data.
    It is then called again each time the data (stored a this node or any sub-node) change.

    The DataSnapshot passed to the callback refers to the new data stored at the data node referred to by this Query instance.
    The prevChildName argument passed to the callback is not used and remains undefined.

  • value_ack event

    The callback is not initially called.
    It is then called each time the value at this data node is acknowledged by the Webcom back end. Note that if both the value and the acknowledgement status change, then the value event is raised instead.

    As with the value event, the DataSnapshot passed to the callback refers to the value of the data node and the prevChildName is not used.

  • child_added event

    The callback is called initially once for each current child node of this node.
    It is then called again each time a new data child is added to this node.

    The DataSnapshot passed to the callback refers to the new data stored at the corresponding child data node.
    The prevChildName argument passed to the callback refers to the name of the sibling child node that precedes the added child node in the data tree structure (following key order), or null if the added child node is the first child of the data node referred to by this Query instance.

  • child_changed event

    The callback is not initially called.
    It is then called each time the value of one of the data children changes (excluding child additions and removals).

    The DataSnapshot passed to the callback refers to the new data stored at the corresponding child data node.
    The prevChildName argument passed to the callback refers to the name of the sibling child node that precedes the changed child node in the data tree structure (following key order), or null if the changed child node is the first child of the data node referred to by this Query instance.

  • child_removed event

    The callback is not initially called.
    It is then called each time one of the data children is removed (or its value becomes null or it loses all of its children).

    The DataSnapshot passed to the callback refers to the old data stored at the corresponding child data node.
    The prevChildName argument passed to the callback is not used and remains undefined.

  • child_ack event

    The callback is not initially called.
    It is then called the value of a child of this data node is acknowledged by the Webcom back end. Note that if both the value and the acknowledgement status of the child change, then one of the child_added, child_removed or child_changed events is raised instead.

    The DataSnapshot passed to the callback refers to the value of the child node.
    The prevChildName argument passed to the callback is not used and remains undefined.

Note: data is first synchronized locally, so that if you set (using the set() method) some data locally after registering a watch callback, this callback will be called immediately. Later, when the synchronization with the server occurs, the callback will be possibly called again for acknowledgement notification, data update, or even for data deletion if the synchronization fails.

Parameters:
Name Type Attributes Description
eventTypes string | Array.<string>

The type of event to watch. It can be either a single value among "value", "value_ack", "child_added", "child_changed", "child_removed" or "child_ack", or a list of values among these constants.

callback Query~watchCallback

Callback function called when one of the watched events is raised.

completionCallback Query~completionCallback <optional>

Callback function called when the data node is no longer watched. This can result from either a cancelation from the app (by calling the Query#off method) or a revocation from the Webcom back end due to a permission loss (either the token of the authenticated user has expired or the security rules have denied the read permission). In case of cancelation, the callback is called with null, in case of revocation it is called with an Error object. In addition, the value returned by this callback controls how the corresponding data in the local cache is kept or deleted.
Note 1: In both cases, the watch callback function is automatically unregistered and will no longer be called.
Note 2: the completionCallback is called for a cancelation only if the underlying Webcom instance has been constructed with the DatasyncService.completeSubscriptionOnCancelation option set to true.

context Object <optional>

Context object for binding of the callback functions

Returns:

A reference to the callback function provided in the callback parameter. It is intended to be passed to the Query#off method, especially when the callback parameter is given as an inline function.

Type
Query~watchCallback
Examples

Value

// Get a reference to the "friends" node of the "contacts" application
var ref = new Webcom("contacts").child("friends");

// This callback is called only when some data change under the "friends" node
ref.on("value", function(snapshot) {
  console.log("New friends value is: " + JSON.stringify(snapshot.val()));
});

Child Added

// Get a reference to the "friends" node of the "contacts" application
var ref = new Webcom("contacts").child("friends");

// This callback is called only when a new child is added to the "friends" node
ref.on("child_added", function(snapshot, prevChildName) {
  console.log("New child for friends: " + snapshot.name() + " -> " + JSON.stringify(snapshot.val()));
  if (prevChildName) {
    console.log("This new child comes after " + prevChildName);
  } else {
    console.log("This new child is the only one");
  }
});

Child Changed

// Get a reference to the "friends" node of the "contacts" application
var ref = new Webcom("contacts").child("friends");

// This callback is called only when the value of an existing child of the "friends" node changes
ref.on("child_changed", function(snapshot, prevChildName) {
  console.log("The " + snapshot.name() + " child has changed value to: " + JSON.stringify(snapshot.val()));
  if (prevChildName) {
    console.log("This child comes after " + prevChildName);
  } else {
    console.log("This child is the only one");
  }
});

Child Removed

// Get a reference to the "friends" node of the "contacts" application
var ref = new Webcom("contacts").child("friends");

// This callback is called only when a child of the "friends" node is removed
ref.on("child_removed", function(snapshot) {
  console.log("The " + snapshot.name() + " child has been removed, its value was: " +
    JSON.stringify(snapshot.val()));
});

once(eventType, callback, cancelCallbackopt, contextopt)

Watches the next data change at the data node referred to by this Query instance.

This method is similar to Query#on, except it automatically unregisters the given callback function from the data node referred to by this Query instance as soon as it is called. In other words, the given callback function will be called no more than once.

With the "value" event type, this method makes it possible to read (asynchronously) the data stored at a given data node. Other event types are useless with this method.

Parameters:
Name Type Attributes Description
eventType string

The type of event to watch. Although the same event types as for the Query#on method are available, on the "value" one is really useful.

callback Query~watchCallback

Callback function called when the specified event occurs.

cancelCallback Query~completionCallback <optional>

Callback function called when the authenticated user loses read permission at the data node referred to by this Query instance. In this case, the watch callback function is automatically unregistered and will no longer be called.

context Object <optional>

Context object for callback binding

Deprecated:
Examples
// Get a reference to the "friends" node of the "contacts" application
var ref = new Webcom("contacts").child("friends");

// Read the value of the "friends" node
ref.once("value", function(snapshot) {
  console.log("The value of the " + snapshot.name() + " node is: " + JSON.stringify(snapshot.val()));
});
// Get a reference to the "friends" node of the "contacts" application
var ref = new Webcom("contacts").child("friends");

// Check the read permission on the "friends" node
ref.once("value", function() {}, function(error) {
  console.log("Insufficient read permission");
});

parent() → {Webcom}

Gets a Webcom instance that refers to the parent data node of the one referred to by this Query instance.

Returns:

A parent instance of this Query instance or null if the data node referred to by this Query instance has no parent.

Type
Webcom
Example
// Get a reference to the "friends" data node
var ref = new Webcom("contacts").child("friends");

var contactsRef = ref.parent();
console.log(contactsRef.toString());
// ==> "/https/io.datasync.orange.com/contacts/"

pathString() → {String}

Returns the path of the data node represented by this instance of Query.

Since:
  • 2.6.2
Returns:

The path of this data node, with path levels separated by "/" (slashes)

Type
String

ref() → {Webcom}

Returns a Webcom reference associated to the data node referred to by this Query instance.

Returns:

The Webcom reference associated with this instance.

Type
Webcom
Example
// Get a reference to the "friends" data node
var ref = new Webcom("contacts").child("friends");

var query = ref.limit(2);
var refSameLocation = query.ref(); //ref === refSameLocation

root() → {Webcom}

Gets a Webcom instance that refers to the data tree root of current Webcom application.

Returns:

A Webcom instance that refers to the root data node

Type
Webcom
Example
// Get a reference to the "john" data node
var ref = new Webcom("contacts").child("friends/john");

var rootRef = ref.root();
console.log(rootRef.toString());
// ==> "/https/io.datasync.orange.com/contacts/"

startAt(nameopt, nullable) → {Query}

Creates Query object that returns children beginning at a specific starting point.

Parameters:
Name Type Attributes Description
name string <optional>
<nullable>

The child name to start at. If omitted or null, the query iterate items from the upper ones in key order.

Since:
  • 2.2
Returns:

Generated query

Type
Query
Example
// Get a reference to friends
var ref = new Webcom("/base/contacts/friends");

// Display friends whose names (keys) come after john
ref.startAt("john").on("value", function(snapshot){
     console.log(snapshot.val());
});

Type Definitions

completionCallback(errornullable) → {number}

A callback function fired when a subscription is competed by either cancelation from the app itself (in this case the error parameter is passed null) or revocation from the Webcom back end because of permission loss. In addition, when the DatasyncService.completeSubscriptionOnCancelation option is set to true, the return value of this callback controls how the previously watched data is kept within or removed from the local cache for further offline availability.

Parameters:
Name Type Attributes Description
error Error <nullable>

null for a subscription cancelation, or an Error object for a revocation (which describes the reason of the revocation).

See:
Returns:

the data preservation policy among: Query.FORGET (default if the callback returns nothing - the previously watched data is removed from the local cache), Query.KEEP (the previously watched data is kept within the local cache) or Query.KEEP_UPDATING (the previously watched data is kept within the local cache and becomes watched in background outside any subscription to keep being updated in real time)

Type
number

watchCallback(snapshot, prevChildNameopt, nullable)

A callback function fired when a watched data event occurs.

Parameters:
Name Type Attributes Description
snapshot DataSnapshot

Snapshot data associated with the event.

prevChildName string <optional>
<nullable>

Name of the previous sibling child depending on key order, or null for an only child.
This parameter is valued only for the "child_added" and "child_changed" event types, otherwise it remains undefined.

See:
show
deprecated