CollectionImpl

Klasse: CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>

Definiert in: packages/db/src/collection.ts:204

Erweitert von

Typparameter

T extends object = Record<string, unknown>

TKey erweitert string | number = string | number

TUtils erweitert UtilsRecord = {}

TSchema extends StandardSchemaV1 = StandardSchemaV1

TInsertInput extends object = T

Konstruktoren

new CollectionImpl()

ts
new CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>(config): CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>
new CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>(config): CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>

Definiert in: packages/db/src/collection.ts:407

Erstellt eine neue Collection-Instanz

Parameter

config

CollectionConfig<T, TKey, TSchema, TInsertInput>

Konfigurationsobjekt für die Collection

Gibt zurück

CollectionImpl<T, TKey, TUtils, TSchema, TInsertInput>

Wirft

Fehler, wenn die Sync-Konfiguration fehlt

Eigenschaften

config

ts
config: CollectionConfig<T, TKey, TSchema, TInsertInput>;
config: CollectionConfig<T, TKey, TSchema, TInsertInput>;

Definiert in: packages/db/src/collection.ts:211


id

ts
id: string;
id: string;

Definiert in: packages/db/src/collection.ts:331


optimisticDeletes

ts
optimisticDeletes: Set<TKey>;
optimisticDeletes: Set<TKey>;

Definiert in: packages/db/src/collection.ts:221


optimisticUpserts

ts
optimisticUpserts: Map<TKey, T>;
optimisticUpserts: Map<TKey, T>;

Definiert in: packages/db/src/collection.ts:220


pendingSyncedTransactions

ts
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];
pendingSyncedTransactions: PendingSyncedTransaction<T>[] = [];

Definiert in: packages/db/src/collection.ts:215


syncedData

ts
syncedData: Map<TKey, T> | SortedMap<TKey, T>;
syncedData: Map<TKey, T> | SortedMap<TKey, T>;

Definiert in: packages/db/src/collection.ts:216


syncedMetadata

ts
syncedMetadata: Map<TKey, unknown>;
syncedMetadata: Map<TKey, unknown>;

Definiert in: packages/db/src/collection.ts:217


transactions

ts
transactions: SortedMap<string, Transaction<any>>;
transactions: SortedMap<string, Transaction<any>>;

Definiert in: packages/db/src/collection.ts:214


utils

ts
utils: Record<string, Fn> = {};
utils: Record<string, Fn> = {};

Definiert in: packages/db/src/collection.ts:238

Accessors

indexes

Get-Signatur

ts
get indexes(): Map<number, BaseIndex<TKey>>
get indexes(): Map<number, BaseIndex<TKey>>

Definiert in: packages/db/src/collection.ts:1439

Gibt aufgelöste Indizes für die Abfrageoptimierung zurück

Gibt zurück

Map<number, BaseIndex<TKey>>


size

Get-Signatur

ts
get size(): number
get size(): number

Definiert in: packages/db/src/collection.ts:995

Gibt die aktuelle Größe der Collection zurück (gecached)

Gibt zurück

number


state

Get-Signatur

ts
get state(): Map<TKey, T>
get state(): Map<TKey, T>

Definiert in: packages/db/src/collection.ts:2038

Ruft den aktuellen Zustand der Collection als Map ab

Beispiel
ts
const itemsMap = collection.state
console.log(`Collection has ${itemsMap.size} items`)

for (const [key, item] of itemsMap) {
  console.log(`${key}: ${item.title}`)
}

// Check if specific item exists
if (itemsMap.has("todo-1")) {
  console.log("Todo 1 exists:", itemsMap.get("todo-1"))
}
const itemsMap = collection.state
console.log(`Collection has ${itemsMap.size} items`)

for (const [key, item] of itemsMap) {
  console.log(`${key}: ${item.title}`)
}

// Check if specific item exists
if (itemsMap.has("todo-1")) {
  console.log("Todo 1 exists:", itemsMap.get("todo-1"))
}
Gibt zurück

Map<TKey, T>

Map mit allen Elementen in der Collection, wobei die Schlüssel die Identifikatoren sind


status

Get-Signatur

ts
get status(): CollectionStatus
get status(): CollectionStatus

Definiert in: packages/db/src/collection.ts:336

Ruft den aktuellen Status der Collection ab

Gibt zurück

CollectionStatus


toArray

Get-Signatur

ts
get toArray(): T[]
get toArray(): T[]

Definiert in: packages/db/src/collection.ts:2071

Ruft den aktuellen Zustand der Collection als Array ab

Gibt zurück

T[]

Ein Array, das alle Elemente in der Collection enthält

Methoden

[iterator]()

ts
iterator: IterableIterator<[TKey, T]>
iterator: IterableIterator<[TKey, T]>

Definiert in: packages/db/src/collection.ts:1046

Holt alle Einträge (virtueller abgeleiteter Zustand)

Gibt zurück

IterableIterator<[TKey, T]>


cleanup()

ts
cleanup(): Promise<void>
cleanup(): Promise<void>

Definiert in: packages/db/src/collection.ts:583

Räumt die Collection auf, indem die Synchronisierung gestoppt und die Daten gelöscht werden. Kann manuell oder automatisch durch Garbage Collection aufgerufen werden.

Gibt zurück

Promise<void>


commitPendingTransactions()

ts
commitPendingTransactions(): void
commitPendingTransactions(): void

Definiert in: packages/db/src/collection.ts:1082

Versucht, ausstehende synchronisierte Transaktionen zu committen, wenn keine aktiven Transaktionen vorhanden sind. Diese Methode verarbeitet Operationen aus ausstehenden Transaktionen und wendet sie auf die synchronisierten Daten an.

Gibt zurück

void


createIndex()

ts
createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>
createIndex<TResolver>(indexCallback, config): IndexProxy<TKey>

Definiert in: packages/db/src/collection.ts:1344

Erstellt einen Index für eine Collection für schnellere Abfragen. Indizes verbessern die Abfrageleistung erheblich, indem sie Binärsuchen und Bereichsabfragen anstelle von vollständigen Scans ermöglichen.

Typparameter

TResolver erweitert IndexResolver<TKey> = typeof BTreeIndex

Der Typ des Index-Resolvers (Konstruktor oder asynchroner Lader)

Parameter

indexCallback

(row) => any

Funktion, die den indizierten Wert aus jedem Element extrahiert

config

IndexOptions<TResolver> = {}

Konfiguration, einschließlich Index-Typ und typenspezifischen Optionen

Gibt zurück

IndexProxy<TKey>

Ein Index-Proxy, der Zugriff auf den Index bietet, sobald er bereit ist

Beispiel

ts
// Create a default B+ tree index
const ageIndex = collection.createIndex((row) => row.age)

// Create a ordered index with custom options
const ageIndex = collection.createIndex((row) => row.age, {
  indexType: BTreeIndex,
  options: { compareFn: customComparator },
  name: 'age_btree'
})

// Create an async-loaded index
const textIndex = collection.createIndex((row) => row.content, {
  indexType: async () => {
    const { FullTextIndex } = await import('./indexes/fulltext.js')
    return FullTextIndex
  },
  options: { language: 'en' }
})
// Create a default B+ tree index
const ageIndex = collection.createIndex((row) => row.age)

// Create a ordered index with custom options
const ageIndex = collection.createIndex((row) => row.age, {
  indexType: BTreeIndex,
  options: { compareFn: customComparator },
  name: 'age_btree'
})

// Create an async-loaded index
const textIndex = collection.createIndex((row) => row.content, {
  indexType: async () => {
    const { FullTextIndex } = await import('./indexes/fulltext.js')
    return FullTextIndex
  },
  options: { language: 'en' }
})

currentStateAsChanges()

ts
currentStateAsChanges(options): ChangeMessage<T, string | number>[]
currentStateAsChanges(options): ChangeMessage<T, string | number>[]

Definiert in: packages/db/src/collection.ts:2113

Gibt den aktuellen Zustand der Collection als Array von Änderungen zurück

Parameter

options

CurrentStateAsChangesOptions<T> = {}

Optionen, einschließlich eines optionalen Where-Filters

Gibt zurück

ChangeMessage<T, string | number>[]

Ein Array von Änderungen

Beispiel

ts
// Get all items as changes
const allChanges = collection.currentStateAsChanges()

// Get only items matching a condition
const activeChanges = collection.currentStateAsChanges({
  where: (row) => row.status === 'active'
})

// Get only items using a pre-compiled expression
const activeChanges = collection.currentStateAsChanges({
  whereExpression: eq(row.status, 'active')
})
// Get all items as changes
const allChanges = collection.currentStateAsChanges()

// Get only items matching a condition
const activeChanges = collection.currentStateAsChanges({
  where: (row) => row.status === 'active'
})

// Get only items using a pre-compiled expression
const activeChanges = collection.currentStateAsChanges({
  whereExpression: eq(row.status, 'active')
})

delete()

ts
delete(keys, config?): Transaction<any>
delete(keys, config?): Transaction<any>

Definiert in: packages/db/src/collection.ts:1939

Löscht ein oder mehrere Elemente aus der Collection

Parameter

keys

Einzelner Schlüssel oder Array von Schlüsseln zum Löschen

TKey | TKey[]

config?

OperationConfig

Optionale Konfiguration, einschließlich Metadaten

Gibt zurück

Transaction<any>

Ein Transaction-Objekt, das die Löschoperation(en) darstellt

Beispiele

ts
// Delete a single item
const tx = collection.delete("todo-1")
await tx.isPersisted.promise
// Delete a single item
const tx = collection.delete("todo-1")
await tx.isPersisted.promise
ts
// Delete multiple items
const tx = collection.delete(["todo-1", "todo-2"])
await tx.isPersisted.promise
// Delete multiple items
const tx = collection.delete(["todo-1", "todo-2"])
await tx.isPersisted.promise
ts
// Delete with metadata
const tx = collection.delete("todo-1", { metadata: { reason: "completed" } })
await tx.isPersisted.promise
// Delete with metadata
const tx = collection.delete("todo-1", { metadata: { reason: "completed" } })
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.delete("item-1")
  await tx.isPersisted.promise
  console.log('Delete successful')
} catch (error) {
  console.log('Delete failed:', error)
}
// Handle errors
try {
  const tx = collection.delete("item-1")
  await tx.isPersisted.promise
  console.log('Delete successful')
} catch (error) {
  console.log('Delete failed:', error)
}

entries()

ts
entries(): IterableIterator<[TKey, T]>
entries(): IterableIterator<[TKey, T]>

Definiert in: packages/db/src/collection.ts:1034

Holt alle Einträge (virtueller abgeleiteter Zustand)

Gibt zurück

IterableIterator<[TKey, T]>


forEach()

ts
forEach(callbackfn): void
forEach(callbackfn): void

Definiert in: packages/db/src/collection.ts:1055

Führt eine Rückruffunktion für jeden Eintrag in der Collection aus

Parameter

callbackfn

(value, key, index) => void

Gibt zurück

void


generateGlobalKey()

ts
generateGlobalKey(key, item): string
generateGlobalKey(key, item): string

Definiert in: packages/db/src/collection.ts:1306

Parameter

key

any

item

any

Gibt zurück

string


get()

ts
get(key): undefined | T
get(key): undefined | T

Definiert in: packages/db/src/collection.ts:959

Ruft den aktuellen Wert für einen Schlüssel ab (virtueller abgeleiteter Zustand)

Parameter

key

TKey

Gibt zurück

undefined | T


getKeyFromItem()

ts
getKeyFromItem(item): TKey
getKeyFromItem(item): TKey

Definiert in: packages/db/src/collection.ts:1302

Parameter

item

T

Gibt zurück

TKey


has()

ts
has(key): boolean
has(key): boolean

Definiert in: packages/db/src/collection.ts:977

Prüft, ob ein Schlüssel in der Collection vorhanden ist (virtueller abgeleiteter Zustand)

Parameter

key

TKey

Gibt zurück

boolean


insert()

ts
insert(data, config?): 
  | Transaction<Record<string, unknown>>
| Transaction<T>
insert(data, config?): 
  | Transaction<Record<string, unknown>>
| Transaction<T>

Definiert in: packages/db/src/collection.ts:1594

Fügt ein oder mehrere Elemente in die Collection ein

Parameter

data

TInsertInput | TInsertInput[]

config?

InsertConfig

Optionale Konfiguration, einschließlich Metadaten

Gibt zurück

| Transaction<Record<string, unknown>> | Transaction<T>

Ein Transaction-Objekt, das die Einfügeoperation(en) darstellt

Wirft

Wenn die Daten die Schema-Validierung nicht bestehen

Beispiele

ts
// Insert a single todo (requires onInsert handler)
const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
await tx.isPersisted.promise
// Insert a single todo (requires onInsert handler)
const tx = collection.insert({ id: "1", text: "Buy milk", completed: false })
await tx.isPersisted.promise
ts
// Insert multiple todos at once
const tx = collection.insert([
  { id: "1", text: "Buy milk", completed: false },
  { id: "2", text: "Walk dog", completed: true }
])
await tx.isPersisted.promise
// Insert multiple todos at once
const tx = collection.insert([
  { id: "1", text: "Buy milk", completed: false },
  { id: "2", text: "Walk dog", completed: true }
])
await tx.isPersisted.promise
ts
// Insert with metadata
const tx = collection.insert({ id: "1", text: "Buy groceries" },
  { metadata: { source: "mobile-app" } }
)
await tx.isPersisted.promise
// Insert with metadata
const tx = collection.insert({ id: "1", text: "Buy groceries" },
  { metadata: { source: "mobile-app" } }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.insert({ id: "1", text: "New item" })
  await tx.isPersisted.promise
  console.log('Insert successful')
} catch (error) {
  console.log('Insert failed:', error)
}
// Handle errors
try {
  const tx = collection.insert({ id: "1", text: "New item" })
  await tx.isPersisted.promise
  console.log('Insert successful')
} catch (error) {
  console.log('Insert failed:', error)
}

isReady()

ts
isReady(): boolean
isReady(): boolean

Definiert in: packages/db/src/collection.ts:294

Prüft, ob die Collection für die Nutzung bereit ist. Gibt true zurück, wenn die Collection von ihrer Sync-Implementierung als bereit markiert wurde.

Gibt zurück

boolean

true, wenn die Collection bereit ist, andernfalls false

Beispiel

ts
if (collection.isReady()) {
  console.log('Collection is ready, data is available')
  // Safe to access collection.state
} else {
  console.log('Collection is still loading')
}
if (collection.isReady()) {
  console.log('Collection is ready, data is available')
  // Safe to access collection.state
} else {
  console.log('Collection is still loading')
}

keys()

ts
keys(): IterableIterator<TKey>
keys(): IterableIterator<TKey>

Definiert in: packages/db/src/collection.ts:1002

Holt alle Schlüssel (virtueller abgeleiteter Zustand)

Gibt zurück

IterableIterator<TKey>


map()

ts
map<U>(callbackfn): U[]
map<U>(callbackfn): U[]

Definiert in: packages/db/src/collection.ts:1067

Erstellt ein neues Array mit den Ergebnissen des Aufrufs einer Funktion für jeden Eintrag in der Collection

Typparameter

U

Parameter

callbackfn

(value, key, index) => U

Gibt zurück

U[]


onFirstReady()

ts
onFirstReady(callback): void
onFirstReady(callback): void

Definiert in: packages/db/src/collection.ts:272

Registriert eine Rückruffunktion, die ausgeführt werden soll, wenn die Collection zum ersten Mal bereit wird. Nützlich für das Vorladen von Collections.

Parameter

callback

() => void

Funktion, die aufgerufen werden soll, wenn die Collection zum ersten Mal bereit wird

Gibt zurück

void

Beispiel

ts
collection.onFirstReady(() => {
  console.log('Collection is ready for the first time')
  // Safe to access collection.state now
})
collection.onFirstReady(() => {
  console.log('Collection is ready for the first time')
  // Safe to access collection.state now
})

onTransactionStateChange()

ts
onTransactionStateChange(): void
onTransactionStateChange(): void

Definiert in: packages/db/src/collection.ts:2271

Löst eine Neuberechnung aus, wenn sich Transaktionen ändern. Diese Methode sollte von der Transaction-Klasse aufgerufen werden, wenn sich der Zustand ändert.

Gibt zurück

void


preload()

ts
preload(): Promise<void>
preload(): Promise<void>

Definiert in: packages/db/src/collection.ts:544

Lädt die Collection-Daten vor, indem die Synchronisierung gestartet wird, falls sie noch nicht gestartet wurde. Mehrere gleichzeitige Aufrufe teilen sich dasselbe Promise.

Gibt zurück

Promise<void>


startSyncImmediate()

ts
startSyncImmediate(): void
startSyncImmediate(): void

Definiert in: packages/db/src/collection.ts:450

Synchronisierung sofort starten – interne Methode für kompilierte Abfragen. Dies umgeht das Lazy Loading für spezielle Fälle wie Live-Abfrageergebnisse.

Gibt zurück

void


stateWhenReady()

ts
stateWhenReady(): Promise<Map<TKey, T>>
stateWhenReady(): Promise<Map<TKey, T>>

Definiert in: packages/db/src/collection.ts:2052

Ruft den aktuellen Zustand der Collection als Map ab, löst jedoch erst auf, wenn Daten verfügbar sind. Wartet, bis der erste Sync-Commit abgeschlossen ist, bevor er aufgelöst wird.

Gibt zurück

Promise<Map<TKey, T>>

Promise, der zu einer Map mit allen Elementen in der Collection aufgelöst wird


subscribeChanges()

ts
subscribeChanges(callback, options): () => void
subscribeChanges(callback, options): () => void

Definiert in: packages/db/src/collection.ts:2158

Änderungen in der Collection abonnieren

Parameter

callback

(changes) => void

Funktion, die aufgerufen wird, wenn sich Elemente ändern

optionen

SubscribeChangesOptions<T> = {}

Abonnementoptionen, einschließlich includeInitialState und Where-Filter

Gibt zurück

Funktion

Deabonnement-Funktion – Rufen Sie diese auf, um auf Änderungen zu hören

Gibt zurück

void

Beispiele

ts
// Basic subscription
const unsubscribe = collection.subscribeChanges((changes) => {
  changes.forEach(change => {
    console.log(`${change.type}: ${change.key}`, change.value)
  })
})

// Later: unsubscribe()
// Basic subscription
const unsubscribe = collection.subscribeChanges((changes) => {
  changes.forEach(change => {
    console.log(`${change.type}: ${change.key}`, change.value)
  })
})

// Later: unsubscribe()
ts
// Include current state immediately
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, { includeInitialState: true })
// Include current state immediately
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, { includeInitialState: true })
ts
// Subscribe only to changes matching a condition
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, {
  includeInitialState: true,
  where: (row) => row.status === 'active'
})
// Subscribe only to changes matching a condition
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, {
  includeInitialState: true,
  where: (row) => row.status === 'active'
})
ts
// Subscribe using a pre-compiled expression
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, {
  includeInitialState: true,
  whereExpression: eq(row.status, 'active')
})
// Subscribe using a pre-compiled expression
const unsubscribe = collection.subscribeChanges((changes) => {
  updateUI(changes)
}, {
  includeInitialState: true,
  whereExpression: eq(row.status, 'active')
})

subscribeChangesKey()

ts
subscribeChangesKey(
   key, 
   listener, 
   __namedParameters): () => void
subscribeChangesKey(
   key, 
   listener, 
   __namedParameters): () => void

Definiert in: packages/db/src/collection.ts:2197

Änderungen für einen bestimmten Schlüssel abonnieren

Parameter

key

TKey

listener

ChangeListener<T, TKey>

__namedParameters
includeInitialState?

boolean = false

Gibt zurück

Funktion

Gibt zurück

void


toArrayWhenReady()

ts
toArrayWhenReady(): Promise<T[]>
toArrayWhenReady(): Promise<T[]>

Definiert in: packages/db/src/collection.ts:2081

Ruft den aktuellen Zustand der Collection als Array ab, löst jedoch erst auf, wenn Daten verfügbar sind. Wartet, bis der erste Sync-Commit abgeschlossen ist, bevor er aufgelöst wird.

Gibt zurück

Promise<T[]>

Promise, der zu einem Array mit allen Elementen in der Collection aufgelöst wird


update()

Call-Signatur

ts
update<TItem>(key, callback): Transaction
update<TItem>(key, callback): Transaction

Definiert in: packages/db/src/collection.ts:1725

Aktualisiert ein oder mehrere Elemente in der Collection mithilfe einer Rückruffunktion

Typparameter

TItem erweitert object = T

Parameter
key

unbekannt[]

callback

(drafts) => void

Gibt zurück

Transaction

Ein Transaction-Objekt, das die Updateoperation(en) darstellt

Wirft

Wenn die aktualisierten Daten die Schema-Validierung nicht bestehen

Beispiele
ts
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
ts
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
ts
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}

Aufruf-Signatur

ts
update<TItem>(
   keys, 
   config, 
   callback): Transaction
update<TItem>(
   keys, 
   config, 
   callback): Transaction

Definiert in: packages/db/src/collection.ts:1731

Aktualisiert ein oder mehrere Elemente in der Collection mithilfe einer Rückruffunktion

Typparameter

TItem erweitert object = T

Parameter
keys

unbekannt[]

Einzelner Schlüssel oder Array von Schlüsseln zum Aktualisieren

config

OperationConfig

callback

(drafts) => void

Gibt zurück

Transaction

Ein Transaction-Objekt, das die Updateoperation(en) darstellt

Wirft

Wenn die aktualisierten Daten die Schema-Validierung nicht bestehen

Beispiele
ts
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
ts
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
ts
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}

Aufruf-Signatur

ts
update<TItem>(id, callback): Transaction
update<TItem>(id, callback): Transaction

Definiert in: packages/db/src/collection.ts:1738

Aktualisiert ein oder mehrere Elemente in der Collection mithilfe einer Rückruffunktion

Typparameter

TItem erweitert object = T

Parameter
id

unbekannt

callback

(draft) => void

Gibt zurück

Transaction

Ein Transaction-Objekt, das die Updateoperation(en) darstellt

Wirft

Wenn die aktualisierten Daten die Schema-Validierung nicht bestehen

Beispiele
ts
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
ts
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
ts
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}

Aufruf-Signatur

ts
update<TItem>(
   id, 
   config, 
   callback): Transaction
update<TItem>(
   id, 
   config, 
   callback): Transaction

Definiert in: packages/db/src/collection.ts:1744

Aktualisiert ein oder mehrere Elemente in der Collection mithilfe einer Rückruffunktion

Typparameter

TItem erweitert object = T

Parameter
id

unbekannt

config

OperationConfig

callback

(draft) => void

Gibt zurück

Transaction

Ein Transaction-Objekt, das die Updateoperation(en) darstellt

Wirft

Wenn die aktualisierten Daten die Schema-Validierung nicht bestehen

Beispiele
ts
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
// Update single item by key
const tx = collection.update("todo-1", (draft) => {
  draft.completed = true
})
await tx.isPersisted.promise
ts
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
// Update multiple items
const tx = collection.update(["todo-1", "todo-2"], (drafts) => {
  drafts.forEach(draft => { draft.completed = true })
})
await tx.isPersisted.promise
ts
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
// Update with metadata
const tx = collection.update("todo-1",
  { metadata: { reason: "user update" } },
  (draft) => { draft.text = "Updated text" }
)
await tx.isPersisted.promise
ts
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}
// Handle errors
try {
  const tx = collection.update("item-1", draft => { draft.value = "new" })
  await tx.isPersisted.promise
  console.log('Update successful')
} catch (error) {
  console.log('Update failed:', error)
}

values()

ts
values(): IterableIterator<T>
values(): IterableIterator<T>

Definiert in: packages/db/src/collection.ts:1022

Holt alle Werte (virtueller abgeleiteter Zustand)

Gibt zurück

IterableIterator<T>

Unsere Partner
Code Rabbit
Electric
Prisma
Bytes abonnieren

Ihre wöchentliche Dosis JavaScript-Nachrichten. Jeden Montag kostenlos an über 100.000 Entwickler geliefert.

Bytes

Kein Spam. Jederzeit kündbar.

Bytes abonnieren

Ihre wöchentliche Dosis JavaScript-Nachrichten. Jeden Montag kostenlos an über 100.000 Entwickler geliefert.

Bytes

Kein Spam. Jederzeit kündbar.