Write - SrejonKhan/FirebaseRestClient GitHub Wiki
Overview
Firebase Rest Client comes with some handy methods to run Write Operations.
- Basic Write Operation to specific reference -
WriteValue()
- Key-Value Pair Write Operation -
WriteKeyValuePair()
Examples
Write to specific reference -
var firebase = new RealtimeDatabase();
// Object as payload, it can be any datatypes, even raw Json
firebase.Child("product/orange").WriteValue(anyObject).OnSuccess( () =>
{
Debug.Log("Successfully written.");
});
firebase.Child("price").WriteValue(123); //int
firebase.Child("price").WriteValue(324.25f); //float
firebase.Child("stockout").WriteValue(true); //bool
firebase.Child("product/abc").WriteValue(jsonString); //JSON String
Writing Key and Value Pair to specific reference (suitable for key-value pair leaderboard or similar) -
firebase.Child("leaderboard").WriteKeyValuePair("player123", "123");
firebase.Child("leaderboard").WriteKeyValuePair("player321", "521", true); //append to parent
Use Case
WriteValue()
is perfect for writing to a specific reference. Let's say we would like to write a new product information apple
to following dataset -
"products" : {
"cherry" : {
"id" : "fr242",
"name" : "Cherry",
"price" : 12.99
},
"kiwi" : {
"id" : "fr243",
"name" : "Kiwi",
"price" : 10.99
}
}
So, our code snippet would looks like this -
var orange = new Product("fr244","Orange", 7.99f);
firebase.Child("products/orange").WriteValue(orange).OnSuccess( () =>
{
Debug.Log("Successfully written to products/orange.");
});
In the future, a new requirement added to have Stock Out
information for orange
product. We can easily add that also -
firebase.Child("products/orange/stockout").WriteValue(true);
Or, we can also use another available method -
firebase.Child("products/orange").WriteKeyValuePair("stockout", true);
Let's say, we have a leaderboard. Every time a new player plays our games, we need to add them to leaderboard
reference in the database. We need to have this kind of dataset -
"leaderboard": {
"alovelace": 126,
"ghopper": 65,
"eclarke": 576
}
Now if we need to add a new score of a player -
firebase.Child("leaderboard").WriteKeyValuePair("srejon", 923, true).OnSuccess( () =>
{
Debug.Log("Successfully added.");
});
In the following code, we passed true
as third argument of WriteKeyValuePair()
. Here, this true
represent appending to reference. What we mean by appending is, rather than overwriting whole path we add (patch) that key-value pair to the reference.
For updating a specific reference, please go to Update Page.