TypeScript client usage
This page provides language-specific guidance for using the Data API TypeScript client.
For information about installing and getting started with the TypeScript client, see Get started with the Data API.
Client hierarchy
When you create apps using the Data API clients, you must instantiate a DataAPIClient
object.
The DataAPIClient
object serves as the entry point to the client hierarchy. It includes the following concepts:
Adjacent to these concepts are the administration classes for database administration. The specific administration classes you use, and how you instantiate them, depends on your client language and database type (Astra DB, HCD, or DSE).
-
-
AstraDbAdmin
orDataAPIDbAdmin
-
You directly instantiate the DataAPIClient
object only.
Then, through the DataAPIClient
object, you can instantiate and access other classes and concepts.
Where necessary, instructions for instantiating other classes are provided in the command reference relevant to each class.
For instructions for instantiating the DataAPIClient
object, see Instantiate a client object.
Options hierarchy
These concepts are the same for both the 1.x and 2.x versions of the TypeScript client, but specific names can change between major versions.
For example, |
Like the client hierarchy, the options for each class also exist in a hierarchy. The general options for parent classes are deeply merged with the options for child classes.
The root of the hierarchy is the DataAPIClientOptions
, which branches into AdminOptions
and DbOptions
.
These options further branch into TableOptions
and CollectionOptions
, with settings merged from parent to child.
For the full list of available options at each level, see the TypeScript client reference.
TimeoutDescriptor
|
Timeout defaults
The timeoutDefaults
option, of type Partial<TimeoutDescriptor>
, is present throughout the options hierarchy.
It represents the group of timeouts that cover any operation the client can perform, including individual and multi-call methods, as well as the time required to make the actual request call.
All timeout values are expressed in milliseconds.
A timeout of 0
disables that timeout, but operations associated with that timeout setting can still follow other concurrent timeouts to limit their duration.
Most operations are subject to two different, concurrent timeouts.
For example, the total duration of multi-call methods is limited by the method-specific timeout, such as generalMethodTimeoout
or keyspaceAdminTimeout
.
Meanwhile, each underlying HTTP request is independently subject to the requestTimeout
.
Per-method timeouts
For all methods that issue HTTP requests, you can override the method’s timeouts through the timeout
option field.
The timeout
field is always in the omnipresent options
parameters, and there are two ways that you can set it:
-
Set it to a plain
number
, which resolves to the most appropriate timeout for the operation. -
Set it to a subset of
TimeoutDescriptor
, which provides slighly more fine-grained control over the timeouts.
You can check method signatures/autocomplete to find the timeouts that are available for each method.
Timeout errors
If a timeout occurs, a DataAPITimeoutException
or DevOpsAPITimeoutError
is thrown, depending on the operation being performed at the time and the database type (DevOpsAPITimeoutError
only occurs for Astra DB database).
To help you debug the error, the error and error message include the timeout fields that hit their defined timeout limit.
Timeout fields
Name | Default | Summary |
---|---|---|
|
|
The timeout imposed on a single HTTP request. This applies to HTTP requests to both the Data API and DevOps API, with the exception of API calls that inherently take a long time to resolve, such as |
|
|
The timeout imposed on the overall duration of a method invocation. It is valid for all DML methods that aren’t concerned with schema or admin operations. For single-call methods, such as For methods that can take multiple HTTP calls, |
|
|
A timeout imposed on all collection-related schema/admin operations, such as Except |
|
|
A timeout for all table-related schema/admin operations, such as Each individual request issued as part of these operations must obey |
|
|
A timeout for all database-related schema/admin operations, such as The longest running operations in this class are Each individual request issued as part of these operations must obey |
|
|
A timeout for all keyspace-related operations, such as Each individual request issued as part of these operations must obey |
FindCursor
This following information applies to TypeScript client version 2.0-preview or later. Earlier TypeScript client versions also has a
For more information about moving from 1.x to 2.x, see Data API client upgrade guide. |
When you call a find
command on a Table
or a Collection
, a FindCursor
object is returned.
FindCursor
objects also have the subclassed forms TableFindCursor
and CollectionFindCursor
.
FindCursor
objects represent a lazy stream of results that you can use to progressively retrieve new results (pagination).
The basic usage pattern is to consume the cursor item by item.
For example:
// Using find
to create a fully-configured TableFindCursor
object
const cursor = table.find<{ winner: number }>({ matchId: 'challenge6' }, {
projection: { winner: 1 },
limit: 3,
});
// Lazily consuming the cursor as an async iterator
for await (const item of cursor) {
console.log(item);
}
// Or if you prefer to build the cursor using a fluent interface
// Also, you can use the toArray
method to get all the results at once
const rows = await table.find({ matchId: 'challenge6' })
.project<{ winner: number }>({ winner: 1 })
.limit(3)
.toArray();
console.log(rows);
Cursor properties
Cursors have the following properties that you can inspect at any time:
Name | Return type | Summary |
---|---|---|
|
|
The current state of the cursor:
|
|
|
The number of items the cursors has yielded, meaning the number of items already read by the code consuming the cursor. |
|
|
The number of items (documents or rows) currently stored in the client-side buffer of this cursor. |
|
|
The This type can be more specific if a subclass of |
Methods that directly alter the cursor
The following methods, in addition to iterating over the cursor, alter the cursor’s internal state:
Name | Return type | Summary |
---|---|---|
|
|
Closes the cursor regardless of its You can close a cursor at any time. Closing a cursor discards any items that haven’t been consumed. You can use a closed cursor again unless you call |
|
|
Rewinds the cursor to it’s original, unconsumed state while retaining all cursor settings, such as |
|
|
Consumes (returns) up to the requested number of raw buffered items (rows or documents). Cursor mapping is not applied to these documents. The returned items are consumed, meaning that the cursor can’t return those items again. |
|
|
Consumes the remaining rows in the cursor, invoking a provided callback If the callback returns exactly Calling this method on a closed cursor results in an error. |
|
|
Converts all remaining, unconsumed rows from the cursor into a list. If the cursor is DataStax doesn’t recommend calling this method if you expect a large list of results because constructing the full list requires many data exchanges with the Data API and potentially massive memory usage. If you expect many results, DataStax recommends following a lazy pattern of iterating and consuming the rows. Calling this method on a closed cursor results in an error. |
|
|
Returns a Boolean indicating whether the cursor has more documents to return.
|
|
|
Returns the query vector used in the vector (ANN) search that originated this cursor, if applicable.
If the query wasn’t an ANN search or it was invoked without the If called an |
Methods that copy the cursor
The following methods don’t directly alter the cursor’s internal state. Instead, these methods produce a copy of the cursor with altered attributes. You can use these to fluently build up the cursor.
Except for the clone
method, these methods require that the cursor is in the 'idle'
state.
Name | Return type | Summary |
---|---|---|
|
|
Creates a new |
|
|
Returns a copy of the cursor with a new |
|
|
Return a copy of the cursor with a new To prevent typing misalignment, you can’t set |
|
|
Returns a copy of the cursor with a new |
|
|
Returns a copy of the cursor with a new |
|
|
Returns a copy of the cursor with a new To prevent typing misalignment, you can’t set |
|
|
Returns a copy of the cursor with a new |
|
|
Returns a copy of the cursor with a new |
|
|
Returns a copy of the cursor with a mapping function to transform the returned items. Calling this method on a cursor that already has a mapping causes the mapping functions to be composed. |
Collection and Table typing
This information applies to TypeScript client version 2.0-preview or later. For more information, see Data API client upgrade guide. |
The actual type signatures of Collection
and Table
aren’t standard Collection<Schema>
-like types that you may be used to.
Instead, they’re typed as follows:
class Collection<
WSchema extends SomeDoc = SomeDoc,
RSchema extends WithId<SomeDoc> = FoundDoc<WSchema>,
> {}
class Table<
WSchema extends SomeRow,
PKey extends SomeRow = Partial<FoundRow<WSchema>>,
RSchema extends SomeRow = FoundRow<WSchema>,
> {}
In astra-db-ts
version 1.x, FoundDoc
was used in the return type of find
and findOne
:
async find(filter: Filter, options: FindOneOptions): FoundDoc<Schema>;
FoundDoc
represents the type of the document as it’s read from the database:
-
For collections, this means an
_id
field is part of the type, and it won’t return$vector
or$vectorize
without an explicitprojection
.If you use a projection to exclude
_id
or include$vector
or$vectorize
, you must specify a specific type for the operation regardless. -
For tables, this means vector fields are returned as
DataAPIVector
, regardless of the input type or use of vectorize.
For most use cases, you can treat Because all type parameters have default values, the usage and behavior can be the same as if they were typed simply. This means that the following is valid:
The difference is typically negligible, with the exception of advanced use case like custom serialization/deserialization. |
If necessary, such as for advanced use cases with custom serialization/deserialization logic, you can specify dual types:
type MyPKey = Pick<MyWSchema, 'ptKey' | 'clKey'>;
const coll = await db.createCollection<MyWSchema, MyRSchema>('my_collection');
const table = await db.table<MyWSchema, MyPKey, MyRSchema>('my_table');
function useCollection<W, R>(coll: Collection<W, R>) {
// ...
}
function useTable<W, P, R>(table: Table<W, P, R>) {
// ...
}
Custom Ser/Des
Custom ser/des is a public preview feature available in TypeScript client version 2.0-preview. Features and functionality are subject to change during the preview period. These options are not recommended for production during the preview period. For information about changes in 2.0-preview and migrating from 1.x to 2x, see Data API client upgrade guide. |
You can use custom serialization and deserialization logic to customize client usage at a lower level, enabling features such as object mapping, custom data types, validation, snake case interop, and more.
Common options
-
mutateInPlace
: Enables a minor optimization to allow any given object to be mutated in-place. This means you can serialize rows, documents, filters, sorts, and so on without creating a copy of every nested object or array.Only use this option if you don’t need to reuse an object after passing it to any operation. Otherwise, unexpected mutations and behaviors can occur.
-
snakeCaseInterop
: Enables the client to automatically convert all keys in serialized objects tosnake_case
before sending them to the server, and then the client convert them back tocamelCase
when deserializing them. -
codecs
: You can use codecs to customize the way that objects are serialized and deserialized, allowing you to change data types, add validation logic, add object mapping, and more.For more information and examples, see the TypeScript client examples on GitHub.
Collection-specific options
-
enableBigNumbers
: Enables serialization ofbigint
andBigNumber
. Additionally, any number larger than the JavaScript-enforced 64-bit standard are returned asBigNumber
.
Table-specific options
-
sparseData
: Enables sparse returned rows. This means that any fields not present in the row are omitted from the returned row rather than being returned asnull
.
See also
For command specifications, see the command references, such as Work with collections, and Work with tables.
For major changes between versions, see Data API client upgrade guide.
For the complete client reference, see TypeScript client reference.