Services
Firebase data and entity service implementations.
Table of contents
FirebaseDataService
Concrete base class for Firebase Realtime Database reads and writes. EntityService extends this class.
Constructor
Pass a Firebase Admin Database instance.
new FirebaseDataService(database)
Methods
getList<T>(path): returns a path’s children as an array, with Firebase keys mixed into each item.getObject<T>(path): returns the value at a path with its Firebase key, ornullif the path is empty.setObject(path, value): replaces the value at a path.updateObject(path, value): merges properties at a path.findAllObjectsBy<T>(path, propertyName, value): queries children by one property.getSnapshot(path): returns the FirebaseDataSnapshot.convertObjectToList<T>(value)andmixKey(value, key): static conversion helpers.
Example
import { FirebaseDataService } from '@migration-script-runner/firebase';
import { initializeApp } from 'firebase-admin/app';
import { getDatabase } from 'firebase-admin/database';
const app = initializeApp({ databaseURL: process.env.DATABASE_URL });
const dataService = new FirebaseDataService(getDatabase(app));
const users = await dataService.getList<{ name: string }>('/users');
await dataService.setObject('/users/user1', { name: 'John' });
await dataService.updateObject('/users/user1', { name: 'John Smith' });
await dataService.setObject('/users/user1', null);
EntityService
Type-safe service for managing entities in Firebase Realtime Database. Provides CRUD operations, batch updates, and query capabilities with generic type support.
Perfect for migrations! EntityService is specifically designed for use in migration scripts, providing a clean, type-safe API for working with collections of entities.
Constructor
constructor(
db: Database,
root: string
)
Parameters:
db- Firebase Realtime Database instance (fromIFirebaseDB.database)root- Root path for the entity collection (usehandler.cfg.buildPath())
Type Parameter
EntityService uses a generic type parameter T extends IEntity:
import { EntityService, type IEntity } from '@migration-script-runner/firebase';
// Define your entity type
interface User extends IEntity {
name: string;
email: string;
role: 'admin' | 'user';
}
// Create type-safe service
const userService = new EntityService<User>(db.database, handler.cfg.buildPath('users'));
Methods
getAll()
Retrieves all entities from the collection as an array.
getAll(): Promise<T[]>
Returns: Promise resolving to array of entities (each includes key property)
Example:
const users = await userService.getAll();
console.log(`Found ${users.length} users`);
getAllAsObject()
Retrieves all entities as an object with keys as properties.
getAllAsObject(): Promise<Record<string, T> | null>
Returns: Promise resolving to an object containing all entities, or null when the collection does not exist.
Example:
const usersObject = await userService.getAllAsObject();
const user = usersObject?.['user-key-123'];
get()
Retrieves a single entity by its key.
get(key: string): Promise<T | null>
Parameters:
key- Firebase key of the entity
Returns: Promise resolving to entity or null if not found
Example:
const user = await userService.get('user-key-123');
if (user) {
console.log(user.name);
}
create()
Creates a new entity with auto-generated Firebase key.
create(obj: T): Promise<string>
Parameters:
obj- Entity object (key will be auto-generated)
Returns: Promise resolving to the newly created entity’s key
Example:
const newKey = await userService.create({
name: 'Alice',
email: 'alice@example.com',
role: 'admin'
});
save()
Smart save that creates if no key, updates if key present.
save(obj: T): Promise<string>
Parameters:
obj- Entity object (with or without key)
Returns: Promise resolving to entity key (existing or new)
Example:
// Create (the key is generated by Firebase)
const key1 = await userService.save({ name: 'Bob', email: 'bob@example.com', role: 'user' });
// Update (with key)
const key2 = await userService.save({ key: 'user-123', name: 'Bob Updated', email: 'bob@example.com', role: 'user' });
update()
Updates an existing entity (merges with existing data).
update(key: string, obj: T): Promise<string>
Parameters:
key- Firebase key of the entity to updateobj- Complete entity object; Firebase merges its properties at the entity path
Returns: Promise resolving to the entity key
Example:
await userService.update('user-key-123', {
key: 'user-key-123',
name: 'Alice',
email: 'newemail@example.com',
role: 'admin'
});
set()
Sets (replaces) an entity completely.
set(key: string, obj: T): Promise<string>
Parameters:
key- Firebase key of the entity to setobj- Complete entity object (overwrites existing)
Returns: Promise resolving to the entity key
Example:
await userService.set('user-key-123', {
key: 'user-key-123',
name: 'Alice',
email: 'alice@example.com',
role: 'admin'
});
remove()
Removes a single entity by key.
remove(key: string): Promise<string>
Parameters:
key- Firebase key of the entity to remove
Returns: Promise resolving to the removed entity’s key
Example:
await userService.remove('user-key-123');
removeByIds()
Removes multiple entities in parallel.
removeByIds(ids: string[]): Promise<void>
Parameters:
ids- Array of Firebase keys to remove
Example:
await userService.removeByIds(['key1', 'key2', 'key3']);
removeAll()
Removes all entities in the collection.
Destructive operation! This cannot be undone.
removeAll(): Promise<void>
Example:
await userService.removeAll(); // Use with caution!
findAllBy()
Finds entities where a property matches a value.
findAllBy(propertyName: string, value: number | string | boolean | null): Promise<T[]>
Parameters:
propertyName- Property name to queryvalue- Value to match
Returns: Promise resolving to array of matching entities
Example:
// Find all admin users
const admins = await userService.findAllBy('role', 'admin');
// Find verified users
const verified = await userService.findAllBy('verified', true);
updateAll()
Batch updates all entities using an update function.
updateAll(updateFn: (entity: T) => boolean): Promise<ModificationResults>
Parameters:
updateFn- Function that modifies entity and returnstrueif modified,falseif skipped
Returns: Promise resolving to ModificationResults with updated and skipped arrays
Example:
const results = await userService.updateAll((user) => {
if (user.verified !== undefined) {
return false; // Skip - already has field
}
user.verified = false; // Add field
return true; // Modified
});
console.log(`Updated: ${results.updated.length}, Skipped: ${results.skipped.length}`);
Usage Guidance
EntityService can be used inside a class-based IRunnableScript<IFirebaseDB> migration. For a full migration example and patterns, see Using EntityService.
See Also
- Using EntityService Guide - Complete guide with examples
- Migration Scripts - Writing migrations
- IEntity Interface - Entity interface definition