Skip to main content

Class: GoatDB<US>

Defined in: db/db.ts:215

The main database class that manages repositories, synchronization, and data access.

GoatDB is the primary entry point for working with the database. It handles:

  • Repository management (opening, closing, accessing)
  • Data synchronization with peers
  • User authentication and authorization
  • Schema validation
  • Buffered writes: commits are coalesced and written to disk only on flush / flushAll. Commits pending in the buffer are lost on ungraceful exit; listen for the EventWriteFailure event to detect repeated write failures that cause commits to be dropped.

Extends

Type Parameters

Type ParameterDefault typeDescription
US extends SchemaSchemaThe user schema type, defaults to the base Schema type

Constructors

Constructor

new GoatDB<US>(config): GoatDB<US>

Defined in: db/db.ts:263

Parameters

ParameterType
configDBInstanceConfig

Returns

GoatDB<US>

Overrides

Emitter.constructor

Properties

PropertyModifierTypeDefault valueInherited fromDefined in
_testForceAppendFailurespublicnumber0-db/db.ts:240
alwaysActivereadonlybooleanundefinedEmitter.alwaysActivebase/emitter.ts:10
debugreadonlybooleanundefined-db/db.ts:220
modereadonlyDBModeundefined-db/db.ts:221
orgIdreadonlystringundefined-db/db.ts:217
queryPersistence?publicQueryPersistenceundefined-db/db.ts:256
registryreadonlyDataRegistryundefined-db/db.ts:218
shardConfigreadonlyShardConfigundefined-db/db.ts:261
storageFormatreadonlyStorageFormatundefined-db/db.ts:222
trustedreadonlybooleanundefined-db/db.ts:219

Accessors

currentSession

Get Signature

get currentSession(): ManagedItem<{ fields: { expiration: { required: true; type: "date"; }; id: { required: true; type: "string"; }; owner: { type: "string"; }; publicKey: { required: true; type: "string"; }; }; ns: "sessions"; version: 1; }>

Defined in: db/db.ts:333

Returns the current session.

Throws

This method throws if called before db.ready returns true.

Returns

ManagedItem<{ fields: { expiration: { required: true; type: "date"; }; id: { required: true; type: "string"; }; owner: { type: "string"; }; publicKey: { required: true; type: "string"; }; }; ns: "sessions"; version: 1; }>


currentUser

Get Signature

get currentUser(): ManagedItem<US, Schema>

Defined in: db/db.ts:324

Returns the current user item or undefined if the current session is anonymous.

Returns

ManagedItem<US, Schema>


isActive

Get Signature

get isActive(): boolean

Defined in: base/emitter.ts:57

Returns

boolean

Inherited from

Emitter.isActive


loggedIn

Get Signature

get loggedIn(): boolean

Defined in: db/db.ts:316

Returns whether this DB instance uses an anonymous session or a session that's attached to a known user.

Returns

boolean


path

Get Signature

get path(): string

Defined in: db/db.ts:301

Returns the directory under which this DB instance stores all data. Repositories are sub-directories within this directory.

Returns

string


ready

Get Signature

get ready(): boolean

Defined in: db/db.ts:346

Returns whether this DB instance is ready to receive commands or is it still performing the initial load.

Returns

boolean


settings

Get Signature

get settings(): DBSettings

Defined in: db/db.ts:308

Returns the settings object of this DB instance.

Returns

DBSettings

Methods

attach()

attach<C, E>(e, c): () => void

Defined in: base/emitter.ts:116

Type Parameters

Type Parameter
C extends Function
E extends "UserChanged" | "WriteFailure" | "ItemChanged" | EmitterEvent

Parameters

ParameterType
eE
cC

Returns

() => void

Inherited from

Emitter.attach


clientsForRepo()

clientsForRepo(...pathComps): Iterable<RepoClient>

Defined in: db/db.ts:986

Returns the associated RepoClient instances for the given repository. Each client instance handles synchronization with a different server endpoint, enabling client-side load-balancing.

Parameters

ParameterTypeDescription
...pathCompsstring[]Repository path.

Returns

Iterable<RepoClient>

RepoClient instances for the given repository.


close()

close(): Promise<void>

Defined in: db/db.ts:389

Closes the database, releasing all resources including repositories, sync schedulers, queries, and file handles. This method should be called when you're done using the database instance.

Returns

Promise<void>


closeRepo()

closeRepo(path): Promise<void>

Defined in: db/db.ts:464

Closes a repository, flushing any pending writes to disk before releasing all memory associated with this repository.

This method does nothing if the repository isn't currently loaded.

Parameters

ParameterTypeDescription
pathstringPath to the desired repository.

Returns

Promise<void>


count()

count(path): number

Defined in: db/db.ts:657

Returns the number of items at the specified path, or -1 if the path doesn't exist.

NOTE: Currently only paths to repositories are supported.

Parameters

ParameterTypeDescription
pathstringThe full path to count.

Returns

number

The number of items found or -1.


create()

create<S>(path, schema, data?): ManagedItem<S>

Defined in: db/db.ts:565

Creates a new item at the target repository, opening it if needed. Unlike GoatDB.item() there's no need to explicitly open a repository before creating items in it. Newly created items become immediately available for use and will get committed to the underlying repo after open completes.

Note: This method only initializes the item if it doesn't already exist. If the item already exists with a valid schema, this method will return the existing item without modifying it.

Type Parameters

Type Parameter
S extends Schema

Parameters

ParameterTypeDescription
pathstringIf a full path is provided, the item will be created with the provided key. If a repository path is provided, a unique item key will be automatically generated.
schemaSThe schema to create the item with.
data?Partial<SchemaDataType<S>>The initial data to populate the item with.

Returns

ManagedItem<S>

The newly created managed item, or the existing item if it already exists.


detach()

detach<C, E>(e, c): void

Defined in: base/emitter.ts:149

Type Parameters

Type Parameter
C extends Function
E extends "UserChanged" | "WriteFailure" | "ItemChanged" | EmitterEvent

Parameters

ParameterType
eE
cC

Returns

void

Inherited from

Emitter.detach


detachAll()

detachAll<E>(e?): void

Defined in: base/emitter.ts:188

Type Parameters

Type Parameter
E extends "UserChanged" | "WriteFailure" | "ItemChanged" | EmitterEvent

Parameters

ParameterType
e?E

Returns

void

Inherited from

Emitter.detachAll


emit()

emit<E>(e, a0?, a1?): void

Defined in: base/emitter.ts:65

Emits an event to all registered listeners in registration (FIFO) order. This ordering is a stable contract -- chained query listeners depend on it.

Type Parameters

Type Parameter
E extends "UserChanged" | "WriteFailure" | "ItemChanged" | EmitterEvent

Parameters

ParameterType
eE
a0?unknown
a1?unknown

Returns

void

Inherited from

Emitter.emit


flush()

flush(path): Promise<void>

Defined in: db/db.ts:825

Flushes all pending writes for the given repository to disk. Use this method when you must ensure all previously known commits are written to the local disk.

Parameters

ParameterTypeDescription
pathstringPath to the desired repository.

Returns

Promise<void>

A promise that resolves after all commits have been flushed to disk.


flushAll()

flushAll(): Promise<void>

Defined in: db/db.ts:853

Flushes all pending writes for all repositories to disk.

Returns

Promise<void>


getTrustPool()

getTrustPool(): Promise<TrustPool>

Defined in: db/db.ts:955

Returns the trust pool of this DB instance. The trust pool is a low level object that manages all known sessions and their public keys. It is used to verify the authenticity of the underlying commit graph before persisting it to the local storage.

Note: You almost never need to use the trust pool directly.

Returns

Promise<TrustPool>

The trust pool of this DB instance.


insert()

insert<S>(repoPath, schema, items): Promise<void>

Defined in: db/db.ts:629

Bulk-insert items into a repository. Significantly faster than individual load() calls for large batches, as it batches signing and persistence.

Type Parameters

Type Parameter
S extends Schema

Parameters

ParameterTypeDescription
repoPathstringPath to the target repository (e.g. '/data/todos').
schemaSThe schema for the items.
itemsobject[]Array of items to insert. Each may include an optional key; if omitted, a unique key is generated. Commits are buffered in memory; call flush() or flushAll() to persist.

Returns

Promise<void>


item()

item<S>(...pathComps): ManagedItem<S>

Defined in: db/db.ts:531

Access an item at the given path. An item's path is typically at the following format: /<data type>/<repo id>/<item key>

NOTE: If the item's repository haven't been opened yet, it'll be opened in the background. While open is progressing, the returned item will initially have a NULL scheme, and once open completes it'll be converted to the correct scheme if available. Typically it's easier to first explicitly open the repository before accessing any of its items.

Type Parameters

Type Parameter
S extends Schema

Parameters

ParameterTypeDescription
...pathCompsstring[]A full path or path components.

Returns

ManagedItem<S>

A managed item that tracks both local and remote edits.


itemLoaded()

itemLoaded(path): boolean

Defined in: db/db.ts:1225

Checks if an item at the given path is currently loaded in memory. This is a passive check that does not trigger loading the item.

Parameters

ParameterTypeDescription
pathstringThe full path to the item to check

Returns

boolean

True if the item is loaded in memory, false otherwise


keys()

keys(path): Iterable<string>

Defined in: db/db.ts:671

Returns the keys at the specified path.

NOTE: Currently only paths to repositories are supported.

Parameters

ParameterTypeDescription
pathstringFull path to a repository.

Returns

Iterable<string>

The keys at the specified path.


load()

load<S>(path, schema, data): Promise<void>

Defined in: db/db.ts:595

Explicitly create an item, loading its repository if needed. Use this method for bulk load operations where you want to be notified after the write completes.

NOTE: This method uses a different internal path than the Item based API, and is much more efficient for bulk creations.

Type Parameters

Type Parameter
S extends Schema

Parameters

ParameterTypeDescription
pathstringThe path for the item to create.
schemaSThe schema to create the item with.
dataSchemaDataType<S>The initial data for the item.

Returns

Promise<void>


loginWithMagicLinkEmail()

loginWithMagicLinkEmail(email): Promise<boolean>

Defined in: db/db.ts:375

When connecting to a new DB instance on the client, it'll start with an anonymous session that's not attached to any user in the system. Call this method with a user's email, to initiate an email-based login sequence that will end with the current session being attached to the user owning this email.

This login sequence sends a temporary magic link to the provided email address. Once clicked, the user item will be automatically created in /sys/users and attached to the current session.

Parameters

ParameterTypeDescription
emailstringThe target of the magic link.

Returns

Promise<boolean>

true if the magic link had been successfully sent, false otherwise.


logout()

logout(): Promise<void>

Defined in: db/db.ts:423

Logs out the current user, closing all open repositories and clearing local data. On browsers, this method will also reload the page to ensure a clean state.

Returns

Promise<void>

Throws

ServiceUnavailable if the operation fails.


mute()

mute(): void

Defined in: base/emitter.ts:288

Returns

void

Inherited from

Emitter.mute


once()

once<C, E>(e, c): () => void

Defined in: base/emitter.ts:248

Type Parameters

Type Parameter
C extends Function
E extends "UserChanged" | "WriteFailure" | "ItemChanged" | EmitterEvent

Parameters

ParameterType
eE
cC

Returns

() => void

Inherited from

Emitter.once


open()

open(path, opts?): Promise<Repository<MemRepoStorage>>

Defined in: db/db.ts:438

Opens the given repository, loading all its items to memory. This method does nothing if the repository is already open.

Parameters

ParameterTypeDescription
pathstringThe path to the given repository.
opts?OpenOptionsConfiguration options when opening this repository.

Returns

Promise<Repository<MemRepoStorage>>


query()

query<IS, CTX, OS>(config): Query<IS, OS, CTX>

Defined in: db/db.ts:685

Open a new query or access an already open one. Once opened, the query remains open until explicitly closed, and tracks updates to items as they happen.

Type Parameters

Type ParameterDefault type
IS extends Schema-
CTX extends ReadonlyJSONValue-
OS extends SchemaIS

Parameters

ParameterTypeDescription
configOmit<QueryConfig<IS, OS, CTX>, "db">The configuration for the desired query.

Returns

Query<IS, OS, CTX>

A live query instance.


readyPromise()

readyPromise(): Promise<void>

Defined in: db/db.ts:356

A convenience promise form of the ready flag. When the promise returns, this DB instance is ready to receive commands.

Returns

Promise<void>

Throws

ServiceUnavailable if the initial load failed.


repository()

repository(...pathComps): Repository<MemRepoStorage>

Defined in: db/db.ts:939

Returns the requested repository or undefined if it wasn't opened yet.

Note: Prefer to use the higher level APIs of this class rather than the repository instance directly.

Parameters

ParameterTypeDescription
...pathCompsstring[]A full path or path components.

Returns

Repository<MemRepoStorage>

The repository instance or undefined.


resume()

protected resume(): void

Defined in: base/emitter.ts:286

Returns

void

Inherited from

Emitter.resume


suspend()

protected suspend(): void

Defined in: base/emitter.ts:284

Returns

void

Inherited from

Emitter.suspend


sync()

sync(path): Promise<SyncResult>

Defined in: db/db.ts:882

Syncs the given repository with all configured peers and waits for completion.

Parameters

ParameterTypeDescription
pathstringPath to the desired repository.

Returns

Promise<SyncResult>

An object with a status field:

  • { status: 'success' } if all peers succeeded
  • { status: 'failed' } if all peers failed
  • { status: 'partial', failedPeers: string[] } if some peers failed

Example

const result = await db.sync('/my-repo');
if (result.status === 'success') {
console.log('All peers synced successfully!');
} else if (result.status === 'failed') {
console.log('All peers failed to sync.');
} else {
console.log('Some peers failed:', result.failedPeers);
}

syncAll()

syncAll(): Promise<Record<string, SyncResult>>

Defined in: db/db.ts:920

Syncs all open repositories with all configured peers and waits for completion.

Returns

Promise<Record<string, SyncResult>>

An object mapping repoId to SyncResult.

Example

const results = await db.syncAll();
for (const [repo, result] of Object.entries(results)) {
if (result.status === 'success') {
console.log(`${repo}: all peers synced!`);
} else if (result.status === 'failed') {
console.log(`${repo}: all peers failed!`);
} else {
console.log(`${repo}: some peers failed:`, result.failedPeers);
}
}

unmute()

unmute(): void

Defined in: base/emitter.ts:292

Returns

void

Inherited from

Emitter.unmute