Module firestore
nalaka/firestore
Firestore Module
A Ballerina module for accessing Google Cloud Firestore database with authentication support.
Overview
This module provides a simple interface to interact with Google Cloud Firestore, including:
- Document creation
- Document querying with filters
- Firebase/Google Cloud authentication
- Automatic data type conversion between Ballerina and Firestore formats
Features
- Document Operations: Create and query documents in Firestore collections
- Authentication: Integrated Google Cloud authentication using service account
- Type Safety: Automatic conversion between Ballerina types and Firestore field types
- Filtering: Support for single and multiple field filters with AND operations
- Error Handling: Comprehensive error handling for all operations
Usage
Configuration
import nalaka/firestore; public function main() returns error? { firestore:AuthConfig authConfig = { serviceAccountPath: "./path/to/service-account.json", privateKeyPath: "./private.key", jwtConfig: { scope: "https://www.googleapis.com/auth/datastore", expTime: 3600 } }; // Your operations here }
Creating Documents
firestore:AuthConfig authConfig = { serviceAccountPath: "./service-account.json", jwtConfig: { scope: "https://www.googleapis.com/auth/datastore", expTime: 3600 } }; map<json> documentData = { "name": "John Doe", "age": 30, "active": true, "metadata": { "created": "2024-01-01", "tags": ["user", "active"] } }; check firestore:create(authConfig, "users", documentData);
Querying Documents
firestore:AuthConfig authConfig = { serviceAccountPath: "./service-account.json", jwtConfig: { scope: "https://www.googleapis.com/auth/datastore", expTime: 3600 } }; map<json> filter = { "active": true, "age": 30 }; map<json>[] results = check firestore:findByFilter("users", filter, authConfig); foreach var doc in results { io:println("Document: ", doc); }
Working with the Client Directly
firestore:Client firestoreClient = check new(authConfig); string accessToken = check firestoreClient.generateToken(); string projectId = check firestoreClient.getProjectId(); io:println("Project ID: ", projectId);
Supported Data Types
The module automatically converts between Ballerina and Firestore types:
Ballerina Type | Firestore Type |
---|---|
string | stringValue |
int | integerValue |
boolean | booleanValue |
() (null) | nullValue |
float | doubleValue |
map<json> | mapValue |
json[] | arrayValue |
API Reference
Types
ServiceAccount
Service account configuration record containing:
type
: Service account typeproject_id
: Google Cloud project IDprivate_key_id
: Private key IDprivate_key
: Private key contentclient_email
: Service account emailclient_id
: Client IDauth_uri
: Authorization URItoken_uri
: Token URIauth_provider_x509_cert_url
: Auth provider certificate URLclient_x509_cert_url
: Client certificate URLuniverse_domain
: Universe domain
FirebaseConfig
Firebase project configuration (optional):
apiKey
: Firebase API keyauthDomain
: Auth domaindatabaseURL
: Database URLprojectId
: Project IDstorageBucket
: Storage bucketmessagingSenderId
: Messaging sender IDappId
: App IDmeasurementId
: Measurement ID
JWTConfig
JWT token configuration:
scope
: OAuth2 scope for Firestore accessexpTime
: Token expiration time in seconds
AuthConfig
Authentication configuration:
serviceAccountPath
: Path to service account JSON filefirebaseConfig
: Optional Firebase configurationjwtConfig
: JWT configurationprivateKeyPath
: Private key file path (defaults to "./private.key")
Functions
create(AuthConfig authConfig, string collection, map<json> documentData) returns error?
Create a new document in a Firestore collection.
findByFilter(string collection, map<json> filter, AuthConfig authConfig) returns map<json>[]|error
Query documents with filters using AND operation for multiple conditions.
processFirestoreValue(json value) returns map<json>
Convert Ballerina values to Firestore format.
extractFirestoreValue(json firestoreValue) returns json|error
Convert Firestore values to Ballerina format.
buildFirestoreFilter(map<json> filter) returns json
Build Firestore query filters from key-value pairs.
Client
Client
Main client class for authentication and token management.
Methods:
generateToken() returns string|error
: Generate OAuth2 access token for Firestore API callsgetProjectId() returns string|error
: Get project ID from service account
Configuration Requirements
Service Account Setup
- Create a Google Cloud Project with Firestore enabled
- Create a Service Account with Firestore permissions:
Cloud Datastore User
orFirestore Service Agent
role
- Download the service account JSON key file
File Structure
your-project/ ├── service-account.json # Service account credentials ├── private.key # Auto-generated private key file └── main.bal # Your Ballerina code
Error Handling
The module provides comprehensive error handling:
- Authentication errors (invalid service account, expired tokens)
- Network errors (connection failures, timeouts)
- Firestore API errors (permission denied, quota exceeded)
- Data conversion errors (invalid field types)
Requirements
- Ballerina Swan Lake 2201.8.0 or later
- Google Cloud Project with Firestore enabled
- Service Account with Firestore permissions
- Service Account JSON key file
License
This module is available under the Apache 2.0 license.