UNPKG

@datastax/astra-mongoose

Version:

Astra's NodeJS Mongoose compatibility client

239 lines (238 loc) 10.3 kB
import { Collection, MongooseCollectionOptions } from './collection'; import { AstraDbAdmin, AlterTypeOptions, CollectionDescriptor, CommandFailedEvent, CommandStartedEvent, CommandSucceededEvent, CommandWarningsEvent, CreateAstraKeyspaceOptions, CreateCollectionOptions, CreateDataAPIKeyspaceOptions, CreateTableDefinition, CreateTableOptions, CreateTypeDefinition, DataAPIDbAdmin, DropCollectionOptions, DropTableOptions, DropTypeOptions, ListCollectionsOptions, ListTablesOptions, LoggingEvent, RawDataAPIResponse, SomeRow, TableDescriptor, TypeDescriptor, WithTimeout } from '@datastax/astra-db-ts'; import { CollectionsDb, TablesDb } from './db'; import { default as MongooseConnection } from 'mongoose/lib/connection'; import type { ConnectOptions, Mongoose, Model } from 'mongoose'; import { DataAPIClient } from '@datastax/astra-db-ts'; interface ConnectOptionsInternal extends ConnectOptions { isTable?: boolean; isAstra?: boolean; _fireAndForget?: boolean; username?: string; password?: string; autoIndex?: boolean; autoCreate?: boolean; sanitizeFilter?: boolean; bufferCommands?: boolean; debug?: boolean | ((name: string, fn: string, ...args: unknown[]) => void) | null; logging?: LoggingEvent; } interface ConnectionEvents { commandStarted: CommandStartedEvent; commandFailed: CommandFailedEvent; commandSucceeded: CommandSucceededEvent; commandWarnings: CommandWarningsEvent; } /** * Extends Mongoose's Connection class to provide compatibility with Data API. Responsible for maintaining the * connection to Data API. */ export declare class Connection extends MongooseConnection { debugType: string; initialConnection: Promise<Connection> | null; client: DataAPIClient | null; admin: AstraDbAdmin | DataAPIDbAdmin | null; db: CollectionsDb | TablesDb | null; keyspaceName: string | null; config?: ConnectOptionsInternal; baseUrl: string | null; baseApiPath: string | null; models: Record<string, Model<unknown>>; _debug?: boolean | ((name: string, fn: string, ...args: unknown[]) => void) | null; private _dbEventListeners?; constructor(base: Mongoose); /** * Helper borrowed from Mongoose to wait for the connection to finish connecting. Because Mongoose * supports creating a new connection, registering some models, and connecting to the database later. * This method is private and should not be called by clients. * * #### Example: * const conn = mongoose.createConnection(); * // This may call `createCollection()` internally depending on `autoCreate` option, even though * // this connection hasn't connected to the database yet. * conn.model('Test', mongoose.Schema({ name: String })); * await conn.openUri(uri); * * @ignore */ _waitForClient(): Promise<{ db: CollectionsDb | TablesDb; admin: AstraDbAdmin | DataAPIDbAdmin; }>; /** * Get a collection by name. Cached in `this.collections`. * @param name * @param options */ collection<DocType extends Record<string, unknown> = Record<string, unknown>>(name: string, options?: MongooseCollectionOptions): Collection<DocType>; /** * Create a new collection in the database * @param name The name of the collection to create * @param options */ createCollection<DocType extends Record<string, unknown> = Record<string, unknown>>(name: string, options?: CreateCollectionOptions<DocType>): Promise<import("@datastax/astra-db-ts").Collection<DocType, import("@datastax/astra-db-ts").FoundDoc<DocType>>>; /** * Get current debug setting, accounting for potential changes to global debug config (`mongoose.set('debug', true | false)`) */ get debug(): boolean | ((name: string, fn: string, ...args: unknown[]) => void) | null | undefined; /** * Create a new table in the database * @param name * @param definition */ createTable<DocType extends Record<string, unknown> = Record<string, unknown>>(name: string, definition: CreateTableDefinition, options?: Omit<CreateTableOptions, 'definition'>): Promise<import("@datastax/astra-db-ts").Table<DocType, Partial<import("@datastax/astra-db-ts").FoundRow<DocType>>, import("@datastax/astra-db-ts").FoundRow<DocType>>>; /** * Drop a collection from the database * @param name */ dropCollection(name: string, options?: DropCollectionOptions): Promise<void>; /** * Drop a table from the database * @param name The name of the table to drop */ dropTable(name: string, options?: DropTableOptions): Promise<void>; /** * Create a new keyspace. * * @param name The name of the keyspace to create */ createKeyspace(name: string, options?: CreateAstraKeyspaceOptions & CreateDataAPIKeyspaceOptions): Promise<void>; /** * Not implemented. * * @ignore */ dropDatabase(): Promise<void>; /** * List all collections in the database */ listCollections(options: ListCollectionsOptions & { nameOnly: true; }): Promise<string[]>; listCollections(options?: ListCollectionsOptions & { nameOnly?: false; }): Promise<CollectionDescriptor[]>; /** * List all tables in the database */ listTables(options: ListTablesOptions & { nameOnly: true; }): Promise<string[]>; listTables(options?: ListTablesOptions & { nameOnly?: false; }): Promise<TableDescriptor[]>; /** * List all user-defined types (UDTs) in the database. * @returns An array of type descriptors. */ listTypes(options: { nameOnly: true; }): Promise<string[]>; listTypes(options?: { nameOnly?: false; }): Promise<TypeDescriptor[]>; /** * Create a new user-defined type (UDT) with the specified name and fields definition. * @param name The name of the type to create. * @param definition The definition of the fields for the type. * @returns {Promise<TypeDescriptor>} The created type descriptor. */ createType(name: string, definition: CreateTypeDefinition): Promise<void>; /** * Drop (delete) a user-defined type (UDT) by name. * @param name The name of the type to drop. * @returns The result of the dropType command. */ dropType(name: string, options?: DropTypeOptions): Promise<void>; /** * Alter a user-defined type (UDT) by renaming or adding fields. * @param name The name of the type to alter. * @param update The alterations to be made: renaming or adding fields. * @returns The result of the alterType command. */ alterType<UDTSchema extends SomeRow = SomeRow>(name: string, update: AlterTypeOptions<UDTSchema>): Promise<void>; /** * Synchronizes the set of user-defined types (UDTs) in the database. It makes existing types in the database * match the list provided by `types`. New types that are missing are created, and types that exist in the database * but are not in the input list are dropped. If a type is present in both, we add all the new type's fields to the existing type. * * @param types An array of objects each specifying the name and CreateTypeDefinition for a UDT to synchronize. * @returns An object describing which types were created, updated, or dropped. * @throws {AstraMongooseError} If an error occurs during type synchronization, with partial progress information in the error. */ syncTypes(types: { name: string; definition: CreateTypeDefinition; }[]): Promise<{ created: string[]; updated: string[]; dropped: string[]; }>; /** * Run an arbitrary Data API command on the database * @param command The command to run */ runCommand(command: Record<string, unknown>): Promise<RawDataAPIResponse>; /** * List all keyspaces. Called "listDatabases" for Mongoose compatibility */ listDatabases(options?: WithTimeout<'keyspaceAdminTimeoutMs'>): Promise<{ databases: { name: string; }[]; }>; /** * Logic for creating a connection to Data API. Mongoose calls `openUri()` internally when the * user calls `mongoose.create()` or `mongoose.createConnection(uri)` * * @param uri the connection string * @param options */ openUri(uri: string, options?: ConnectOptionsInternal): Promise<this>; /** * Create an astra-db-ts client and corresponding objects: client, db, admin. * @param uri the connection string * @param options */ createClient(uri: string, options?: ConnectOptionsInternal): Promise<this>; /** * Not supported * * @param _client * @ignore */ setClient(): void; /** * For consistency with Mongoose's API. `mongoose.createConnection(uri)` returns the connection, **not** a promise, * so the Mongoose pattern to call `createConnection()` and wait for connection to succeed is * `await createConnection(uri).asPromise()` */ asPromise(): Promise<Connection> | null; /** * Not supported * * @ignore */ startSession(): void; /** * Mongoose calls `doClose()` to close the connection when the user calls `mongoose.disconnect()` or `conn.close()`. * Handles closing the astra-db-ts client. * This method is private and should not be called by clients directly. Mongoose will call this method internally when * the user calls `mongoose.disconnect()` or `conn.close()`. * * @returns Client * @ignore */ doClose(): Promise<this>; on<K extends keyof ConnectionEvents>(event: K, listener: (event: ConnectionEvents[K]) => void): this; once<K extends keyof ConnectionEvents>(event: K, listener: (event: ConnectionEvents[K]) => void): this; emit<K extends keyof ConnectionEvents>(event: K, eventData: ConnectionEvents[K]): boolean; } interface ParsedUri { baseUrl: string; baseApiPath: string; keyspaceName: string; applicationToken?: string; } export declare const parseUri: (uri: string) => ParsedUri; export {};