nalaka/firestore

Deprecated1.0.1
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

Copy
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

Copy
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

Copy
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

Copy
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 TypeFirestore Type
stringstringValue
intintegerValue
booleanbooleanValue
() (null)nullValue
floatdoubleValue
map<json>mapValue
json[]arrayValue

API Reference

Types

ServiceAccount

Service account configuration record containing:

  • type: Service account type
  • project_id: Google Cloud project ID
  • private_key_id: Private key ID
  • private_key: Private key content
  • client_email: Service account email
  • client_id: Client ID
  • auth_uri: Authorization URI
  • token_uri: Token URI
  • auth_provider_x509_cert_url: Auth provider certificate URL
  • client_x509_cert_url: Client certificate URL
  • universe_domain: Universe domain

FirebaseConfig

Firebase project configuration (optional):

  • apiKey: Firebase API key
  • authDomain: Auth domain
  • databaseURL: Database URL
  • projectId: Project ID
  • storageBucket: Storage bucket
  • messagingSenderId: Messaging sender ID
  • appId: App ID
  • measurementId: Measurement ID

JWTConfig

JWT token configuration:

  • scope: OAuth2 scope for Firestore access
  • expTime: Token expiration time in seconds

AuthConfig

Authentication configuration:

  • serviceAccountPath: Path to service account JSON file
  • firebaseConfig: Optional Firebase configuration
  • jwtConfig: JWT configuration
  • privateKeyPath: 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 calls
  • getProjectId() returns string|error: Get project ID from service account

Configuration Requirements

Service Account Setup

  1. Create a Google Cloud Project with Firestore enabled
  2. Create a Service Account with Firestore permissions:
    • Cloud Datastore User or Firestore Service Agent role
  3. 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.

Import

import nalaka/firestore;Copy

Metadata

Released date: 3 days ago

Version: 1.0.1


Compatibility

Platform: any

Ballerina version: 2201.12.3

GraalVM compatible: Yes


Pull count

Total: 1

Current verison: 0


Weekly downloads


Other versions