5
5
> **Warning**
6
6
> This README is still under construction; parts of it may be incomplete or outdated.
7
7
8
- *This README targets v2.0.0+, which introduces a whole new API. Click [here](https://github.com/datastax/astra-db-ts/tree/v1.x?tab=readme-ov-file#datastaxastra-db-ts) for the pre-existing client readme.*
8
+ *This README targets v2.0.0+, which expands on the previous 1.x API. Click [here](https://github.com/datastax/astra-db-ts/tree/v1.x?tab=readme-ov-file#datastaxastra-db-ts) for the pre-existing client readme.*
9
9
10
10
## Table of contents
11
11
- [Quickstart](#quickstart)
12
12
- [Collections](#collections)
13
13
- [Tables](#tables)
14
14
- [High-level architecture](#high-level-architecture)
15
- - [Getting the most out of the typing](#getting-the-most-out-of-the-typing)
16
- - [Working with Dates](#working-with-dates)
17
- - [Working with ObjectIds and UUIDs](#working-with-objectids-and-uuids)
18
- - [Monitoring/logging](#monitoringlogging)
19
- - [Non-astra support](#non-astra-support)
15
+ - [Options hierarchy](#options-hierarchy)
16
+ - [Datatypes](#datatypes)
17
+ [Non-astra support](#non-astra-support)
20
18
- [Non-standard environment support](#non-standard-environment-support)
21
19
- [HTTP/2 with minification](#http2-with-minification)
22
20
- [Browser support](#browser-support)
@@ -70,9 +68,9 @@ interface Dream extends VectorDoc {
70
68
71
69
// Let's see what we've got
72
70
const cursor = collection.find({})
73
- .sort({ vector: vector([0, 0.2, 0.4]) }) // Performing a vector search
74
- .includeSimilarity(true) // The found doc is inferred to have `$similarity` as a property now
75
- .limit(2);
71
+ .sort({ vector: vector([0, 0.2, 0.4]) }) // Performing a vector search
72
+ .includeSimilarity(true) // The found doc is inferred to have `$similarity` as a property now
73
+ .limit(2);
76
74
77
75
// This would print:
78
76
// - Surfers' paradise: 0.98238194
@@ -113,11 +111,11 @@ const mkDreamsTable = async () => await db.createTable('dreams', {
113
111
114
112
// Infer the TS-equivalent type from the table definition (like zod or arktype). Equivalent to:
115
113
//
116
- // interface TableSchema extends Row<'id'> {
117
- // id: number, -- A primary key component, so it's required
118
- // summary?: string | null, -- Not a primary key, so it's optional and may return as null when found
119
- // tags?: Set<string>, -- Sets/maps/lists are optional to insert, but will actually be returned as empty collections instead of null
120
- // vector?: DataAPIVector | null, -- Vectors, however, may be null.
114
+ // interface TableSchema {
115
+ // id: number, -- A primary key component, so it's required
116
+ // summary?: string | null, -- Not a primary key, so it's optional and may return as null when found
117
+ // tags?: Set<string>, -- Sets/maps/lists are optional to insert, but will actually be returned as empty collections instead of null
118
+ // vector?: DataAPIVector | null, -- Vectors, however, may be null.
121
119
// }
122
120
type Dream = InferTableSchema<typeof mkDreamsTable>;
123
121
@@ -181,7 +179,23 @@ type Dream = InferTableSchema<typeof mkDreamsTable>;
181
179
182
180
`astra-db-ts`'s abstractions for working at the data and admin layers are structured as depicted by this diagram:
183
181
184
- 
182
+ ```mermaid
183
+ flowchart TD
184
+ DataAPIClient -->|".db(endpoint)"| Db
185
+ DataAPIClient -->|".admin()"| AstraAdmin
186
+
187
+ Db --->|".collection(name)
188
+ .createCollection(name)"| Collection
189
+
190
+ Db --->|".table(name)
191
+ .createTable(name)"| Table
192
+
193
+ AstraAdmin -->|".dbAdmin(endpoint)
194
+ .dbAdmin(id, region)"| DbAdmin
195
+
196
+ Db -->|".admin()"| DbAdmin
197
+ DbAdmin -->|".db()"| Db
198
+ ```
185
199
186
200
Here's a small admin-oriented example:
187
201
@@ -204,139 +218,23 @@ const admin = client.admin();
204
218
})();
205
219
```
206
220
207
- ## Getting the most out of the typing
208
-
209
- `astra-db-ts` is a typescript-first library, performing minimal runtime type-checking. As such, it provides
210
- a rich set of types to help you write type-safe code.
211
-
212
- Here are some examples of how you can properly leverage types to make your code more robust:
213
-
214
- ```typescript
215
- // First of all:
216
- // I *highly* recommend writing your query objects & filter objects and such inline with the methods
217
- // to get the best possible type-checking and autocomplete
218
-
219
- import { DataAPIClient, StrictFilter, StrictSort, UUID } from '@datastax/astra-db-ts';
220
-
221
- const client = new DataAPIClient('*TOKEN*');
222
- const db = client.db('*ENDPOINT*', { namespace: '*NAMESPACE*' });
223
-
224
- // You can strictly type your collections for proper type-checking
225
- interface Person {
226
- _id: UUID,
227
- name: string,
228
- interests: {
229
- favoriteBand?: string,
230
- friend?: UUID,
231
- }
232
- }
233
-
234
- (async () => {
235
- // Create your collections with a defaultId type to enforce the type of the _id field
236
- // (Otherwise it'll default to a string UUID that wouldn't be deserialized as a UUID by the client)
237
- const collection = await db.createCollection<Person>('my_collection', { defaultId: { type: 'uuidv7' } });
238
-
239
- // Now it'll raise type-errors if you try to insert a document with the wrong shape
240
- await collection.insertOne({
241
- _id: new UUID('e7f1f3a0-7e3d-11eb-9439-0242ac130002'),
242
- name: 'John',
243
- interests: {
244
- favoriteBand: 'Nightwish',
245
- },
246
- // @ts-expect-error - 'eyeColor' does not exist in type MaybeId<Person>
247
- eyeColor: 'blue',
248
- });
249
- })();
250
- ```
251
-
252
- ## Working with Dates
253
-
254
- Native JS `Date` objects can be used anywhere in documents to represent dates and times.
221
+ ### Options hierarchy
255
222
256
- Document fields stored using the `{ $date: number }` will also be returned as Date objects when read .
223
+ Like the client hierarchy, the options for each class also exist in a hierarchy .
257
224
258
- ```typescript
259
- import { DataAPIClient } from '@datastax/astra-db-ts';
260
-
261
- // Reference an untyped collections
262
- const client = new DataAPIClient('*TOKEN*');
263
- const db = client.db('*ENDPOINT*', { namespace: '*NAMESPACE*' });
225
+ The general options for parent classes are deeply merged with the options for child classes.
264
226
265
- (async () => {
266
- const collection = await db.createCollection('dates_test');
267
-
268
- // Insert documents with some dates
269
- await collection.insertOne({ dateOfBirth: new Date(1394104654000) });
270
- await collection.insertOne({ dateOfBirth: new Date('1863-05-28') });
271
-
272
- // Update a document with a date and setting lastModified to now
273
- await collection.updateOne(
274
- {
275
- dateOfBirth: new Date('1863-05-28'),
276
- },
277
- {
278
- $set: { message: 'Happy Birthday!' },
279
- $currentDate: { lastModified: true },
280
- },
281
- );
282
-
283
- // Will print *around* `new Date()` (i.e. when server processed the request)
284
- const found = await collection.findOne({ dateOfBirth: { $lt: new Date('1900-01-01') } });
285
- console.log(found?.lastModified);
286
-
287
- // Cleanup (if desired)
288
- await collection.drop();
289
- })();
227
+ ```mermaid
228
+ graph TD
229
+ DataAPIClientOptions --> AdminOptions
230
+ DataAPIClientOptions --> DbOptions
231
+ DbOptions --> CollectionOptions
232
+ DbOptions --> TableOptions
290
233
```
291
234
292
- ## Working with ObjectIds and UUIDs
293
-
294
- `astra-db-ts` exports an `ObjectId` and `UUID` class for working with these types in the database.
295
-
296
- Note that these are custom classes, and *not* the ones from the `bson` package. Make sure you're using the right one!
235
+ ## Datatypes
297
236
298
- ```typescript
299
- import { DataAPIClient, ObjectId, UUID } from '@datastax/astra-db-ts';
300
-
301
- interface Person {
302
- _id: ObjectId | UUID,
303
- name: string,
304
- friendId?: ObjectId | UUID,
305
- }
306
-
307
- // Connect to the db
308
- const client = new DataAPIClient('*TOKEN*');
309
- const db = client.db('*ENDPOINT*', { namespace: '*NAMESPACE*' });
310
-
311
- (async () => {
312
- // Create a collections with a UUIDv7 as the default ID
313
- const collection = await db.createCollection<Person>('ids_test', { defaultId: { type: 'uuidv7' } });
314
-
315
- // You can manually set whatever ID you want
316
- await collection.insertOne({ _id: new ObjectId("65fd9b52d7fabba03349d013"), name: 'John' });
317
-
318
- // Or use the default ID
319
- await collection.insertOne({ name: 'Jane' });
320
-
321
- // Let's give Jane a friend with a UUIDv4
322
- const friendId = UUID.v4();
323
-
324
- await collection.insertOne({ name: 'Alice', _id: friendId });
325
-
326
- await collection.updateOne(
327
- { name: 'Jane' },
328
- { $set: { friendId } },
329
- );
330
-
331
- // And let's get Jane as a document
332
- // (Prints "Jane", the generated UUIDv4, and true)
333
- const jane = await collection.findOne({ name: 'Jane' });
334
- console.log(jane?.name, jane?.friendId?.toString(), friendId.equals(jane?.friendId));
335
-
336
- // Cleanup (if desired)
337
- await collection.drop();
338
- })();
339
- ```
237
+ See [DATATYPES.md](etc/docs/DATATYPES.md) for a full list of supported datatypes and their TypeScript equivalents.
340
238
341
239
## Non-astra support
342
240
@@ -354,8 +252,9 @@ const db = client.db('*ENDPOINT*');
354
252
355
253
// You'll also need to pass it to db.admin() when not using Astra for typing purposes
356
254
// If the environment does not match, an error will be thrown as a reminder
357
- const dbAdmin: DataAPIDbAdmin = db.admin({ environment: 'dse' });
358
- dbAdmin.createNamespace(...);
255
+ // `environment: 'dse'` makes the return type be `DataAPIDbAdmin`
256
+ const dbAdmin = db.admin({ environment: 'dse' });
257
+ dbAdmin.createNamespace('...');
359
258
```
360
259
361
260
The `TokenProvider` class is an extensible concept to allow you to create or even refresh your tokens
0 commit comments