Skip to main content

Core Types

ID

A string representing a Firestore document ID.
type ID = string;
ID
string
Document identifier used throughout the ORM. Auto-generated by Firestore when creating documents.

Hook Types

HookEvent

Union type of all available lifecycle hook events.
type HookEvent = SingleHookEvent | BulkHookEvent;
HookEvent
SingleHookEvent | BulkHookEvent
All possible lifecycle hook event names that can be registered with repository.on().

SingleHookEvent

Events triggered by single-document operations.
type SingleHookEvent = 
  | 'beforeCreate' | 'afterCreate'
  | 'beforeSoftDelete' | 'afterSoftDelete'
  | 'beforeUpdate' | 'afterUpdate'
  | 'beforeDelete' | 'afterDelete'
  | 'beforeRestore' | 'afterRestore';
beforeCreate
string
Triggered before a document is created.
afterCreate
string
Triggered after a document is successfully created.
beforeUpdate
string
Triggered before a document is updated.
afterUpdate
string
Triggered after a document is successfully updated.
beforeDelete
string
Triggered before a document is permanently deleted.
afterDelete
string
Triggered after a document is successfully deleted.
beforeSoftDelete
string
Triggered before a document is soft deleted.
afterSoftDelete
string
Triggered after a document is successfully soft deleted.
beforeRestore
string
Triggered before a soft-deleted document is restored.
afterRestore
string
Triggered after a document is successfully restored.

BulkHookEvent

Events triggered by bulk operations.
type BulkHookEvent = 
  | 'beforeBulkCreate' | 'afterBulkCreate'
  | 'beforeBulkUpdate' | 'afterBulkUpdate'
  | 'beforeBulkDelete' | 'afterBulkDelete'
  | 'beforeBulkSoftDelete' | 'afterBulkSoftDelete'
  | 'beforeBulkRestore' | 'afterBulkRestore';
beforeBulkCreate
string
Triggered before multiple documents are created.
afterBulkCreate
string
Triggered after multiple documents are successfully created.
beforeBulkUpdate
string
Triggered before multiple documents are updated.
afterBulkUpdate
string
Triggered after multiple documents are successfully updated.
beforeBulkDelete
string
Triggered before multiple documents are permanently deleted.
afterBulkDelete
string
Triggered after multiple documents are successfully deleted.
beforeBulkSoftDelete
string
Triggered before multiple documents are soft deleted.
afterBulkSoftDelete
string
Triggered after multiple documents are successfully soft deleted.
beforeBulkRestore
string
Triggered before multiple soft-deleted documents are restored.
afterBulkRestore
string
Triggered after multiple documents are successfully restored.

Hook Function Types

SingleHookFn

Function signature for single-document lifecycle hooks.
type SingleHookFn<T> = (data: Partial<T> & { id?: ID }) => Promise<void> | void;
data
Partial<T> & { id?: ID }
The document data being operated on. May include an id field depending on the operation.
Example:
userRepo.on('afterCreate', async (user) => {
  console.log(`Created user: ${user.id}`);
  await sendWelcomeEmail(user.email);
});

BulkCreateHookFn

Function signature for bulk create hooks.
type BulkCreateHookFn<T> = (data: (T & { id: ID })[]) => Promise<void> | void;
data
(T & { id: ID })[]
Array of documents being created, each with a generated ID.

BulkUpdateHookFn

Function signature for bulk update hooks.
type BulkUpdateHookFn<T> = (data: { id: ID, data: Partial<T> }[]) => Promise<void> | void;
data
{ id: ID, data: Partial<T> }[]
Array of update operations, each containing the document ID and partial data.

BulkDeleteHookFn

Function signature for bulk delete hooks.
type BulkDeleteHookFn<T> = (data: { ids: ID[], documents: (T & { id: ID })[] }) => Promise<void> | void;
data
object
ids
ID[]
Array of document IDs being deleted.
documents
(T & { id: ID })[]
Full document data for all documents being deleted.

BulkSoftDeleteHookFn

Function signature for bulk soft delete hooks.
type BulkSoftDeleteHookFn<T> = (data: { 
  ids: ID[], 
  documents: (T & { id: ID })[], 
  deletedAt: string 
}) => Promise<void> | void;
data
object
ids
ID[]
Array of document IDs being soft deleted.
documents
(T & { id: ID })[]
Full document data for all documents being soft deleted.
deletedAt
string
ISO 8601 timestamp when the documents are being deleted.

BulkRestoreHookFn

Function signature for bulk restore hooks.
type BulkRestoreHookFn<T> = (data: { documents: (T & { id: ID })[] }) => Promise<void> | void;
data
object
documents
(T & { id: ID })[]
Full document data for all documents being restored.

Validation Types

Validator

Interface for schema validation.
type Validator<T> = {
  parseCreate(input: unknown): T;
  parseUpdate(input: unknown): Partial<T>;
}
Validator
object
parseCreate
(input: unknown) => T
Validates and parses data for create operations. Throws ValidationError if validation fails.
parseUpdate
(input: unknown) => Partial<T>
Validates and parses data for update operations. All fields are optional. Throws ValidationError if validation fails.
Example:
import { z } from 'zod';
import { makeValidator } from '@spacelabstech/firestoreorm';

const userSchema = z.object({
  name: z.string().min(1),
  email: z.string().email(),
  age: z.number().int().positive().optional()
});

const validator = makeValidator(userSchema);

// Used internally by FirestoreRepository.withSchema()
const userRepo = FirestoreRepository.withSchema<User>(db, 'users', userSchema);

Query Types

Query Operators

Type-safe query operators based on field types.
type EqOps = '==' | '!=';
type CmpOps = '<' | '<=' | '>' | '>=';
type InOps = 'in' | 'not-in';
type ArrOps = 'array-contains' | 'array-contains-any';
EqOps
'==' | '!='
Equality operators. Work with all field types.
CmpOps
'<' | '<=' | '>' | '>='
Comparison operators. Work with numbers, dates, and timestamps.
InOps
'in' | 'not-in'
Membership operators. Check if a value is in or not in an array. Maximum 10 items in the array.
ArrOps
'array-contains' | 'array-contains-any'
Array operators. Check if an array field contains specific values.
Example:
// Equality
await userRepo.query().where('status', '==', 'active').get();

// Comparison
await productRepo.query().where('price', '>', 100).get();

// In/Not-in
await orderRepo.query().where('status', 'in', ['pending', 'processing']).get();

// Array operations
await postRepo.query().where('tags', 'array-contains', 'typescript').get();

Pagination Results

Return type for cursor-based pagination.
type PaginationResult<T> = {
  items: (T & { id: ID })[];
  nextCursorId: ID | undefined;
}
PaginationResult
object
items
(T & { id: ID })[]
Array of documents for the current page.
nextCursorId
ID | undefined
ID to use for fetching the next page. undefined if there are no more pages.
Example:
const { items, nextCursorId } = await userRepo.query()
  .orderBy('createdAt', 'desc')
  .paginate(20);

if (nextCursorId) {
  const nextPage = await userRepo.query()
    .orderBy('createdAt', 'desc')
    .paginate(20, nextCursorId);
}

Offset Pagination Results

Return type for offset-based pagination.
type OffsetPaginationResult<T> = {
  items: (T & { id: ID })[];
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}
OffsetPaginationResult
object
items
(T & { id: ID })[]
Array of documents for the current page.
page
number
Current page number (1-based).
pageSize
number
Number of items per page.
total
number
Total number of documents matching the query.
totalPages
number
Total number of pages available.
Example:
const { items, page, totalPages, total } = await userRepo.query()
  .where('role', '==', 'customer')
  .orderBy('createdAt', 'desc')
  .offsetPaginate(2, 20);

console.log(`Page ${page} of ${totalPages} (${total} total users)`);

Transaction Types

Types used when working with Firestore transactions.

Transaction Callback

Function signature for transaction operations.
type TransactionFn<R> = (
  tx: FirebaseFirestore.Transaction,
  repo: FirestoreRepository<T>
) => Promise<R>;
tx
FirebaseFirestore.Transaction
Firestore transaction object for atomic operations.
repo
FirestoreRepository<T>
Repository instance configured for transaction use.
returns
Promise<R>
Return value of the transaction. Can be any type.
Example:
const newBalance = await accountRepo.runInTransaction(async (tx, repo) => {
  const account = await repo.getForUpdate(tx, 'account-123');
  if (!account) throw new Error('Account not found');
  
  const newValue = account.balance + 100;
  await repo.updateInTransaction(tx, account.id, { balance: newValue });
  
  return newValue;
});

Utility Types

SubcollectionPath

Internal type for tracking subcollection paths.
interface SubcollectionPath {
  parentId: ID;
  subcollectionName: string;
}
SubcollectionPath
object
parentId
ID
ID of the parent document.
subcollectionName
string
Name of the subcollection.

Scalar

Primitive types supported by Firestore queries.
type Scalar = string | number | boolean | Date | Timestamp;
Scalar
string | number | boolean | Date | Timestamp
Basic value types that can be stored and queried in Firestore.

Build docs developers (and LLMs) love