Skip to content

Realtime

YYBartT edited this page Aug 29, 2024 · 6 revisions

Realtime Database

The Firebase Realtime Database is a cloud-hosted database. Data in the Realtime Database is stored as JSON and synchronized in real time to every connected client. When you build cross-platform apps with the iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database instance and automatically receive updates with the newest data. Check the official page for more information.

Setup

Before starting to use any Firebase extensions, you are required to follow some initial configuration steps.

Note

The SDK version is only available for the Android, iOS and Web targets; if you're targeting other devices, please follow the steps for REST API.

Functions

The Firebase Realtime Database extension was implemented using a fluent-API (method chaining) approach and the entry point for interacting with the database is using the function FirebaseRealTime, which will return a dbEntryRef of the database. The following functions are given for working with Firebase Firestore extension:

Filter Functions

The functions given below should only be used for filtering data when reading from the database using the Read() function given above.

Structs

This module offers a collection of structs, which serve as custom data models for organizing and structuring data. Explore the provided structs to better understand the relationships between data elements and simplify your data manipulation tasks.



Back To Top

FirebaseRealTime

This function is the entry point for database interactions using the Firebase Realtime Database extension. It returns a < dbEntryRef > that can be further modified and configured using chained methods.

Note

The Firebase Realtime Database implements a fluent-API meaning almost all functions return self allowing them to be chained and for you to build complex database interactions while keeping the code clean and easy to follow. Entries in the database are structs and are referred to in this documentation as dbEntryRef:: ** These, under the hood, are structs that point to a specific path in the database (they are NOT the actual entry).


Syntax:

FirebaseRealTime(database=undefined)
Argument Type Description
database String Overwrite the default database



Returns:

dbEntryRef


Example:

// 1) This will use the default database
FirebaseRealTime().Path("players/hero/hp").Set(100);

// 2) This will use a custom database url
FirebaseRealTime(dbUrl).Path("players/hero/hp").Set(100);

Above we have two database interaction examples. In the first one we create a reference to a database entry ("players/hero/hp", using the chained method <dbEntryRef>.Path and afterwards we set that entry to the value 100 (using the method <dbEntryRef>.Set). The second example is very similar but we pass in a specific database URL (dbUrl) to the main function call; this is very powerful and allows the developer to have access as many different databases as needed.




Back To Top

<dbEntryRef>.Listener

The method listens for changes to a given entry in the database. If you need to stop listening to changes you can use <dbEntryRef>.ListenerRemove for a specific database reference or <dbEntryRef>.ListenerRemoveAll to remove all listeners.

Warning

When you no longer need to listen to changes make sure to remove the listeners, as not doing so can lead to memory leaks.

This function operates asynchronously, which means that it does not immediately return the requested result. Instead, upon completion of the task, it will trigger the Social Async Event.


Syntax:

<dbEntryRef>.Listener()



Returns:

Real


Triggers:

Social Async Event

Key Type Description
type String The string "FirebaseRealTime_Listener"
listener Real The asynchronous listener ID.
path String The path of the database reference.
status Real The HTTP status response code (see reference)
value Real or String or Struct The new value of the entry
errorMessage String The readable error message

Example:

listenerId = FirebaseRealTime("players/hero").Listener();

The code above starts listening for updates on the database entry ("player/hero"). If this reference gets updated, set or deleted an async event will be triggered. The function call will return a listener ID (listenerId) that can be used inside a Social Async Event.

if (async_load[? "type"] == "FirebaseRealTime_Listener")
{
    if (async_load[? "status"] == 200)
    {
        show_debug_message("Changes were made to this entry");
    }
    else
    {
        var _errorMessage = async_load[? "errorMessage"];
    }
}

The code above matches the response against the correct event type and logs when changes are made to the database reference being listened to.




Back To Top

<dbEntryRef>.Exists

This method checks if a reference exists on the database and returns a listener identifier for tracking purposes.

This function operates asynchronously, which means that it does not immediately return the requested result. Instead, upon completion of the task, it will trigger the Social Async Event.


Syntax:

<dbEntryRef>.Exists()



Returns:

Real


Triggers:

Social Async Event

Key Type Description
type String The string "FirebaseRealTime_Exists"
listener Real The asynchronous listener ID.
path String The path of the database reference.
status Real The HTTP status response code (see reference)
values Boolean Whether or not the database path exists.
errorMessage String The readable error message.

Example:

listenerId = FirebaseRealTime().Path("myCollection/oldDoc").Exists();

In the code above we first get the reference to a database path ("myCollection/oldDoc", using the function <dbEntryRef>.Path) and check if that entry exists in our database. The function call will then return a listener ID (listenerId) that can be used inside a Social Async Event.

if (async_load[? "type"] == "FirebaseRealTime_Exists")
{
    if (async_load[? "status"] == 200 && async_load[? "values"])
    {
        show_debug_message("Database entry exists.");
    }
    else
    {
        var _errorMessage = async_load[?"errorMessage"];
    }
}

The code above matches the response against the correct event type, providing a success message if the entry exists in the database.




Back To Top

<dbEntryRef>.Delete

This method deletes a reference on the database and returns a listener identifier for tracking purposes.

This function operates asynchronously, which means that it does not immediately return the requested result. Instead, upon completion of the task, it will trigger the Social Async Event.


Syntax:

<dbEntryRef>.Delete()



Returns:

Real


Triggers:

Social Async Event

Key Type Description
type String The string "FirebaseRealTime_Delete"
listener Real The asynchronous listener ID.
path String The path of the database reference.
status Real The HTTP status response code (see reference)
errorMessage String The readable error message

Example:

listenerId = FirebaseRealTime().Path("myCollection/oldDoc").Delete();

In the code above we first get the reference to a database path ("myCollection/oldDoc", using the method <dbEntryRef>.Path) and then delete that entry. The function call will then return a listener ID (listenerId) that can be used inside a Social Async Event.

if (async_load[? "type"] == "FirebaseRealTime_Delete")
{
    if (async_load[? "status"] == 200)
    {
        show_debug_message("Database entry was successfully deleted.");
    }
    else
    {
        var _errorMessage = async_load[?"errorMessage"];
    }
}

The code above matches the response against the correct event type, providing a success message if status is valid.




Back To Top

<dbEntryRef>.ListenerRemove

This method removes a previously created listener (that was created using the function <dbEntryRef>.Listener).

Tip

If you wish to remove all created listeners use the function <dbEntryRef>.ListenerRemoveAll instead.


Syntax:

<dbEntryRef>.ListenerRemove(listenerId)
Argument Type Description
listenerId Real The listener Id to be removed.



Returns:

N/A


Example:

listenerId = FirebaseRealTime("players/hero").Listener();

// Some time later

FirebaseRealTime().ListenerRemove(listenerId);

The code sample above starts by creating a listener to a database entry reference (using the <dbEntryRef>.Listener method). This function returns a listener ID (listenerId) and at a later stage we use that ID to remove the listener.




Back To Top

<dbEntryRef>.ListenerRemoveAll

This method removes all previously created listeners (that were created using the function <dbEntryRef>.Listener).

Tip

If you wish to remove a specific listener use the <dbEntryRef>.ListenerRemove instead.


Syntax:

<dbEntryRef>.ListenerRemoveAll()



Returns:

N/A


Example:

listenerId1 = FirebaseRealTime().Path("players/hero").Listener();
listenerId2 = FirebaseRealTime().Path("players/knight").Listener();

// Some time later
FirebaseRealTime().ListenerRemoveAll();

The code above creates two listeners (using the <dbEntryRef>.Listener function) on different database entries (using the <dbEntryRef>.Path method) and after some time it removes them all.




Back To Top

<dbEntryRef>.Path

This method attaches a path reference to the current database's <dbEntryRef>.

Note

Paths are a representation of references in the database (i.e.: the path to get "Opera X YoYoGames" is "Testing/String").


Syntax:

<dbEntryRef>.Path(path)
Argument Type Description
path String The path reference to the database entry.



Returns:

dbEntryRef


Example:

FirebaseRealTime().Path("Testing/String").Read();

The code above first creates the reference to a database entry ("Testing/String") and then reads that entry (using the <dbEntryRef>.Read method).




Back To Top

<dbEntryRef>.Child

This method appends the given relatives path to the current path of a Realtime Database <dbEntryRef> struct.


Syntax:

<dbEntryRef>.Child(path)
Argument Type Description
path String Relative child path



Returns:

dbEntryRef


Example:

var _parentNode = "characters/player";
var _nodeRef = FirebaseRealTime().Path(_parentNode).Child("health");

The code sample above will create a <dbNodeRef> to the "characters/player" path (using the <dbEntryRef>.Path method) and afterwards append the relative path "health" to it, meaning the resulting reference (nodeRef) now points to the "characters/player/health" path.




Back To Top

<dbEntryRef>.Parent

This method goes up the hierarchy to the parent path of the current <dbEntryRef> struct.


Syntax:

<dbEntryRef>.Parent()



Returns:

dbEntryRef


Example:

var _dbPath = "players/hero/name";
var _dbEntryRef = FirebaseRealTime().Path(dbPath).Parent().Child("magic").Set(99);

The code above creates a <dbEntryRef> to the "players/hero/name" path (using the <dbEntryRef>.Path function) and afterwards goes up to the parent path meaning the resulting reference (dbEntryRef) now points to the "players/hero" path. We then go into the child database entry (using the <dbEntryRef>.Child method) and finally set this new reference ("players/hero/magic") to the value 99 (using the <dbEntryRef>.Set method).




Back To Top

<dbEntryRef>.Push

This method is useful for storing arrays inside the database. Database elements can be of type string , real or struct , meaning that arrays are not a valid type within a Firebase Realtime Database. This method attaches an auto-generated child location to the current database entry reference.

In this image below we can see the auto-generated keys in "Testing/List".


Syntax:

<dbEntryRef>.Push()



Returns:

dbEntryRef


Example:

var _data = { health: 100, magic: 99 };
var _jsonData = json_stringify(_data);

FirebaseRealTime().Path("Enemies/List").Push().Set(_jsonData);

The code above first creates the reference to a database entry ("Enemies/List", using the <dbEntryRef>.Path method) and then pushes a new auto-generated key into that reference (this is what emulates arrays/collections). Finally it sets that database entry with the previously created data (using the <dbEntryRef>.Set method).




Back To Top

<dbEntryRef>.Read

This method reads the current database reference and returns a listener identifier.

This function operates asynchronously, which means that it does not immediately return the requested result. Instead, upon completion of the task, it will trigger the Social Async Event.


Syntax:

<dbEntryRef>.Read()



Returns:

Real


Triggers:

Social Async Event

Key Type Description
type String The string "FirebaseRealTime_Read"
listener Real The asynchronous listener ID.
path String The path of the database reference.
status Real The HTTP status response code (see reference)
value Real or String or Struct The value being read
errorMessage String The readable error message

Example:

listenerId = FirebaseRealTime().Path("players/hero").Read();

The code above first gets the reference to a database entry ("players/hero", using the <dbEntryRef>.Path method) and then reads that entry. The function call will then return a listener ID (listenerId) that can be used inside a Social Async Event.

if (async_load[? "type"] == "FirebaseRealTime_Read")
{
    if (async_load[? "status"] == 200)
    {
        show_debug_message("The entry data is: " + async_load[? "value"]);
    }
    else
    {
        var _errorMessage = async_load[?"errorMessage"];
    }
}

The code above matches the response against the correct event type, providing the document data if the task succeeded.




Back To Top

<dbEntryRef>.Set

This method creates or overwrites a database entry value of type real , string , or struct (arrays are not a valid type) and returns a listener ID to be used for tracking purposes.

Tip

It's also possible to add a time-stamp value to the database entry if you set it to { .sv: "timestamp" } (example below).

This function operates asynchronously, which means that it does not immediately return the requested result. Instead, upon completion of the task, it will trigger the Social Async Event.


Syntax:

<dbEntryRef>.Set(value)
Argument Type Description
value Real or String or Struct The data to be set within the current database entry.



Returns:

Real


Triggers:

Social Async Event

Key Type Description
type String The string "FirebaseRealTime_Set"
listener Real The asynchronous listener ID.
path String The path of the database reference.
status Real The HTTP status response code (see reference)
errorMessage String The readable error message

Example:

// (1) Set value using a real
listenerId = FirebaseRealTime().Path("enemies/bat/health").Set(999);

// (2) Set value using a string
listenerId = FirebaseRealTime().Path("enemies/bat/name").Set("Monster");

// (3) Set value using a struct
var _data = { health: 100, magic: 99 };
listenerId = FirebaseRealTime().Path("enemies/bat").Set(_data);

// (4) Time stamps
var _data = {};
_data[$ ".sv"] = "timestamp";
listenerId = FirebaseRealTime().Path("enemies/bat/timestamp").Set(_data);

The code sample above provides three example for setting values in a database entry using a real , a string and a struct (a timestamp example is also provided). The function call will then return a listener ID (listenerId) that can be used inside a Social Async Event.

if (async_load[? "type"] == "FirebaseRealTime_Set")
{
    if (async_load[? "status"] == 200)
    {
        show_debug_message(".Set() function call succeeded!");
    }
    else
    {
        var _errorMessage = async_load[? "errorMessage"];
    }
}

The code above matches the response against the correct event type and logs the success of the task.




Back To Top

<dbEntryRef>.LimitToFirst

This function is a filter that should be used when performing a <dbEntryRef>.Read operation or creating <dbEntryRef>.Listener that is ordered in some way (see <dbEntryRef>.OrderByChild, <dbEntryRef>.OrderByKey and <dbEntryRef>.OrderByValue). The filter assures that the returned results stop after the first amount elements.

Note

This method will filter elements from the start of the ordered group; if you want to read from the end, use <dbEntryRef>.LimitToLast instead.


Syntax:

<dbEntryRef>.LimitToFirst(amount)
Argument Type Description
amount Real The number of results to read (from the start)



Returns:

dbEntryRef


Example:

listenerId = FirebaseRealTime().Path("players/healthList").OrderByValue().LimitToFirst(5).Read();

The code above performs a read operation (using the <dbEntryRef>.Read method) on the database reference "players/healthList" (using the <dbEntryRef>.Path method) ordered by the value (using the <dbEntryRef>.OrderByValue method), returning only the first 5 results.




Back To Top

<dbEntryRef>.OrderByChild

This method should be used when performing a <dbEntryRef>.Read operation or creating a <dbEntryRef>.Listener, and orders the returned results by a child field path so they can be then filtered using one of the filtering methods (see <dbEntryRef>.StartAt, <dbEntryRef>.EndAt, <dbEntryRef>.EqualTo, <dbEntryRef>.LimitToFirst and<dbEntryRef>.LimitToLast).

Note

The final result from the Read() call will not be sorted; the sort order is only used by any filter methods chained after this.


Syntax:

<dbEntryRef>.OrderByChild(path)
Argument Type Description
path Real The path to the specified field to sort the values by.



Returns:

dbEntryRef


Example:

listenerId = FirebaseRealTime().Path("enemies").OrderByChild("points").LimitToLast(5).Read();

The code above performs a read operation (using the <dbEntryRef>.Read method) on the database reference "enemies" (using the <dbEntryRef>.Path method) ordered by the children "points", returning only the last 5 results (using the<dbEntryRef>.LimitToLast method).




Back To Top

<dbEntryRef>.EqualTo

This function is a filter that should be used when performing a <dbEntryRef>.Read operation or creating <dbEntryRef>.Listener that is ordered in some way (see <dbEntryRef>.OrderByChild, <dbEntryRef>.OrderByKey and <dbEntryRef>.OrderByValue). The filter assures that the returned results have a specific value.


Syntax:

<dbEntryRef>.EqualTo(value)
Argument Type Description
value Real or String The value to equal to.



Returns:

dbEntryRef


Example:

listenerId = FirebaseRealTime().Path("players/healthList").OrderByValue().EqualTo(77).Read();

The code above performs a read operation (using the <dbEntryRef>.Read method) on the database reference "players/healthList" (using the <dbEntryRef>.Path method) ordered by the value (using the <dbEntryRef>.OrderByValue method), returning only values that are equal to 77.




Back To Top

<dbEntryRef>.StartAt

This function is a filter that should be used when performing a <dbEntryRef>.Read operation or creating a <dbEntryRef>.Listener that is ordered in some way (see <dbEntryRef>.OrderByChild, <dbEntryRef>.OrderByKey and <dbEntryRef>.OrderByValue). The filter assures that the returned results start at a specific value.


Syntax:

<dbEntryRef>.StartAt(value)
Argument Type Description
value Real or String The value to start the query at.



Returns:

dbEntryRef


Example:

listenerId = FirebaseRealTime().Path("players/healthList").OrderByValue().StartAt(10).Read();

The code above performs a read operation (using the <dbEntryRef>.Read method) on the database reference "players/healthList" (using the <dbEntryRef>.Path method) ordered by the value (using the <dbEntryRef>.OrderByValue method), returning only those values that are above or equal to 10.




Back To Top

<dbEntryRef>.EndAt

This function is a filter that should be used when performing a <dbEntryRef>.Read operation or creating <dbEntryRef>.Listener that is ordered in some way (see <dbEntryRef>.OrderByChild, <dbEntryRef>.OrderByKey and <dbEntryRef>.OrderByValue). The filter assures that the returned results stop at a specific value.


Syntax:

<dbEntryRef>.EndAt(value)
Argument Type Description
value Real or String The value to stop the query at.



Returns:

dbEntryRef


Example:

listenerId = FirebaseRealTime().Path("players/healthList").OrderByValue().EndAt(99).Read();

The code above performs a read operation (using the <dbEntryRef>.Read method) on the database reference "players/healthList" (using the <dbEntryRef>.Path method) ordered by the value (using the <dbEntryRef>.OrderByValue method), returning only values below or equal to 99.




Back To Top

<dbEntryRef>.LimitToLast

This function is a filter that should be used when performing a <dbEntryRef>.Read operation or creating <dbEntryRef>.Listener that is ordered in some way (see <dbEntryRef>.OrderByChild, <dbEntryRef>.OrderByKey and <dbEntryRef>.OrderByValue). The filter assures that the returned results are the last amount of elements.

Note

This method will filter elements from the end of the ordered group; if you want to read from the start, use <dbEntryRef>.LimitToFirst instead.


Syntax:

<dbEntryRef>.LimitToLast(amount)
Argument Type Description
amount Real The number of results to read (from the end)



Returns:

dbEntryRef


Example:

listenerId = FirebaseRealTime().Path("players/healthList").OrderByValue().LimitToLast(5).Read();

The code above performs a read operation (using the <dbEntryRef>.Read method) on the database reference "players/healthList" (using the <dbEntryRef>.Path method) ordered by the value (using the <dbEntryRef>.OrderByValue method), returning only the last 5 results.




Back To Top

<dbEntryRef>.OrderByKey

This method should be used when performing a <dbEntryRef>.Read operation or creating a <dbEntryRef>.Listener, and orders the returned results by key so they can be then filtered using one of the filtering methods (see <dbEntryRef>.StartAt, <dbEntryRef>.EndAt, <dbEntryRef>.EqualTo, <dbEntryRef>.LimitToFirst and<dbEntryRef>.LimitToLast).

Note

The final result from the Read() call will not be sorted; the sort order is only used by any filter methods chained after this.


Syntax:

<dbEntryRef>.OrderByKey()



Returns:

dbEntryRef


Example:

listenerId = FirebaseRealTime().Path("enemies/names").OrderByKey().LimitToFirst(5).Read();

The code above performs a read operation (using the <dbEntryRef>.Read method) on the database reference "enemies/names" (using the <dbEntryRef>.Path method) ordering the results by key and returning only the first 5 elements (using the <dbEntryRef>.LimitToFirst method).




Back To Top

<dbEntryRef>.OrderByValue

This method should be used when performing a <dbEntryRef>.Read operation or creating a <dbEntryRef>.Listener, and orders the returned results by value so they can be then filtered using one of the filtering methods (see <dbEntryRef>.StartAt, <dbEntryRef>.EndAt, <dbEntryRef>.EqualTo, <dbEntryRef>.LimitToFirst and<dbEntryRef>.LimitToLast).

Note

The final result from the Read() call will not be sorted; the sort order is only used by any filter methods chained after this.


Syntax:

<dbEntryRef>.OrderByValue()



Returns:

dbEntryRef


Example:

listenerId = FirebaseRealTime().Path("enemies/names").OrderByValue().LimitToFirst(5).Read();

The code above performs a read operation (using the <dbEntryRef>.Read method) on the database reference "enemies/names" (using the <dbEntryRef>.Path method) ordering the results by value and returning only the first 5 elements (using the <dbEntryRef>.LimitToFirst method).




Back To Top

dbEntryRef

This struct is referenced by the following functions: