How to remove store from ydn.db? - ydn-db

I am using ydn.db from local storage. Which function can be used to remove the store using YDB.DB library ? The stores i have added is as follows
var schema = {
stores: [{
name:'consignments',
keyPath:"timeStamp"
}];
var db = new ydn.db.Storage('localhost', schema);
I wish to check whether the store exist in localstorage and if it exists delete the store and if not exist add the store.

If store exist or not can be known only after opening the database. If a schema does not a store name, but exit in the connected database, the existing store will be removed.
To delete the database
var db = new ydn.db.Storage('localhost', schema);
To delete above the database,
ydn.db.deleteDatabase(db.getName(), db.getType());
If type of database is not known
ydn.db.deleteDatabase('localhost');

I use the deleteDatabase function like this:
indexedDB.deleteDatabase(storage_name);
see the doc here: https://dev.yathit.com/api/ydn/db/index.html

Related

Is there a way to prefetch the autogenerated key .push() will generate in Firebase Realtime DB?

I would like to create a unique id for some of the objects I store in real time DB, but I would like the id to be in the object itself. Is there a way two do this without without a 3 stop process, e.g. push the object, read the key, update the db's id field with the key?
In other words, if I want my DB to look like this:
properties:
-Mfq1Ek2geCnkol7EbeW:
id: "-Mfq1Ek2geCnkol7EbeW"
buyer: "ab3s3aga"
seller: "b3skela"
-Mq1Em5a3skfjal3EjkVDMN:
id: "-Mq1Em5a3skfjal3EjkVDMN"
buyer: "zk39xlal"
seller: "34kzla99dl"
Is there a way to do that without having to write twice to the db?
When you call push() without arguments it's a pure client-side operation, that generates a new DatabaseReference object. You can get the key from this new object.
So (in JavaScript) you can get a new key with:
let newKey = ref.push().key;
Or you can keep the reference and the key like this:
let newRef = ref.push();
let newKey = newRef.key;
And then set a value to the new ref with:
newRef.set(...);

Flutter Firebase firestore append data with unique ID

I'm working on the Flutter app where users can save multiple addresses. Previously I used a real-time database and it was easier for me to push data in any child with a unique Id but for some reason, I changed to Firestore and the same thing want to achieve with firestore. So, I generated UUID to create unique ID to append to user_address
This is how I want
and user_address looks like this
And this is how it's getting saved in firestore
So my question Is how I append data with unique id do I have to create a collection inside users field or the above is possible?
Below is my code I tried to set and update even user FieldValue.arrayUnion(userServiceAddress) but not getting the desired result
var uuid = Uuid();
var fireStoreUserRef =
await FirebaseFirestore.instance.collection('users').doc(id);
Map locationMap = {
'latitude': myPosition.latitude,
'longitude': myPosition.longitude,
};
var userServiceAddress = <String, dynamic>{
uuid.v4(): {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
}
};
await fireStoreUserRef.update({'user_address': userServiceAddress});
If I use set and update then whole data is replaced with new value it's not appending, so creating a collection is the only solution here and If I create a collection then is there any issue I'll face?
You won't have any issues per se by storing addresses in a separate collection with a one-to-many relationship, but depending on your usage, you may see much higher read/write requests with this approach. This can make exceeding your budget far more likely.
Fortunately, Firestore allows updating fields in nested objects via dot notation. Try this:
var userServiceAddress = {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
};
await fireStoreUserRef.update({'user_address.${uuid.v4()}': userServiceAddress});

Firebase Function for Deleting Storage after 30 days

Frank van Puffelen has an example for deleting database after time.
https://stackoverflow.com/a/32012520/12253594
https://github.com/firebase/functions-samples/tree/master/delete-old-child-nodes
Which works wonders. But I'm wondering if it is possible for Storage as well?
Firebase Storage Structure
The structure: Experiences -> Experience_ID -> fullHD -> Image
And I want to delete including Experience_ID.
I'm thinking, something like:
exports.deleteOldItems = functions.storange.ref('/Experiences/{notification_id}')
.onWrite((change, context) => {
var ref = change.after.ref.parent; // reference to the items
var now = Date.now();
var cutoff = now - 2 * 60 * 60 * 1000;
var oldItemsQuery = ref.orderByChild('timestamp').endAt(cutoff);
return oldItemsQuery.once('value', function(snapshot) {
// create a map with all children that need to be removed
var updates = {};
snapshot.forEach(function(child) {
updates[child.key] = null
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
});
But I obviously don't have timestamps like I do in the database section.
So what do I do?
Best regards,
You have two main options.
Encode the date into the name of the file or its metadata, use the Cloud Storage list api to list all possible files, and check the file name or metadata to determine if it should be deleted. This solution doesn't scale very well as the number of possible files to be listed grows very large.
Mirror some data about each file in a database. For each file that you add to Cloud Storage, make an equivalent record in a database that includes both the timestamp and the path of the file. Since databases are easy to query, you can simply query the database to find the files that should be deleted.

How to clone a record and create a new records in app maker?

I have a table. I want to clone a record. I added a button and in the OnClick event I have tried
var rowDataSource = widget.datasource;
// Instead of using the row datasource for create, explicitly use the data source of your list.
var listDatasource = app.datasources.Change;
var createDataSource = listDatasource.modes.create;
createDataSource.item.Systems.SystemName = rowDataSource.item.Systems.SystemName;
createDataSource.item.changeType = rowDataSource.item.changeType;
widget.datasource.createItem();
widget.datasource.saveChanges();
But this gave me error
can't associate Data with Draft Records since I am using relational Database and my databases are in manual save mode.
How to clone all field from one record and create a new record??
Here Author name comes from the relational database and Timestamp is from the tables database.

Firebase,iOS: Appending key-value pair into a child node

I have the following User Table structure in Firebase
As you can see in the user that I have opened, I have a Posts section, inside this post section holds the Id's all articles which have been posted by this user.
The issue I am facing is as follows:
When the user creates a new article it's saved within the Posts Table, after the save I return the newly generated ID which I then pass on to the user table, I trying to insert the newly created ID into the post section of the user, so I assumed the URL would be something like this:
Users/{UserId}/Posts
However all this does it create a new section called posts, it doesn't actually insert the record into the given area.
My code which isn't working is as follows:
let linkPost = [childautoID: true]
FIRDatabase.database().reference().child("Users/\(UserId)/Posts").child(UserId).setValue(linkPost)
FYI the two id's that are currently inside Posts I added manually.
I've also tried the following:
FIRDatabase.database().reference().child("Users/\(UserId)/Posts").setValue(linkPost)
However all this does it remove all existing Id's and then inserts the new id.
I prefer something like this. This automatically append the data without fetching first
FIRDatabase.database().reference().child("Users/\(UserId)/Posts").child(UserId).setValue(true)
To append a key-value pair in Firebase Database child node use this :-
Make a Firebase Database Reference to the Posts node of that currentUser FIRDatabase.database().reference().child("Users").child(FIRAuth.auth()!.currentUser!.uid).child("Posts")
Check if Posts node exists in your user's DB, If not then create one by :- parentRef.setValue([postId : "True"]) in else block.
But if Posts node does exist retrieve it as a NSMutableDictionary , set the new object to it, and then store the updated Dictionary to that node.
func storePostsToDB(postID :String!, userID : String! = FIRAuth.auth()!.currentUser!.uid){
let parentRef = FIRDatabase.database().reference().child("Users").child(userID).child("Posts")
parentRef.observeSingleEventOfType(.Value, withBlock: {(friendsList) in
if friendsList.exists(){
if let listDict = friendsList.value as? NSMutableDictionary{
listDict.setObject("True", forKey: postID)
parentRef.setValue(listDict)
}
}else{
parentRef.setValue([postID : "True"])
}
})
}
Calling the function:-
storePostsToDB("yourPostID")// If you want to store in the currentUser DB
storePostsToDB("yourPostID", userID : otherUserID)//If you want to store the post in some other users database with uid `otherUserID`

Resources