createTransaction

函数: createTransaction()

ts
function createTransaction<T>(config): Transaction<T>
function createTransaction<T>(config): Transaction<T>

定义于: packages/db/src/transactions.ts:74

创建一个新的事务,用于对多个 collection 操作进行分组

类型参数

T extends object = Record<string, unknown>

参数

config

TransactionConfig<T>

包含 mutation 函数的事务配置

Returns (返回)

Transaction<T>

新的 Transaction 实例

示例

ts
// Basic transaction usage
const tx = createTransaction({
  mutationFn: async ({ transaction }) => {
    // Send all mutations to API
    await api.saveChanges(transaction.mutations)
  }
})

tx.mutate(() => {
  collection.insert({ id: "1", text: "Buy milk" })
  collection.update("2", draft => { draft.completed = true })
})

await tx.isPersisted.promise
// Basic transaction usage
const tx = createTransaction({
  mutationFn: async ({ transaction }) => {
    // Send all mutations to API
    await api.saveChanges(transaction.mutations)
  }
})

tx.mutate(() => {
  collection.insert({ id: "1", text: "Buy milk" })
  collection.update("2", draft => { draft.completed = true })
})

await tx.isPersisted.promise
ts
// Handle transaction errors
try {
  const tx = createTransaction({
    mutationFn: async () => { throw new Error("API failed") }
  })

  tx.mutate(() => {
    collection.insert({ id: "1", text: "New item" })
  })

  await tx.isPersisted.promise
} catch (error) {
  console.log('Transaction failed:', error)
}
// Handle transaction errors
try {
  const tx = createTransaction({
    mutationFn: async () => { throw new Error("API failed") }
  })

  tx.mutate(() => {
    collection.insert({ id: "1", text: "New item" })
  })

  await tx.isPersisted.promise
} catch (error) {
  console.log('Transaction failed:', error)
}
ts
// Manual commit control
const tx = createTransaction({
  autoCommit: false,
  mutationFn: async () => {
    // API call
  }
})

tx.mutate(() => {
  collection.insert({ id: "1", text: "Item" })
})

// Commit later
await tx.commit()
// Manual commit control
const tx = createTransaction({
  autoCommit: false,
  mutationFn: async () => {
    // API call
  }
})

tx.mutate(() => {
  collection.insert({ id: "1", text: "Item" })
})

// Commit later
await tx.commit()
我们的合作伙伴
Code Rabbit
Electric
Prisma
订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。

订阅 Bytes

您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。

Bytes

无垃圾邮件。您可以随时取消订阅。