Skip to main content

Transactions

Transactions in Collect allow you to execute multiple operations in a way that either all succeed or none are applied, ensuring data integrity.

Typescript Definition

declare class CollectTransaction extends CollectRestApiProxy {
// id of transaction
readonly id: string;
constructor(id: string);

// message about transaction status when creating or rolling back transaction
rollback(): Promise<{
message: string;
}>;
commit(): Promise<{
message: string;
}>;
}

Data Example

{
"id": "0191f150-752c-7dd9-8884-078ed5dae03a"
}

How it works

It's easiest to explain how transactions work without diving into code. Think of a transaction like a delivery truck. You can load many packages (operations) onto the truck and send them to their destination all at once. If the customer cancels the order, you simply unload the truck and cancel the delivery. Without transactions, you'd have to send each package individually, and if something went wrong, you'd have to retrieve each one from its destination, which can be a lot of extra work. Transactions ensure that all your packages either reach their destination together or not at all, maintaining the integrity of the process.


Create Transaction

Endpoints

Create a Transaction

POST /api/v1/transactions

To create a new transaction in Collect, simply call the .begin method on the tx object.

Request

const tx = await collect.tx.begin();

Example with TTL:

const tx = await collect.tx.begin({
ttl: 500
});

Response

{
"id": "0191f150-752c-7dd9-8884-078ed5dae03a"
}

Get Transaction

Endpoints

Get a specific Transaction

GET /api/v1/transactions/:txId

To retrieve a specific transaction in Collect, simply call the .get method on the tx object.

Request

const tx = await collect.tx.get(id);

Example with TTL:

Response

{
"id": "0191f150-752c-7dd9-8884-078ed5dae03a"
}

Commit Transaction

Endpoints

Commit a Transaction

POST /api/v1/transactions/:txId

To commit a transaction, indicating that all operations within the transaction should be applied:

Request

await tx.commit();

Response

{
"message": "Transaction (0191f150-752c-7dd9-8884-078ed5dae03a) has been successfully committed."
}

Rollback Transaction

Endpoints

Rollback a Transaction

POST /api/v1/transactions/:txId/rollback

To roll back a transaction, undoing all operations performed within it:

Request

await tx.rollback();

Response

{
"message": "Transaction (0191f150-752c-7dd9-8884-078ed5dae03a) has been rolled back."
}

Endpoints Overview

The Transaction API provides several endpoints to work with transactions. Here's an overview of all available endpoints in this section:

MethodEndpointDescription
POST/api/v1/transactionsCreate a new transaction
GET/api/v1/transactions/:txIdRetrieve a single Transaction
POST/api/v1/transactions/:txId/commitCommit the specified transaction
POST/api/v1/transactions/:txId/rollbackRollback the specified transaction