Amazon QLDB Node.js Driver

raw JSON →
3.1.0 verified Wed Apr 22 auth: no javascript

The `amazon-qldb-driver-nodejs` package provides an official Node.js driver for interacting with Amazon Quantum Ledger Database (QLDB). It simplifies common tasks like managing sessions, executing transactions, and handling retries for transient errors with QLDB. Currently at stable version 3.1.0, the driver integrates seamlessly with the AWS SDK for JavaScript V3, requiring its V3 client peer dependencies for operation. It facilitates the exchange of data using Amazon ION documents, which is QLDB's underlying immutable data format. Releases occur periodically, with significant updates often aligning with AWS SDK version changes, ensuring compatibility and leveraging the latest AWS features. This package is an official offering from AWS Labs, differentiating it from community-driven alternatives by offering direct support for QLDB's unique ledger-first, immutable data model and providing robust transaction management and error handling.

error Cannot read properties of null (reading 'executeLambda')
cause A driver session became null after a timeout and was not correctly re-established before an attempt to execute a lambda.
fix
Upgrade the amazon-qldb-driver-nodejs package to version 3.0.1 or newer, which includes a bug fix for this session management issue.
error No open transaction
cause Internal bug in older driver versions leading to incorrect transaction state management.
fix
Upgrade the amazon-qldb-driver-nodejs package to v2.2.0 or newer to resolve known transaction handling bugs.
error TypeError: Cannot read properties of undefined (reading 'Client') or similar related to @aws-sdk client
cause Missing or incompatible `@aws-sdk` peer dependencies, especially after migrating to driver v3.0.0 without updating AWS SDK client packages to their V3 versions.
fix
Install or update @aws-sdk/client-qldb and @aws-sdk/client-qldb-session to compatible V3 major versions (e.g., ^3.x.x) that align with the driver's requirements.
error Error: No QLDB Session
cause The driver failed to acquire or establish a QLDB session, typically due to incorrect AWS credentials, an invalid region configuration, or network connectivity issues.
fix
Verify that AWS credentials and region are correctly configured through environment variables, ~/.aws/config (with AWS_SDK_LOAD_CONFIG=1), or explicitly in the QLDBSessionClientConfig. Check network access to AWS QLDB endpoints and the QLDB service status.
breaking Version 3.0.0 introduced breaking changes by migrating to the AWS SDK for JavaScript V3. This requires updating all related `@aws-sdk` client dependencies to their V3 versions.
fix Follow the AWS SDK for JavaScript V3 migration guide and ensure all peer dependencies like `@aws-sdk/client-qldb-session` are updated to compatible V3 major versions (e.g., `^3.x.x`).
breaking Version 2.2.0 refined the internal retry logic and API definition more strictly. This could lead to breaking changes if the driver was being used in ways not explicitly supported by previous documentation, particularly concerning session management and error handling.
fix Review application code against the official QLDB Node.js driver documentation to ensure compliance with supported API usage and retry configurations, especially around session and transaction lifecycle.
gotcha Versions 2.0.0, 2.0.0-rc.1, 2.1.0, and 2.1.1 contained a critical bug leading to 'No open transaction' or 'Transaction already open' errors due to issues in transaction state management. These versions are unstable for production use.
fix Upgrade the driver to version 2.2.0 or newer to resolve these transaction-related stability issues. Version 2.2.0 introduced significant improvements to retry logic and session handling that mitigate these errors.
gotcha The driver explicitly requires several peer dependencies (`@aws-sdk/client-qldb`, `@aws-sdk/client-qldb-session`, `ion-js`, `jsbi`) to be installed by the consuming application. Failure to install these will result in runtime errors.
fix Ensure all required peer dependencies, especially the `@aws-sdk` client packages and `ion-js`, are explicitly installed in your project's `package.json` with compatible versions. For driver v3.x.x, `@aws-sdk` packages must also be v3.x.x.
gotcha To correctly load AWS configuration from `~/.aws/config` files, the `AWS_SDK_LOAD_CONFIG` environment variable must be set to a truthy value (e.g., '1'). Without it, region and credentials might not be loaded as expected from shared config files.
fix Set `AWS_SDK_LOAD_CONFIG=1` in your application's environment, or explicitly configure AWS credentials and region within the `QLDBSessionClientConfig` object when initializing the driver.
npm install amazon-qldb-driver-nodejs
yarn add amazon-qldb-driver-nodejs
pnpm add amazon-qldb-driver-nodejs

Initializes the QLDB driver, retrieves a list of table names, and demonstrates a basic transaction to insert a document, followed by a query to retrieve it.

import { QLDBSessionClientConfig } from "@aws-sdk/client-qldb-session";
import { QldbDriver, TransactionExecutor } from "amazon-qldb-driver-nodejs";

// Configure the QLDB session client (using AWS SDK v3)
const qldbClientConfig: QLDBSessionClientConfig = {
    region: "us-east-1", // Specify your AWS region
    credentials: {
        accessKeyId: process.env.AWS_ACCESS_KEY_ID ?? '', // Ensure AWS credentials are set
        secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY ?? ''
    }
};

// Initialize the QLDB Driver for a specific ledger
const ledgerName = "my-test-ledger"; // Replace with your QLDB ledger name
const qldbDriver: QldbDriver = new QldbDriver(ledgerName, qldbClientConfig);

async function main() {
    try {
        console.log(`Listing tables in ledger: ${ledgerName}`);
        const tableNames = await qldbDriver.getTableNames();
        console.log("Existing tables:", tableNames);

        // Example of executing a transaction to insert data
        const newDocument = {
            id: `doc-${Date.now()}`,
            name: "Example Item",
            quantity: 10,
            status: "available"
        };

        await qldbDriver.execute(async (txn: TransactionExecutor) => {
            console.log("Attempting to insert document...");
            // The driver automatically handles conversion of plain JS objects to Amazon ION
            await txn.execute(`INSERT INTO Products VALUE ?`, newDocument);
            console.log("Document inserted successfully.");
        });

        // Example of querying data
        await qldbDriver.execute(async (txn: TransactionExecutor) => {
            console.log("Querying for inserted document...");
            const result = await txn.execute(`SELECT * FROM Products WHERE id = ?`, newDocument.id);
            const docs = await result.toArray();
            console.log("Queried documents:", JSON.stringify(docs, null, 2));
        });

    } catch (error) {
        console.error("Error interacting with QLDB:", error);
    } finally {
        // Close the driver to release resources and end active sessions
        await qldbDriver.close();
        console.log("QLDB Driver closed.");
    }
}

main();