Overview

The main entrypoint into working with the Data API. It sits at the top of the conceptual hierarchy of the SDK.

The client may take in a default token, which can be overridden by a stronger/weaker token when spawning a new Db or AstraAdmin instance.

It also takes in a set of default options (see DataAPIClientOptions) that may also generally be overridden in lower classes.

Example

// Client with default token
const client = new DataAPIClient('<token>');
const db = client.db('https://<db_id>-<region>.apps.astra.datastax.com');

// Client with no default token; must provide token in .db() or .admin()
const client = new DataAPIClient();
const db = client.db('https://<db_id>-<region>.apps.astra.datastax.com', { token });

const coll = await db.collection('my_collection');

const admin1 = client.admin();
const admin2 = client.admin({ adminToken: '<stronger_token>' });

console.log(await coll.insertOne({ name: 'John Joe' }));
console.log(await admin1.listDatabases());

The options hierarchy

Like the class hierarchy aforementioned, the options for each class also form an adjacent hierarchy.

The options for any class are a deep merge of the options for the class itself and the options for its parent classes.

For example, you may set default CollectionOptions.logging options in DataAPIClientOptions.logging, and override them in the CollectionOptions themselves as desired.

Example

const client = new DataAPIClient({
logging: [{ events: 'all', emits: 'event' }],
});
const db = client.db('https://<db_id>-<region>.apps.astra.datastax.com', { token });

// Everything will still be emitted as an event,
// But now, `commandFailed` events from this collection will also log to stderr
const coll = db.collection('<name>', {
logging: [{ events: 'commandFailed', emits: ['event', 'stderr'] }],
});

Non-Astra support (DSE, HCD, etc.)

Depending on the Data API backend used, you may need to set the environment option in certain places to "dse", "hcd", etc.

See DataAPIEnvironment for all possible backends; it defaults to "astra" if not specified.

Currently, if you're not using Astra, you need to specify the environment when:

Example

// Client connecting to a local DSE instance
const dseToken = new UsernamePasswordTokenProvider('username', 'password');
const client = new DataAPIClient(dseToken, { environment: 'dse' });

See

  • DataAPIEnvironment
  • DataAPIClientOptions

Hierarchy (view full)

Constructors

  • Overview

    Constructs a new instance of the DataAPIClient without a default token. The token will instead need to be specified when calling .db() or .admin().

    Prefer this method when using a db-scoped token instead of a more universal token.

    Parameters

    Returns DataAPIClient

    Example

    const client = new DataAPIClient();

    // OK
    const db1 = client.db('<endpoint>', { token: '<token>' });

    // Will throw error as no token is ever provided
    const db2 = client.db('<endpoint>');
  • Overview

    Constructs a new instance of the DataAPIClient with a default token. This token will be used everywhere if no overriding token is provided in .db() or .admin().

    Prefer this method when using a universal/admin-scoped token.

    Parameters

    Returns DataAPIClient

    Example

    const client = new DataAPIClient('<default_token>');

    // OK
    const db1 = client.db('<endpoint>', { token: '<weaker_token>' });

    // OK; will use <default_token>
    const db2 = client.db('<endpoint>');

Properties

#options: ParsedRootClientOpts
internal: InternalLogger<DataAPIClientEventMap>

Methods

  • Overview

    Closes the client and disconnects all underlying connections. This should be called when the client is no longer needed to free up resources.

    The client will be no longer usable after this method is called.

    This method is idempotent and can be called multiple times without issue.

    Returns Promise<void>

    A promise that resolves when the client has been closed.

    Example

    const client = new DataAPIClient(...);
    await client.close();

    // Error: Can't make requests on a closed client
    const coll = client.db(...).collection(...);
    await coll.findOne();

    When to call this method

    For most users, this method isn't necessary to call, as resources will be freed up when the server is shut down or the process is killed.

    However, it's useful in long-running processes or when you want to free up resources immediately.

    Think of it as using malloc or using a file descriptor. Freeing them isn't strictly necessary when they're used for the duration of the program, but it's there for when you need it.

  • Overview

    Spawns a new Db instance using a direct endpoint and given options.


    Disclaimer

    This method does not validate the existence of the database—it simply creates a reference.**

    Note that this does not perform any I/O or validation on if the endpoint is valid or not. It's up to the user to ensure that the endpoint is correct. If you want to create an actual database, see AstraAdmin.createDatabase instead.


    The API endpoint

    This endpoint should include the protocol and the hostname, but not the path.

    If you're using Astra, this will typically be of the form https://<db_id>-<region>.apps.astra.datastax.com (the exception being private endpoints); any other database may have a completely unique domain.

    Spawning a db via just an ID and region is no longer supported in astra-db-ts 2.0+. Use the buildAstraEndpoint to create the endpoint if you need to.

    Parameters

    • endpoint: string

      The direct endpoint to use.

    • Optional options: DbOptions

      Any options to override the default options set when creating the DataAPIClient.

    Returns Db

    A new Db instance.

    Example

    const db = client.db('https://<db_id>-<region>.apps.astra.datastax.com');
    

    The options hierarchy

    The options for the Db instance are a deep merge of the options for the DataAPIClient and the options for the Db itself.

    Any options provided to DbOptions may generally also be overridden in any spawned classes' options (e.g. CollectionOptions).

    Example

    const db = client.db('https://<db_id>-<region>.apps.astra.datastax.com', {
    keyspace: 'my_keyspace',
    token: 'AstraCS:...',
    });

    const coll = db.collection('my_coll', {
    keyspace: 'other_keyspace',
    });

    Remarks

    Note that this does not perform any IO or validation on if the endpoint is valid or not. It's up to the user to ensure that the endpoint is correct. If you want to create an actual database, see AstraAdmin.createDatabase instead.

  • Subscribe to an event.

    Type Parameters

    • E extends (keyof AdminCommandEventMap) | (keyof CommandEventMap)

    Parameters

    • eventName: E

      The event to listen for.

    • listener: ((event) => void)

      The callback to invoke when the event is emitted.

    Returns (() => void)

    A function to unsubscribe the listener.

      • (): void
      • Returns void

  • Subscribe to an event once.

    The listener will be automatically unsubscribed after the first time it is called.

    Note that the listener will be unsubscribed BEFORE the actual listener callback is invoked.

    Type Parameters

    • E extends (keyof AdminCommandEventMap) | (keyof CommandEventMap)

    Parameters

    • eventName: E

      The event to listen for.

    • listener: ((event) => void)

      The callback to invoke when the event is emitted.

    Returns (() => void)

    A function to prematurely unsubscribe the listener.

      • (): void
      • Returns void

  • Remove all listeners for an event.

    If no event is provided, all listeners for all events will be removed.

    Type Parameters

    • E extends (keyof AdminCommandEventMap) | (keyof CommandEventMap)

    Parameters

    • Optional eventName: E

      The event to remove listeners for.

    Returns void