UNPKG

@azure/cosmos

Version:
1,122 lines (1,086 loc) • 182 kB
/// <reference lib="dom" /> /// <reference lib="esnext.asynciterable" /> import { AbortSignal as AbortSignal_2 } from 'node-abort-controller'; import { Pipeline } from '@azure/core-rest-pipeline'; import { TokenCredential } from '@azure/core-auth'; export declare interface Agent { maxFreeSockets: number; maxSockets: number; sockets: any; requests: any; destroy(): void; } export declare type AggregateType = "Average" | "Count" | "Max" | "Min" | "Sum"; export declare const BulkOperationType: { readonly Create: "Create"; readonly Upsert: "Upsert"; readonly Read: "Read"; readonly Delete: "Delete"; readonly Replace: "Replace"; readonly Patch: "Patch"; }; /** * Options object used to modify bulk execution. * continueOnError (Default value: false) - Continues bulk execution when an operation fails ** NOTE THIS WILL DEFAULT TO TRUE IN the 4.0 RELEASE */ export declare interface BulkOptions { continueOnError?: boolean; } export declare type BulkPatchOperation = OperationBase & { operationType: typeof BulkOperationType.Patch; id: string; }; /** * Provides iterator for change feed. * * Use `Items.changeFeed()` to get an instance of the iterator. */ export declare class ChangeFeedIterator<T> { private clientContext; private resourceId; private resourceLink; private partitionKey; private changeFeedOptions; private static readonly IfNoneMatchAllHeaderValue; private nextIfNoneMatch; private ifModifiedSince; private lastStatusCode; private isPartitionSpecified; /** * Gets a value indicating whether there are potentially additional results that can be retrieved. * * Initially returns true. This value is set based on whether the last execution returned a continuation token. * * @returns Boolean value representing if whether there are potentially additional results that can be retrieved. */ get hasMoreResults(): boolean; /** * Gets an async iterator which will yield pages of results from Azure Cosmos DB. */ getAsyncIterator(): AsyncIterable<ChangeFeedResponse<Array<T & Resource>>>; /** * Read feed and retrieves the next page of results in Azure Cosmos DB. */ fetchNext(): Promise<ChangeFeedResponse<Array<T & Resource>>>; private getFeedResponse; } /** * Specifies options for the change feed * * Some of these options control where and when to start reading from the change feed. The order of precedence is: * - continuation * - startTime * - startFromBeginning * * If none of those options are set, it will start reading changes from the first `ChangeFeedIterator.fetchNext()` call. */ export declare interface ChangeFeedOptions { /** * Max amount of items to return per page */ maxItemCount?: number; /** * The continuation token to start from. * * This is equivalent to the etag and continuation value from the `ChangeFeedResponse` */ continuation?: string; /** * The session token to use. If not specified, will use the most recent captured session token to start with. */ sessionToken?: string; /** * Signals whether to start from the beginning or not. */ startFromBeginning?: boolean; /** * Specified the start time to start reading changes from. */ startTime?: Date; } /** * A single response page from the Azure Cosmos DB Change Feed */ export declare class ChangeFeedResponse<T> { /** * Gets the items returned in the response from Azure Cosmos DB */ readonly result: T; /** * Gets the number of items returned in the response from Azure Cosmos DB */ readonly count: number; /** * Gets the status code of the response from Azure Cosmos DB */ readonly statusCode: number; /** * Gets the request charge for this request from the Azure Cosmos DB service. */ get requestCharge(): number; /** * Gets the activity ID for the request from the Azure Cosmos DB service. */ get activityId(): string; /** * Gets the continuation token to be used for continuing enumeration of the Azure Cosmos DB service. * * This is equivalent to the `etag` property. */ get continuation(): string; /** * Gets the session token for use in session consistency reads from the Azure Cosmos DB service. */ get sessionToken(): string; /** * Gets the entity tag associated with last transaction in the Azure Cosmos DB service, * which can be used as If-Non-Match Access condition for ReadFeed REST request or * `continuation` property of `ChangeFeedOptions` parameter for * `Items.changeFeed()` * to get feed changes since the transaction specified by this entity tag. * * This is equivalent to the `continuation` property. */ get etag(): string; /** * Response headers of the response from Azure Cosmos DB */ headers: CosmosHeaders; } /** * @hidden * @hidden */ export declare class ClientContext { private cosmosClientOptions; private globalEndpointManager; private readonly sessionContainer; private connectionPolicy; private pipeline; partitionKeyDefinitionCache: { [containerUrl: string]: any; }; constructor(cosmosClientOptions: CosmosClientOptions, globalEndpointManager: GlobalEndpointManager); /** @hidden */ read<T>({ path, resourceType, resourceId, options, partitionKey, }: { path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; }): Promise<Response_2<T & Resource>>; queryFeed<T>({ path, resourceType, resourceId, resultFn, query, options, partitionKeyRangeId, partitionKey, }: { path: string; resourceType: ResourceType; resourceId: string; resultFn: (result: { [key: string]: any; }) => any[]; query: SqlQuerySpec | string; options: FeedOptions; partitionKeyRangeId?: string; partitionKey?: PartitionKey; }): Promise<Response_2<T & Resource>>; getQueryPlan(path: string, resourceType: ResourceType, resourceId: string, query: SqlQuerySpec | string, options?: FeedOptions): Promise<Response_2<PartitionedQueryExecutionInfo>>; queryPartitionKeyRanges(collectionLink: string, query?: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<PartitionKeyRange>; delete<T>({ path, resourceType, resourceId, options, partitionKey, }: { path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; }): Promise<Response_2<T & Resource>>; patch<T>({ body, path, resourceType, resourceId, options, partitionKey, }: { body: any; path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; }): Promise<Response_2<T & Resource>>; create<T, U = T>({ body, path, resourceType, resourceId, options, partitionKey, }: { body: T; path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; }): Promise<Response_2<T & U & Resource>>; private processQueryFeedResponse; private applySessionToken; replace<T>({ body, path, resourceType, resourceId, options, partitionKey, }: { body: any; path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; }): Promise<Response_2<T & Resource>>; upsert<T, U = T>({ body, path, resourceType, resourceId, options, partitionKey, }: { body: T; path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; }): Promise<Response_2<T & U & Resource>>; execute<T>({ sprocLink, params, options, partitionKey, }: { sprocLink: string; params?: any[]; options?: RequestOptions; partitionKey?: PartitionKey; }): Promise<Response_2<T>>; /** * Gets the Database account information. * @param options - `urlConnection` in the options is the endpoint url whose database account needs to be retrieved. * If not present, current client's url will be used. */ getDatabaseAccount(options?: RequestOptions): Promise<Response_2<DatabaseAccount>>; getWriteEndpoint(): Promise<string>; getReadEndpoint(): Promise<string>; getWriteEndpoints(): Promise<readonly string[]>; getReadEndpoints(): Promise<readonly string[]>; batch<T>({ body, path, partitionKey, resourceId, options, }: { body: T; path: string; partitionKey: string; resourceId: string; options?: RequestOptions; }): Promise<Response_2<any>>; bulk<T>({ body, path, partitionKeyRangeId, resourceId, bulkOptions, options, }: { body: T; path: string; partitionKeyRangeId: string; resourceId: string; bulkOptions?: BulkOptions; options?: RequestOptions; }): Promise<Response_2<any>>; private captureSessionToken; clearSessionToken(path: string): void; private getSessionParams; private isMasterResource; private buildHeaders; /** * Returns collection of properties which are derived from the context for Request Creation * @returns */ private getContextDerivedPropsForRequestCreation; } export declare class ClientSideMetrics { readonly requestCharge: number; constructor(requestCharge: number); /** * Adds one or more ClientSideMetrics to a copy of this instance and returns the result. */ add(...clientSideMetricsArray: ClientSideMetrics[]): ClientSideMetrics; static readonly zero: ClientSideMetrics; static createFromArray(...clientSideMetricsArray: ClientSideMetrics[]): ClientSideMetrics; } /** * Use to read or delete a given {@link Conflict} by id. * * @see {@link Conflicts} to query or read all conflicts. */ export declare class Conflict { readonly container: Container; readonly id: string; private readonly clientContext; private partitionKey?; /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url(): string; /** * @hidden * @param container - The parent {@link Container}. * @param id - The id of the given {@link Conflict}. */ constructor(container: Container, id: string, clientContext: ClientContext, partitionKey?: PartitionKey); /** * Read the {@link ConflictDefinition} for the given {@link Conflict}. */ read(options?: RequestOptions): Promise<ConflictResponse>; /** * Delete the given {@link ConflictDefinition}. */ delete(options?: RequestOptions): Promise<ConflictResponse>; } export declare interface ConflictDefinition { /** The id of the conflict */ id?: string; /** Source resource id */ resourceId?: string; resourceType?: ResourceType; operationType?: OperationType; content?: string; } export declare enum ConflictResolutionMode { Custom = "Custom", LastWriterWins = "LastWriterWins" } /** * Represents the conflict resolution policy configuration for specifying how to resolve conflicts * in case writes from different regions result in conflicts on documents in the collection in the Azure Cosmos DB service. */ export declare interface ConflictResolutionPolicy { /** * Gets or sets the <see cref="ConflictResolutionMode"/> in the Azure Cosmos DB service. By default it is {@link ConflictResolutionMode.LastWriterWins}. */ mode?: keyof typeof ConflictResolutionMode; /** * Gets or sets the path which is present in each document in the Azure Cosmos DB service for last writer wins conflict-resolution. * This path must be present in each document and must be an integer value. * In case of a conflict occurring on a document, the document with the higher integer value in the specified path will be picked. * If the path is unspecified, by default the timestamp path will be used. * * This value should only be set when using {@link ConflictResolutionMode.LastWriterWins}. * * ```typescript * conflictResolutionPolicy.ConflictResolutionPath = "/name/first"; * ``` * */ conflictResolutionPath?: string; /** * Gets or sets the {@link StoredProcedure} which is used for conflict resolution in the Azure Cosmos DB service. * This stored procedure may be created after the {@link Container} is created and can be changed as required. * * 1. This value should only be set when using {@link ConflictResolutionMode.Custom}. * 2. In case the stored procedure fails or throws an exception, the conflict resolution will default to registering conflicts in the conflicts feed. * * ```typescript * conflictResolutionPolicy.ConflictResolutionProcedure = "resolveConflict" * ``` */ conflictResolutionProcedure?: string; } export declare class ConflictResponse extends ResourceResponse<ConflictDefinition & Resource> { constructor(resource: ConflictDefinition & Resource, headers: CosmosHeaders, statusCode: number, conflict: Conflict); /** A reference to the {@link Conflict} corresponding to the returned {@link ConflictDefinition}. */ readonly conflict: Conflict; } /** * Use to query or read all conflicts. * * @see {@link Conflict} to read or delete a given {@link Conflict} by id. */ export declare class Conflicts { readonly container: Container; private readonly clientContext; constructor(container: Container, clientContext: ClientContext); /** * Queries all conflicts. * @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query. * @param options - Use to set options like response page size, continuation tokens, etc. * @returns {@link QueryIterator} Allows you to return results in an array or iterate over them one at a time. */ query(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; /** * Queries all conflicts. * @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query. * @param options - Use to set options like response page size, continuation tokens, etc. * @returns {@link QueryIterator} Allows you to return results in an array or iterate over them one at a time. */ query<T>(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<T>; /** * Reads all conflicts * @param options - Use to set options like response page size, continuation tokens, etc. */ readAll(options?: FeedOptions): QueryIterator<ConflictDefinition & Resource>; } /** Determines the connection behavior of the CosmosClient. Note, we currently only support Gateway Mode. */ export declare enum ConnectionMode { /** Gateway mode talks to an intermediate gateway which handles the direct communication with your individual partitions. */ Gateway = 0 } /** * Represents the Connection policy associated with a CosmosClient in the Azure Cosmos DB database service. */ export declare interface ConnectionPolicy { /** Determines which mode to connect to Cosmos with. (Currently only supports Gateway option) */ connectionMode?: ConnectionMode; /** Request timeout (time to wait for response from network peer). Represented in milliseconds. */ requestTimeout?: number; /** * Flag to enable/disable automatic redirecting of requests based on read/write operations. Default true. * Required to call client.dispose() when this is set to true after destroying the CosmosClient inside another process or in the browser. */ enableEndpointDiscovery?: boolean; /** List of azure regions to be used as preferred locations for read requests. */ preferredLocations?: string[]; /** RetryOptions object which defines several configurable properties used during retry. */ retryOptions?: RetryOptions; /** * The flag that enables writes on any locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. * Default is `false`. */ useMultipleWriteLocations?: boolean; /** Rate in milliseconds at which the client will refresh the endpoints list in the background */ endpointRefreshRateInMs?: number; /** Flag to enable/disable background refreshing of endpoints. Defaults to false. * Endpoint discovery using `enableEndpointsDiscovery` will still work for failed requests. */ enableBackgroundEndpointRefreshing?: boolean; } /** * Represents the consistency levels supported for Azure Cosmos DB client operations.<br> * The requested ConsistencyLevel must match or be weaker than that provisioned for the database account. * Consistency levels. * * Consistency levels by order of strength are Strong, BoundedStaleness, Session, Consistent Prefix, and Eventual. * * See https://aka.ms/cosmos-consistency for more detailed documentation on Consistency Levels. */ export declare enum ConsistencyLevel { /** * Strong Consistency guarantees that read operations always return the value that was last written. */ Strong = "Strong", /** * Bounded Staleness guarantees that reads are not too out-of-date. * This can be configured based on number of operations (MaxStalenessPrefix) or time (MaxStalenessIntervalInSeconds). */ BoundedStaleness = "BoundedStaleness", /** * Session Consistency guarantees monotonic reads (you never read old data, then new, then old again), * monotonic writes (writes are ordered) and read your writes (your writes are immediately visible to your reads) * within any single session. */ Session = "Session", /** * Eventual Consistency guarantees that reads will return a subset of writes. * All writes will be eventually be available for reads. */ Eventual = "Eventual", /** * ConsistentPrefix Consistency guarantees that reads will return some prefix of all writes with no gaps. * All writes will be eventually be available for reads. */ ConsistentPrefix = "ConsistentPrefix" } /** * @hidden */ export declare const Constants: { HttpHeaders: { Authorization: string; ETag: string; MethodOverride: string; Slug: string; ContentType: string; LastModified: string; ContentEncoding: string; CharacterSet: string; UserAgent: string; IfModifiedSince: string; IfMatch: string; IfNoneMatch: string; ContentLength: string; AcceptEncoding: string; KeepAlive: string; CacheControl: string; TransferEncoding: string; ContentLanguage: string; ContentLocation: string; ContentMd5: string; ContentRange: string; Accept: string; AcceptCharset: string; AcceptLanguage: string; IfRange: string; IfUnmodifiedSince: string; MaxForwards: string; ProxyAuthorization: string; AcceptRanges: string; ProxyAuthenticate: string; RetryAfter: string; SetCookie: string; WwwAuthenticate: string; Origin: string; Host: string; AccessControlAllowOrigin: string; AccessControlAllowHeaders: string; KeyValueEncodingFormat: string; WrapAssertionFormat: string; WrapAssertion: string; WrapScope: string; SimpleToken: string; HttpDate: string; Prefer: string; Location: string; Referer: string; A_IM: string; Query: string; IsQuery: string; IsQueryPlan: string; SupportedQueryFeatures: string; QueryVersion: string; Continuation: string; PageSize: string; ItemCount: string; ActivityId: string; PreTriggerInclude: string; PreTriggerExclude: string; PostTriggerInclude: string; PostTriggerExclude: string; IndexingDirective: string; SessionToken: string; ConsistencyLevel: string; XDate: string; CollectionPartitionInfo: string; CollectionServiceInfo: string; RetryAfterInMilliseconds: string; RetryAfterInMs: string; IsFeedUnfiltered: string; ResourceTokenExpiry: string; EnableScanInQuery: string; EmitVerboseTracesInQuery: string; EnableCrossPartitionQuery: string; ParallelizeCrossPartitionQuery: string; ResponseContinuationTokenLimitInKB: string; PopulateQueryMetrics: string; QueryMetrics: string; Version: string; OwnerFullName: string; OwnerId: string; PartitionKey: string; PartitionKeyRangeID: string; MaxEntityCount: string; CurrentEntityCount: string; CollectionQuotaInMb: string; CollectionCurrentUsageInMb: string; MaxMediaStorageUsageInMB: string; CurrentMediaStorageUsageInMB: string; RequestCharge: string; PopulateQuotaInfo: string; MaxResourceQuota: string; OfferType: string; OfferThroughput: string; AutoscaleSettings: string; DisableRUPerMinuteUsage: string; IsRUPerMinuteUsed: string; OfferIsRUPerMinuteThroughputEnabled: string; IndexTransformationProgress: string; LazyIndexingProgress: string; IsUpsert: string; SubStatus: string; EnableScriptLogging: string; ScriptLogResults: string; ALLOW_MULTIPLE_WRITES: string; IsBatchRequest: string; IsBatchAtomic: string; BatchContinueOnError: string; DedicatedGatewayPerRequestCacheStaleness: string; ForceRefresh: string; }; WritableLocations: string; ReadableLocations: string; ENABLE_MULTIPLE_WRITABLE_LOCATIONS: string; DefaultUnavailableLocationExpirationTimeMS: number; ThrottleRetryCount: string; ThrottleRetryWaitTimeInMs: string; CurrentVersion: string; AzureNamespace: string; AzurePackageName: string; SDKName: string; SDKVersion: string; Quota: { CollectionSize: string; }; Path: { Root: string; DatabasesPathSegment: string; CollectionsPathSegment: string; UsersPathSegment: string; DocumentsPathSegment: string; PermissionsPathSegment: string; StoredProceduresPathSegment: string; TriggersPathSegment: string; UserDefinedFunctionsPathSegment: string; ConflictsPathSegment: string; AttachmentsPathSegment: string; PartitionKeyRangesPathSegment: string; SchemasPathSegment: string; OffersPathSegment: string; TopologyPathSegment: string; DatabaseAccountPathSegment: string; }; PartitionKeyRange: PartitionKeyRangePropertiesNames; QueryRangeConstants: { MinInclusive: string; MaxExclusive: string; min: string; }; /** * @deprecated Use EffectivePartitionKeyConstants instead */ EffectiveParitionKeyConstants: { MinimumInclusiveEffectivePartitionKey: string; MaximumExclusiveEffectivePartitionKey: string; }; EffectivePartitionKeyConstants: { MinimumInclusiveEffectivePartitionKey: string; MaximumExclusiveEffectivePartitionKey: string; }; }; /** * Operations for reading, replacing, or deleting a specific, existing container by id. * * @see {@link Containers} for creating new containers, and reading/querying all containers; use `.containers`. * * Note: all these operations make calls against a fixed budget. * You should design your system such that these calls scale sublinearly with your application. * For instance, do not call `container(id).read()` before every single `item.read()` call, to ensure the container exists; * do this once on application start up. */ export declare class Container { readonly database: Database; readonly id: string; private readonly clientContext; private $items; /** * Operations for creating new items, and reading/querying all items * * For reading, replacing, or deleting an existing item, use `.item(id)`. * * @example Create a new item * ```typescript * const {body: createdItem} = await container.items.create({id: "<item id>", properties: {}}); * ``` */ get items(): Items; private $scripts; /** * All operations for Stored Procedures, Triggers, and User Defined Functions */ get scripts(): Scripts; private $conflicts; /** * Operations for reading and querying conflicts for the given container. * * For reading or deleting a specific conflict, use `.conflict(id)`. */ get conflicts(): Conflicts; /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url(): string; /** * Returns a container instance. Note: You should get this from `database.container(id)`, rather than creating your own object. * @param database - The parent {@link Database}. * @param id - The id of the given container. * @hidden */ constructor(database: Database, id: string, clientContext: ClientContext); /** * Used to read, replace, or delete a specific, existing {@link Item} by id. * * Use `.items` for creating new items, or querying/reading all items. * * @param id - The id of the {@link Item}. * @param partitionKeyValue - The value of the {@link Item} partition key * @example Replace an item * `const {body: replacedItem} = await container.item("<item id>", "<partition key value>").replace({id: "<item id>", title: "Updated post", authorID: 5});` */ item(id: string, partitionKeyValue?: PartitionKey): Item; /** * Used to read, replace, or delete a specific, existing {@link Conflict} by id. * * Use `.conflicts` for creating new conflicts, or querying/reading all conflicts. * @param id - The id of the {@link Conflict}. */ conflict(id: string, partitionKey?: PartitionKey): Conflict; /** Read the container's definition */ read(options?: RequestOptions): Promise<ContainerResponse>; /** Replace the container's definition */ replace(body: ContainerDefinition, options?: RequestOptions): Promise<ContainerResponse>; /** Delete the container */ delete(options?: RequestOptions): Promise<ContainerResponse>; /** * Gets the partition key definition first by looking into the cache otherwise by reading the collection. * @deprecated This method has been renamed to readPartitionKeyDefinition. */ getPartitionKeyDefinition(): Promise<ResourceResponse<PartitionKeyDefinition>>; /** * Gets the partition key definition first by looking into the cache otherwise by reading the collection. * @hidden */ readPartitionKeyDefinition(): Promise<ResourceResponse<PartitionKeyDefinition>>; /** * Gets offer on container. If none exists, returns an OfferResponse with undefined. */ readOffer(options?: RequestOptions): Promise<OfferResponse>; getQueryPlan(query: string | SqlQuerySpec): Promise<Response_2<PartitionedQueryExecutionInfo>>; readPartitionKeyRanges(feedOptions?: FeedOptions): QueryIterator<PartitionKeyRange>; } export declare interface ContainerDefinition { /** The id of the container. */ id?: string; /** The partition key for the container. */ partitionKey?: PartitionKeyDefinition; /** The indexing policy associated with the container. */ indexingPolicy?: IndexingPolicy; /** The default time to live in seconds for items in a container. */ defaultTtl?: number; /** The conflict resolution policy used to resolve conflicts in a container. */ conflictResolutionPolicy?: ConflictResolutionPolicy; /** Policy for additional keys that must be unique per partition key */ uniqueKeyPolicy?: UniqueKeyPolicy; /** Geospatial configuration for a collection. Type is set to Geography by default */ geospatialConfig?: { type: GeospatialType; }; } export declare interface ContainerRequest extends VerboseOmit<ContainerDefinition, "partitionKey"> { throughput?: number; maxThroughput?: number; autoUpgradePolicy?: { throughputPolicy: { incrementPercent: number; }; }; partitionKey?: string | PartitionKeyDefinition; } /** Response object for Container operations */ export declare class ContainerResponse extends ResourceResponse<ContainerDefinition & Resource> { constructor(resource: ContainerDefinition & Resource, headers: CosmosHeaders, statusCode: number, container: Container); /** A reference to the {@link Container} that the returned {@link ContainerDefinition} corresponds to. */ readonly container: Container; } /** * Operations for creating new containers, and reading/querying all containers * * @see {@link Container} for reading, replacing, or deleting an existing container; use `.container(id)`. * * Note: all these operations make calls against a fixed budget. * You should design your system such that these calls scale sublinearly with your application. * For instance, do not call `containers.readAll()` before every single `item.read()` call, to ensure the container exists; * do this once on application start up. */ export declare class Containers { readonly database: Database; private readonly clientContext; constructor(database: Database, clientContext: ClientContext); /** * Queries all containers. * @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query. * @param options - Use to set options like response page size, continuation tokens, etc. * @returns {@link QueryIterator} Allows you to return specific containers in an array or iterate over them one at a time. * @example Read all containers to array. * ```typescript * const querySpec: SqlQuerySpec = { * query: "SELECT * FROM root r WHERE r.id = @container", * parameters: [ * {name: "@container", value: "Todo"} * ] * }; * const {body: containerList} = await client.database("<db id>").containers.query(querySpec).fetchAll(); * ``` */ query(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; /** * Queries all containers. * @param query - Query configuration for the operation. See {@link SqlQuerySpec} for more info on how to configure a query. * @param options - Use to set options like response page size, continuation tokens, etc. * @returns {@link QueryIterator} Allows you to return specific containers in an array or iterate over them one at a time. * @example Read all containers to array. * ```typescript * const querySpec: SqlQuerySpec = { * query: "SELECT * FROM root r WHERE r.id = @container", * parameters: [ * {name: "@container", value: "Todo"} * ] * }; * const {body: containerList} = await client.database("<db id>").containers.query(querySpec).fetchAll(); * ``` */ query<T>(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<T>; /** * Creates a container. * * A container is a named logical container for items. * * A database may contain zero or more named containers and each container consists of * zero or more JSON items. * * Being schema-free, the items in a container do not need to share the same structure or fields. * * * Since containers are application resources, they can be authorized using either the * master key or resource keys. * * @param body - Represents the body of the container. * @param options - Use to set options like response page size, continuation tokens, etc. */ create(body: ContainerRequest, options?: RequestOptions): Promise<ContainerResponse>; /** * Checks if a Container exists, and, if it doesn't, creates it. * This will make a read operation based on the id in the `body`, then if it is not found, a create operation. * You should confirm that the output matches the body you passed in for non-default properties (i.e. indexing policy/etc.) * * A container is a named logical container for items. * * A database may contain zero or more named containers and each container consists of * zero or more JSON items. * * Being schema-free, the items in a container do not need to share the same structure or fields. * * * Since containers are application resources, they can be authorized using either the * master key or resource keys. * * @param body - Represents the body of the container. * @param options - Use to set options like response page size, continuation tokens, etc. */ createIfNotExists(body: ContainerRequest, options?: RequestOptions): Promise<ContainerResponse>; /** * Read all containers. * @param options - Use to set options like response page size, continuation tokens, etc. * @returns {@link QueryIterator} Allows you to return all containers in an array or iterate over them one at a time. * @example Read all containers to array. * ```typescript * const {body: containerList} = await client.database("<db id>").containers.readAll().fetchAll(); * ``` */ readAll(options?: FeedOptions): QueryIterator<ContainerDefinition & Resource>; } /** * Provides a client-side logical representation of the Azure Cosmos DB database account. * This client is used to configure and execute requests in the Azure Cosmos DB database service. * @example Instantiate a client and create a new database * ```typescript * const client = new CosmosClient({endpoint: "<URL HERE>", auth: {masterKey: "<KEY HERE>"}}); * await client.databases.create({id: "<datbase name here>"}); * ``` * @example Instantiate a client with custom Connection Policy * ```typescript * const connectionPolicy = new ConnectionPolicy(); * connectionPolicy.RequestTimeout = 10000; * const client = new CosmosClient({ * endpoint: "<URL HERE>", * auth: {masterKey: "<KEY HERE>"}, * connectionPolicy * }); * ``` */ export declare class CosmosClient { /** * Used for creating new databases, or querying/reading all databases. * * Use `.database(id)` to read, replace, or delete a specific, existing database by id. * * @example Create a new database * ```typescript * const {resource: databaseDefinition, database} = await client.databases.create({id: "<name here>"}); * ``` */ readonly databases: Databases; /** * Used for querying & reading all offers. * * Use `.offer(id)` to read, or replace existing offers. */ readonly offers: Offers; private clientContext; private endpointRefresher; /** * Creates a new {@link CosmosClient} object from a connection string. Your database connection string can be found in the Azure Portal */ constructor(connectionString: string); /** * Creates a new {@link CosmosClient} object. See {@link CosmosClientOptions} for more details on what options you can use. * @param options - bag of options; require at least endpoint and auth to be configured */ constructor(options: CosmosClientOptions); /** * Get information about the current {@link DatabaseAccount} (including which regions are supported, etc.) */ getDatabaseAccount(options?: RequestOptions): Promise<ResourceResponse<DatabaseAccount>>; /** * Gets the currently used write endpoint url. Useful for troubleshooting purposes. * * The url may contain a region suffix (e.g. "-eastus") if we're using location specific endpoints. */ getWriteEndpoint(): Promise<string>; /** * Gets the currently used read endpoint. Useful for troubleshooting purposes. * * The url may contain a region suffix (e.g. "-eastus") if we're using location specific endpoints. */ getReadEndpoint(): Promise<string>; /** * Gets the known write endpoints. Useful for troubleshooting purposes. * * The urls may contain a region suffix (e.g. "-eastus") if we're using location specific endpoints. */ getWriteEndpoints(): Promise<readonly string[]>; /** * Gets the currently used read endpoint. Useful for troubleshooting purposes. * * The url may contain a region suffix (e.g. "-eastus") if we're using location specific endpoints. */ getReadEndpoints(): Promise<readonly string[]>; /** * Used for reading, updating, or deleting a existing database by id or accessing containers belonging to that database. * * This does not make a network call. Use `.read` to get info about the database after getting the {@link Database} object. * * @param id - The id of the database. * @example Create a new container off of an existing database * ```typescript * const container = client.database("<database id>").containers.create("<container id>"); * ``` * * @example Delete an existing database * ```typescript * await client.database("<id here>").delete(); * ``` */ database(id: string): Database; /** * Used for reading, or updating a existing offer by id. * @param id - The id of the offer. */ offer(id: string): Offer; /** * Clears background endpoint refresher. Use client.dispose() when destroying the CosmosClient within another process. */ dispose(): void; private backgroundRefreshEndpointList; } export declare interface CosmosClientOptions { /** The service endpoint to use to create the client. */ endpoint: string; /** The account master or readonly key */ key?: string; /** An object that contains resources tokens. * Keys for the object are resource Ids and values are the resource tokens. */ resourceTokens?: { [resourcePath: string]: string; }; /** A user supplied function for resolving header authorization tokens. * Allows users to generating their own auth tokens, potentially using a separate service */ tokenProvider?: TokenProvider; /** AAD token from `@azure/identity` * Obtain a credential object by creating an `@azure/identity` credential object * We will then use your credential object and a scope URL (your cosmos db endpoint) * to authenticate requests to Cosmos */ aadCredentials?: TokenCredential; /** An array of {@link Permission} objects. */ permissionFeed?: PermissionDefinition[]; /** An instance of {@link ConnectionPolicy} class. * This parameter is optional and the default connectionPolicy will be used if omitted. */ connectionPolicy?: ConnectionPolicy; /** An optional parameter that represents the consistency level. * It can take any value from {@link ConsistencyLevel}. */ consistencyLevel?: keyof typeof ConsistencyLevel; defaultHeaders?: CosmosHeaders_2; /** An optional custom http(s) Agent to be used in NodeJS enironments * Use an agent such as https://github.com/TooTallNate/node-proxy-agent if you need to connect to Cosmos via a proxy */ agent?: Agent; /** A custom string to append to the default SDK user agent. */ userAgentSuffix?: string; } /** * @hidden */ declare enum CosmosContainerChildResourceKind { Item = "ITEM", StoredProcedure = "STORED_PROCEDURE", UserDefinedFunction = "USER_DEFINED_FUNCTION", Trigger = "TRIGGER" } export declare interface CosmosHeaders { [key: string]: any; } declare interface CosmosHeaders_2 { [key: string]: string | boolean | number; } /** * @hidden */ declare enum CosmosKeyType { PrimaryMaster = "PRIMARY_MASTER", SecondaryMaster = "SECONDARY_MASTER", PrimaryReadOnly = "PRIMARY_READONLY", SecondaryReadOnly = "SECONDARY_READONLY" } /** * Experimental internal only * Generates the payload representing the permission configuration for the sas token. */ export declare function createAuthorizationSasToken(masterKey: string, sasTokenProperties: SasTokenProperties): Promise<string>; export declare type CreateOperation = OperationWithItem & { operationType: typeof BulkOperationType.Create; }; export declare interface CreateOperationInput { partitionKey?: string | number | null | Record<string, unknown> | undefined; ifMatch?: string; ifNoneMatch?: string; operationType: typeof BulkOperationType.Create; resourceBody: JSONObject; } /** * Operations for reading or deleting an existing database. * * @see {@link Databases} for creating new databases, and reading/querying all databases; use `client.databases`. * * Note: all these operations make calls against a fixed budget. * You should design your system such that these calls scale sublinearly with your application. * For instance, do not call `database.read()` before every single `item.read()` call, to ensure the database exists; * do this once on application start up. */ export declare class Database { readonly client: CosmosClient; readonly id: string; private clientContext; /** * Used for creating new containers, or querying/reading all containers. * * Use `.database(id)` to read, replace, or delete a specific, existing {@link Database} by id. * * @example Create a new container * ```typescript * const {body: containerDefinition, container} = await client.database("<db id>").containers.create({id: "<container id>"}); * ``` */ readonly containers: Containers; /** * Used for creating new users, or querying/reading all users. * * Use `.user(id)` to read, replace, or delete a specific, existing {@link User} by id. */ readonly users: Users; /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url(): string; /** Returns a new {@link Database} instance. * * Note: the intention is to get this object from {@link CosmosClient} via `client.database(id)`, not to instantiate it yourself. */ constructor(client: CosmosClient, id: string, clientContext: ClientContext); /** * Used to read, replace, or delete a specific, existing {@link Database} by id. * * Use `.containers` creating new containers, or querying/reading all containers. * * @example Delete a container * ```typescript * await client.database("<db id>").container("<container id>").delete(); * ``` */ container(id: string): Container; /** * Used to read, replace, or delete a specific, existing {@link User} by id. * * Use `.users` for creating new users, or querying/reading all users. */ user(id: string): User; /** Read the definition of the given Database. */ read(options?: RequestOptions): Promise<DatabaseRespons