GCP - Firestore Enum
👉 Overview
👀 What ?
Google Cloud Platform's Firestore is a NoSQL document database that lets you easily store, sync, and query data for your mobile and web apps at global scale. 'Enum' in Firestore is a way to limit a field to one value from a predefined list of constants. It's a feature of Firestore security rules, allowing to create more secure databases by constraining the possible values of a field.
🧐 Why ?
Using Firestore Enums is important as it helps in maintaining data consistency and in enhancing security. With enums, you can define a list of valid values for a field, and Firestore security rules will enforce that only those values can be used, reducing the risk of incorrect or malicious data being stored. Furthermore, enums can also make your code more readable and manageable by replacing magic strings with named constants.
⛏️ How ?
To use Firestore Enum, firstly you need to define your enum in the Firestore security rules. For example,
enum TaskStatus { NotStarted, InProgress, Completed }
. Then, in the rule for the document, you can reference the enum to enforce that a field must be one of its values. For example,allow write: if request.resource.data.status in TaskStatus;
. This rule ensures that the 'status' field of the document can only be 'NotStarted', 'InProgress', or 'Completed'.
⏳ When ?
Firestore Enum should be used whenever you have a field that should only contain a specific set of values. This is commonly used for status fields, types, categories, or any other field where the valid values are known in advance.
⚙️ Technical Explanations
The Firestore Enum is a data type that allows for variables to be set with predefined values which you have already defined as a 'enum'. These predefined values are all of an underlying integral type that can be integer-based or character-based. The Firestore security rules system uses these enums to validate incoming requests and enforce data constraints. It's important to note that Firestore enums are not a built-in feature of the Firestore database itself, but rather a feature of the Firestore security rules language, which is a separate DSL that's used to write security rules for Firestore. The Firestore security rules language has built-in support for enums, which allows for the creation of more sophisticated and precise rules.