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
Emitter<EventUserChanged|EventWriteFailure|EventItemChanged>
Type Parameters
| Type Parameter | Default type | Description |
|---|---|---|
US extends Schema | Schema | The user schema type, defaults to the base Schema type |
Constructors
Constructor
new GoatDB<
US>(config):GoatDB<US>
Defined in: db/db.ts:263
Parameters
| Parameter | Type |
|---|---|
config | DBInstanceConfig |
Returns
GoatDB<US>
Overrides
Properties
| Property | Modifier | Type | Default value | Inherited from | Defined in |
|---|---|---|---|---|---|
_testForceAppendFailures | public | number | 0 | - | db/db.ts:240 |
alwaysActive | readonly | boolean | undefined | Emitter.alwaysActive | base/emitter.ts:10 |
debug | readonly | boolean | undefined | - | db/db.ts:220 |
mode | readonly | DBMode | undefined | - | db/db.ts:221 |
orgId | readonly | string | undefined | - | db/db.ts:217 |
queryPersistence? | public | QueryPersistence | undefined | - | db/db.ts:256 |
registry | readonly | DataRegistry | undefined | - | db/db.ts:218 |
shardConfig | readonly | ShardConfig | undefined | - | db/db.ts:261 |
storageFormat | readonly | StorageFormat | undefined | - | db/db.ts:222 |
trusted | readonly | boolean | undefined | - | 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
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
| Parameter | Type |
|---|---|
e | E |
c | C |
Returns
() => void
Inherited from
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
| Parameter | Type | Description |
|---|---|---|
...pathComps | string[] | 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
| Parameter | Type | Description |
|---|---|---|
path | string | Path 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
| Parameter | Type | Description |
|---|---|---|
path | string | The 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
| Parameter | Type | Description |
|---|---|---|
path | string | If 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. |
schema | S | The 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
| Parameter | Type |
|---|---|
e | E |
c | C |
Returns
void
Inherited from
detachAll()
detachAll<
E>(e?):void
Defined in: base/emitter.ts:188
Type Parameters
| Type Parameter |
|---|
E extends "UserChanged" | "WriteFailure" | "ItemChanged" | EmitterEvent |
Parameters
| Parameter | Type |
|---|---|
e? | E |
Returns
void
Inherited from
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
| Parameter | Type |
|---|---|
e | E |
a0? | unknown |
a1? | unknown |
Returns
void
Inherited from
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
| Parameter | Type | Description |
|---|---|---|
path | string | Path 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
| Parameter | Type | Description |
|---|---|---|
repoPath | string | Path to the target repository (e.g. '/data/todos'). |
schema | S | The schema for the items. |
items | object[] | 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
| Parameter | Type | Description |
|---|---|---|
...pathComps | string[] | 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
| Parameter | Type | Description |
|---|---|---|
path | string | The 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
| Parameter | Type | Description |
|---|---|---|
path | string | Full 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
| Parameter | Type | Description |
|---|---|---|
path | string | The path for the item to create. |
schema | S | The schema to create the item with. |
data | SchemaDataType<S> | The initial data for the item. |
Returns
Promise<void>
loginWithMagicLinkEmail()
loginWithMagicLinkEmail(
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
| Parameter | Type | Description |
|---|---|---|
email | string | The 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
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
| Parameter | Type |
|---|---|
e | E |
c | C |
Returns
() => void
Inherited from
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
| Parameter | Type | Description |
|---|---|---|
path | string | The path to the given repository. |
opts? | OpenOptions | Configuration 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 Parameter | Default type |
|---|---|
IS extends Schema | - |
CTX extends ReadonlyJSONValue | - |
OS extends Schema | IS |
Parameters
| Parameter | Type | Description |
|---|---|---|
config | Omit<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
| Parameter | Type | Description |
|---|---|---|
...pathComps | string[] | A full path or path components. |
Returns
Repository<MemRepoStorage>
The repository instance or undefined.
resume()
protectedresume():void
Defined in: base/emitter.ts:286
Returns
void
Inherited from
suspend()
protectedsuspend():void
Defined in: base/emitter.ts:284
Returns
void
Inherited from
sync()
sync(
path):Promise<SyncResult>
Defined in: db/db.ts:882
Syncs the given repository with all configured peers and waits for completion.
Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | Path 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