Transaction
A transaction in Valkey GLIDE allows you to execute a group of commands in a single, atomic step. This ensures that all commands in the transaction are executed sequentially and without interruption. See Valkey Transactions.
This is equivalent to the Valkey commands MULTI / EXEC.
Modes of Operation
Section titled “Modes of Operation”There are two primary modes for handling transactions in Glide:
- Standalone Mode: Use the
Transactionclass. - Cluster Mode: Use the
ClusterTransactionclass.
Reusing Transaction Objects
Section titled “Reusing Transaction Objects”Transaction objects can be reused. If you need to execute a particular group of commands multiple times, you can simply resend the same transaction object.
Example Usage
Section titled “Example Usage”Here’s a simple example demonstrating how to create and execute a transaction in standalone mode:
import {Transaction} from "@valkey/valkey-glide";
// Initialize a transaction objectconst transaction = new Transaction();
// Add commands to the transactiontransaction.set('key', 'value');transaction.select(1); // Standalone commandtransaction.get('key');
// Execute the transactionconst result = await client.exec(transaction);console.log(result); // Output: [OK, OK, null]Command Chaining
Section titled “Command Chaining”Valkey GLIDE supports command chaining within a transaction, allowing for a more concise and readable code. Here’s how you can use chaining in transactions:
import {ClusterTransaction} from "@valkey/valkey-glide";
// Initialize a cluster transaction objectconst clusterTransaction = new ClusterTransaction();
// Chain commandsclusterTransaction.set('key', 'value').get('key')
// Execute the transactionconst result = await client.exec(clusterTransaction);console.log(result); // Output: [OK, 'value']Cluster Mode Considerations: When using ClusterTransaction, all keys in the transaction must be mapped to the same slot.
Detailed Steps
Section titled “Detailed Steps”Creating a Transaction: Initialize the Transaction or ClusterTransaction object.
import {Transaction, ClusterTransaction} from "@valkey/valkey-glide";
const transaction = new Transaction(); // For standalone modeconst clusterTransaction = new ClusterTransaction(); // For cluster modeAdding Commands: Use the transaction object to queue up the desired commands.
transaction.set('key', 'value');transaction.get('key');Executing the Transaction: Use the exec method of the Valkey GLIDE client to execute the transaction.
await client.exec(transaction);Handling Results: The result of the transaction execution will be a list of responses corresponding to each command in the transaction.
const result = await client.exec(transaction)console.log(result); // Output: [OK, 'value']