Document Keys
With Jugnu Framework - you can choose to define document keys yourself or leave to Firebase / Jugnu to generate a key.
This is achieved by defining the key type in document key annotation.
User Defined Key
Annotate your class property with @DocumentKey(DocumentKeyType.UserDefined)
.
In this case, the document key must be defined by the application. The application must ensure that the key is uninue.
If the value of the key is not set at the time of entity creation, then Firebse will throw an exception.
If the key already exists, then the old document will be updated.
Auto Generated Key
Annotate your class property with @DocumentKey(DocumentKeyType.GeneratedKey)
.
In this case, the key is generated by the Firebase. The create method will return back the key generated.
@FirebaseCollection()
class OrderAddress {
@DocumentKey(DocumentKeyType.GeneratedKey)
addrKey?: String; // Will be set by Firebase
@DocumentField
streetName?: String;
@DocumentField
houseNumer?: String;
}
const addressCollection = jugnu.createFirebaseCollection(OrderAddress);
const address = new OrderAddress();
address.houseNumer = "H No";
address.streetName = "My Street";
// Create method will return the generated key
address.addrKey = await addressCollection.create(address);
Auto Incremented Key
Annotate your class property with @DocumentKey(DocumentKeyType.AutoIncrement)
.
In this case, Firebase will generate a key from a sequence. The key is not a random string.
The create method will return the generated key.
The behaviour is somewhat similar to Auto Increment in mySQL DBs.
Behind the scenes, Jugnu will create a new collection to keep a track of counters. Everytime a create method is called, the counter will be incremented by 1.
@FirebaseCollection()
class SalesOrder {
@DocumentKey(DocumentKeyType.AutoIncrement)
id?: string;
@DocumentField
totalAmount: number = 0;
@DocumentField
orderDate: Date;
constructor(){
this.orderDate = new Date();
}
}
const orderCollection = jugnu.createFirebaseCollection(SalesOrder);
const order = new SalesOrder();
order.totalAmount = 100;
const orderId = await orderCollection.create(order);
console.log(order);