@azure/cosmos
- Version 4.2.0
- Published
- 4.14 MB
- 10 dependencies
- MIT license
Install
npm i @azure/cosmos
yarn add @azure/cosmos
pnpm add @azure/cosmos
Overview
Microsoft Azure Cosmos DB Service Node.js SDK for NOSQL API
Index
Variables
Functions
Classes
ClientContext
- batch()
- bulk()
- clearSessionToken()
- create()
- delete()
- diagnosticLevel
- execute()
- getClientConfig()
- getDatabaseAccount()
- getQueryPlan()
- getReadEndpoint()
- getReadEndpoints()
- getWriteEndpoint()
- getWriteEndpoints()
- initializeDiagnosticSettings()
- partitionKeyDefinitionCache
- patch()
- queryFeed()
- queryPartitionKeyRanges()
- read()
- recordDiagnostics()
- replace()
- upsert()
QueryMetrics
- add()
- clientSideMetrics
- createFromArray()
- createFromDelimitedString()
- documentLoadTime
- documentWriteTime
- indexHitDocumentCount
- indexHitRatio
- indexLookupTime
- outputDocumentCount
- outputDocumentSize
- queryPreparationTimes
- retrievedDocumentCount
- retrievedDocumentSize
- runtimeExecutionTimes
- toDelimitedString()
- totalQueryExecutionTime
- vmExecutionTime
- zero
TimeSpan
- add()
- additionDoesOverflow()
- compare()
- compareTo()
- days()
- duration()
- equals()
- fromDays()
- fromHours()
- fromMilliseconds()
- fromMinutes()
- fromSeconds()
- fromTicks()
- hours()
- interval()
- isTimeSpan()
- maxValue
- milliseconds()
- minValue
- negate()
- seconds()
- subtract()
- subtractionDoesUnderflow()
- ticks()
- totalDays()
- totalHours()
- totalMilliseconds()
- totalMinutes()
- totalSeconds()
- zero
Interfaces
FeedOptions
- accessCondition
- allowUnboundedNonStreamingQueries
- bufferItems
- continuation
- continuationToken
- continuationTokenLimitInKB
- disableNonStreamingOrderByQuery
- enableScanInQuery
- forceQueryPlan
- maxDegreeOfParallelism
- maxItemCount
- partitionKey
- populateIndexMetrics
- populateQueryMetrics
- useIncrementalFeed
- vectorSearchBufferSize
Enums
SasTokenPermissionKind
- ContainerCreateItems
- ContainerCreateStoreProcedure
- ContainerCreateTriggers
- ContainerCreateUserDefinedFunctions
- ContainerDeleteConflicts
- ContainerDeleteItems
- ContainerDeleteStoreProcedure
- ContainerDeleteTriggers
- ContainerDeleteUserDefinedFunctions
- ContainerExecuteQueries
- ContainerExecuteStoredProcedure
- ContainerFullAccess
- ContainerReadAny
- ContainerReadConflicts
- ContainerReadFeeds
- ContainerReadStoreProcedure
- ContainerReadTriggers
- ContainerReadUserDefinedFunctions
- ContainerReplaceItems
- ContainerReplaceStoreProcedure
- ContainerReplaceTriggers
- ContainerReplaceUserDefinedFunctions
- ContainerUpsertItems
- ItemDelete
- ItemFullAccess
- ItemRead
- ItemReadAny
- ItemReplace
- ItemUpsert
- StoreProcedureDelete
- StoreProcedureExecute
- StoreProcedureRead
- StoreProcedureReplace
- TriggerDelete
- TriggerRead
- TriggerReplace
- UserDefinedFuntionDelete
- UserDefinedFuntionRead
- UserDefinedFuntionReplace
Type Aliases
- AggregateType
- BulkOperationResponse
- BulkPatchOperation
- ClientConfigDiagnostic
- ClientSideRequestStatistics
- CreateOperation
- DeleteOperation
- DiagnosticDataValue
- ExistingKeyOperation
- GatewayStatistics
- GroupByExpressions
- JSONValue
- MetadataLookUpDiagnostics
- Next
- NonePartitionKeyType
- NullPartitionKeyType
- Operation
- OperationInput
- OperationWithItem
- PartitionKey
- PatchOperation
- PatchRequestBody
- Plugin
- PrimitivePartitionKeyValue
- ReadOperation
- RemoveOperation
- ReplaceOperation
- RetryDiagnostics
- StatusCode
- SubStatusCode
- TokenProvider
- UpsertOperation
Variables
variable BulkOperationType
const BulkOperationType: { readonly Create: 'Create'; readonly Upsert: 'Upsert'; readonly Read: 'Read'; readonly Delete: 'Delete'; readonly Replace: 'Replace'; readonly Patch: 'Patch';};
variable Constants
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; ContinuationToken: string; PageSize: string; ItemCount: string; ChangeFeedWireFormatVersion: string; ActivityId: string; CorrelatedActivityId: 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; PopulateIndexMetrics: string; IndexUtilization: string; Version: string; OwnerFullName: string; OwnerId: string; PartitionKey: string; PartitionKeyRangeID: string; StartEpk: string; EndEpk: string; ReadFeedKeyType: 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; DedicatedGatewayPerRequestBypassCache: string; ForceRefresh: string; PriorityLevel: string; }; WritableLocations: string; ReadableLocations: string; LocationUnavailableExpirationTimeInMs: number; ENABLE_MULTIPLE_WRITABLE_LOCATIONS: string; DefaultUnavailableLocationExpirationTimeMS: number; ThrottleRetryCount: string; ThrottleRetryWaitTimeInMs: string; CurrentVersion: string; AzureNamespace: string; AzurePackageName: string; SDKName: string; SDKVersion: string; CosmosDbDiagnosticLevelEnvVarName: string; DefaultMaxBulkRequestBodySizeInBytes: number; 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 }; EffectiveParitionKeyConstants: { MinimumInclusiveEffectivePartitionKey: string; MaximumExclusiveEffectivePartitionKey: string; }; EffectivePartitionKeyConstants: { MinimumInclusiveEffectivePartitionKey: string; MaximumExclusiveEffectivePartitionKey: string; }; AllVersionsAndDeletesChangeFeedWireFormatVersion: string; ChangeFeedIfNoneMatchStartFromNowHeader: string;};
variable DEFAULT_PARTITION_KEY_PATH
const DEFAULT_PARTITION_KEY_PATH: string;
variable PatchOperationType
const PatchOperationType: { readonly add: 'add'; readonly replace: 'replace'; readonly remove: 'remove'; readonly set: 'set'; readonly incr: 'incr';};
variable QueryMetricsConstants
const QueryMetricsConstants: { RetrievedDocumentCount: string; RetrievedDocumentSize: string; OutputDocumentCount: string; OutputDocumentSize: string; IndexHitRatio: string; IndexHitDocumentCount: string; TotalQueryExecutionTimeInMs: string; QueryCompileTimeInMs: string; LogicalPlanBuildTimeInMs: string; PhysicalPlanBuildTimeInMs: string; QueryOptimizationTimeInMs: string; IndexLookupTimeInMs: string; DocumentLoadTimeInMs: string; VMExecutionTimeInMs: string; DocumentWriteTimeInMs: string; QueryEngineTimes: string; SystemFunctionExecuteTimeInMs: string; UserDefinedFunctionExecutionTimeInMs: string; RetrievedDocumentCountText: string; RetrievedDocumentSizeText: string; OutputDocumentCountText: string; OutputDocumentSizeText: string; IndexUtilizationText: string; TotalQueryExecutionTimeText: string; QueryPreparationTimesText: string; QueryCompileTimeText: string; LogicalPlanBuildTimeText: string; PhysicalPlanBuildTimeText: string; QueryOptimizationTimeText: string; QueryEngineTimesText: string; IndexLookupTimeText: string; DocumentLoadTimeText: string; WriteOutputTimeText: string; RuntimeExecutionTimesText: string; TotalExecutionTimeText: string; SystemFunctionExecuteTimeText: string; UserDefinedFunctionExecutionTimeText: string; ClientSideQueryMetricsText: string; RetriesText: string; RequestChargeText: string; FetchExecutionRangesText: string; SchedulingMetricsText: string;};
variable StatusCodes
const StatusCodes: StatusCodesType;
Functions
function createAuthorizationSasToken
createAuthorizationSasToken: ( masterKey: string, sasTokenProperties: SasTokenProperties) => Promise<string>;
Experimental internal only Generates the payload representing the permission configuration for the sas token.
function setAuthorizationTokenHeaderUsingMasterKey
setAuthorizationTokenHeaderUsingMasterKey: ( verb: HTTPMethod, resourceId: string, resourceType: ResourceType, headers: CosmosHeaders, masterKey: string) => Promise<void>;
The default function for setting header token using the masterKey
Classes
class ChangeFeedIterator
class ChangeFeedIterator<T> {}
Provides iterator for change feed.
Use
Items.changeFeed()
to get an instance of the iterator.
property hasMoreResults
readonly hasMoreResults: boolean;
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.
method fetchNext
fetchNext: () => Promise<ChangeFeedResponse<Array<T & Resource>>>;
Read feed and retrieves the next page of results in Azure Cosmos DB.
method getAsyncIterator
getAsyncIterator: () => AsyncIterable<ChangeFeedResponse<Array<T & Resource>>>;
Gets an async iterator which will yield pages of results from Azure Cosmos DB.
class ChangeFeedIteratorResponse
class ChangeFeedIteratorResponse<T> {}
A single response page from the Azure Cosmos DB Change Feed
property activityId
readonly activityId: string;
Gets the activity ID for the request from the Azure Cosmos DB service.
property continuationToken
readonly continuationToken: string;
Gets the continuation token to be used for continuing enumeration of the Azure Cosmos DB service.
property count
readonly count: number;
Gets the number of items returned in the response from Azure Cosmos DB
property diagnostics
readonly diagnostics: CosmosDiagnostics;
Cosmos Diagnostic Object.
property headers
headers: CosmosHeaders;
Response headers of the response from Azure Cosmos DB
property requestCharge
readonly requestCharge: number;
Gets the request charge for this request from the Azure Cosmos DB service.
property result
readonly result: {};
Gets the items returned in the response from Azure Cosmos DB
property sessionToken
readonly sessionToken: string;
Gets the session token for use in session consistency reads from the Azure Cosmos DB service.
property statusCode
readonly statusCode: number;
Gets the status code of the response from Azure Cosmos DB
property subStatusCode
readonly subStatusCode?: number;
Gets the subStatusCodes of the response from Azure Cosmos DB. Useful in partition split or partition gone.
class ChangeFeedPolicy
class ChangeFeedPolicy {}
Represents the change feed policy configuration for a container in the Azure Cosmos DB service.
constructor
constructor(retentionDuration: ChangeFeedRetentionTimeSpan);
property retentionDuration
retentionDuration: number;
class ChangeFeedResponse
class ChangeFeedResponse<T> {}
A single response page from the Azure Cosmos DB Change Feed
property activityId
readonly activityId: string;
Gets the activity ID for the request from the Azure Cosmos DB service.
property continuation
readonly continuation: string;
Gets the continuation token to be used for continuing enumeration of the Azure Cosmos DB service.
This is equivalent to the
etag
property.
property count
readonly count: number;
Gets the number of items returned in the response from Azure Cosmos DB
property diagnostics
readonly diagnostics: CosmosDiagnostics;
property etag
readonly etag: 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 ofChangeFeedOptions
parameter forItems.changeFeed()
to get feed changes since the transaction specified by this entity tag.This is equivalent to the
continuation
property.
property headers
headers: CosmosHeaders;
Response headers of the response from Azure Cosmos DB
property requestCharge
readonly requestCharge: number;
Gets the request charge for this request from the Azure Cosmos DB service.
property result
readonly result: {};
Gets the items returned in the response from Azure Cosmos DB
property sessionToken
readonly sessionToken: string;
Gets the session token for use in session consistency reads from the Azure Cosmos DB service.
property statusCode
readonly statusCode: number;
Gets the status code of the response from Azure Cosmos DB
class ChangeFeedRetentionTimeSpan
class ChangeFeedRetentionTimeSpan {}
method fromMinutes
static fromMinutes: (minutes: number) => ChangeFeedRetentionTimeSpan;
Specifies the retention window in minutes for which processing the change feed with allVersionsAndDeletes mode will be available.
class ChangeFeedStartFrom
abstract class ChangeFeedStartFrom {}
Base class for where to start a ChangeFeedIterator.
method Beginning
static Beginning: ( cfResource?: PartitionKey | FeedRange) => ChangeFeedStartFromBeginning;
Returns an object that tells the ChangeFeedIterator to start from the beginning of time.
Parameter cfResource
PartitionKey or FeedRange for which changes are to be fetched. Leave blank for fetching changes for entire container.
method Continuation
static Continuation: ( continuationToken: string) => ChangeFeedStartFromContinuation;
Returns an object that tells the ChangeFeedIterator to start reading changes from a save point.
Parameter continuation
The continuation to resume from.
method Now
static Now: (cfResource?: PartitionKey | FeedRange) => ChangeFeedStartFromNow;
Returns an object that tells the ChangeFeedIterator to start reading changes from this moment onward.
Parameter cfResource
PartitionKey or FeedRange for which changes are to be fetched. Leave blank for fetching changes for entire container.
method Time
static Time: ( startTime: Date, cfResource?: PartitionKey | FeedRange) => ChangeFeedStartFromTime;
Returns an object that tells the ChangeFeedIterator to start reading changes from some point in time onward.
Parameter startTime
Date object specfiying the time to start reading changes from.
Parameter cfResource
PartitionKey or FeedRange for which changes are to be fetched. Leave blank for fetching changes for entire container.
class ClientContext
class ClientContext {}
constructor
constructor( cosmosClientOptions: CosmosClientOptions, globalEndpointManager: GlobalEndpointManager, clientConfig: ClientConfigDiagnostic, diagnosticLevel: CosmosDbDiagnosticLevel);
property diagnosticLevel
diagnosticLevel: CosmosDbDiagnosticLevel;
property partitionKeyDefinitionCache
partitionKeyDefinitionCache: { [containerUrl: string]: any };
method batch
batch: <T>({ body, path, partitionKey, resourceId, options, diagnosticNode,}: { body: T; path: string; partitionKey: PartitionKey; resourceId: string; options?: RequestOptions; diagnosticNode: DiagnosticNodeInternal;}) => Promise<Response_2<any>>;
method bulk
bulk: <T>({ body, path, partitionKeyRangeId, resourceId, bulkOptions, options, diagnosticNode,}: { body: T; path: string; partitionKeyRangeId: string; resourceId: string; bulkOptions?: BulkOptions; options?: RequestOptions; diagnosticNode: DiagnosticNodeInternal;}) => Promise<Response_2<any>>;
method clearSessionToken
clearSessionToken: (path: string) => void;
method create
create: <T, U = T>({ body, path, resourceType, resourceId, diagnosticNode, options, partitionKey,}: { body: T; path: string; resourceType: ResourceType; resourceId: string; diagnosticNode: DiagnosticNodeInternal; options?: RequestOptions; partitionKey?: PartitionKey;}) => Promise<Response_2<T & U & Resource>>;
method delete
delete: <T>({ path, resourceType, resourceId, options, partitionKey, method, diagnosticNode,}: { path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; method?: HTTPMethod; diagnosticNode: DiagnosticNodeInternal;}) => Promise<Response_2<T & Resource>>;
method execute
execute: <T>({ sprocLink, params, options, partitionKey, diagnosticNode,}: { sprocLink: string; params?: any[]; options?: RequestOptions; partitionKey?: PartitionKey; diagnosticNode: DiagnosticNodeInternal;}) => Promise<Response_2<T>>;
method getClientConfig
getClientConfig: () => ClientConfigDiagnostic;
method getDatabaseAccount
getDatabaseAccount: ( diagnosticNode: DiagnosticNodeInternal, options?: RequestOptions) => Promise<Response_2<DatabaseAccount>>;
Gets the Database account information.
Parameter 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.
method getQueryPlan
getQueryPlan: ( path: string, resourceType: ResourceType, resourceId: string, query: SqlQuerySpec | string, options: FeedOptions, diagnosticNode: DiagnosticNodeInternal, correlatedActivityId?: string) => Promise<Response_2<PartitionedQueryExecutionInfo>>;
method getReadEndpoint
getReadEndpoint: (diagnosticNode: DiagnosticNodeInternal) => Promise<string>;
method getReadEndpoints
getReadEndpoints: () => Promise<readonly string[]>;
method getWriteEndpoint
getWriteEndpoint: (diagnosticNode: DiagnosticNodeInternal) => Promise<string>;
method getWriteEndpoints
getWriteEndpoints: () => Promise<readonly string[]>;
method initializeDiagnosticSettings
initializeDiagnosticSettings: (diagnosticLevel: CosmosDbDiagnosticLevel) => void;
method patch
patch: <T>({ body, path, resourceType, resourceId, options, partitionKey, diagnosticNode,}: { body: any; path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; diagnosticNode: DiagnosticNodeInternal;}) => Promise<Response_2<T & Resource>>;
method queryFeed
queryFeed: <T>({ path, resourceType, resourceId, resultFn, query, options, diagnosticNode, partitionKeyRangeId, partitionKey, startEpk, endEpk, correlatedActivityId,}: { path: string; resourceType: ResourceType; resourceId: string; resultFn: (result: { [key: string]: any }) => any[]; query: SqlQuerySpec | string; options: FeedOptions; diagnosticNode: DiagnosticNodeInternal; partitionKeyRangeId?: string; partitionKey?: PartitionKey; startEpk?: string | undefined; endEpk?: string | undefined; correlatedActivityId?: string;}) => Promise<Response_2<T & Resource>>;
method queryPartitionKeyRanges
queryPartitionKeyRanges: ( collectionLink: string, query?: string | SqlQuerySpec, options?: FeedOptions) => QueryIterator<PartitionKeyRange>;
method read
read: <T>({ path, resourceType, resourceId, options, partitionKey, diagnosticNode,}: { path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; diagnosticNode: DiagnosticNodeInternal;}) => Promise<Response_2<T & Resource>>;
method recordDiagnostics
recordDiagnostics: (diagnostic: CosmosDiagnostics) => void;
method replace
replace: <T>({ body, path, resourceType, resourceId, options, partitionKey, diagnosticNode,}: { body: any; path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; diagnosticNode: DiagnosticNodeInternal;}) => Promise<Response_2<T & Resource>>;
method upsert
upsert: <T, U = T>({ body, path, resourceType, resourceId, options, partitionKey, diagnosticNode,}: { body: T; path: string; resourceType: ResourceType; resourceId: string; options?: RequestOptions; partitionKey?: PartitionKey; diagnosticNode: DiagnosticNodeInternal;}) => Promise<Response_2<T & U & Resource>>;
class ClientSideMetrics
class ClientSideMetrics {}
constructor
constructor(requestCharge: number);
property requestCharge
readonly requestCharge: number;
property zero
static readonly zero: ClientSideMetrics;
method add
add: (...clientSideMetricsArray: ClientSideMetrics[]) => ClientSideMetrics;
Adds one or more ClientSideMetrics to a copy of this instance and returns the result.
method createFromArray
static createFromArray: ( ...clientSideMetricsArray: ClientSideMetrics[]) => ClientSideMetrics;
class Conflict
class Conflict {}
constructor
constructor( container: Container, id: string, clientContext: ClientContext, partitionKey?: PartitionKey);
property container
readonly container: Container;
property id
readonly id: string;
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
method delete
delete: (options?: RequestOptions) => Promise<ConflictResponse>;
Delete the given ConflictDefinition.
method read
read: (options?: RequestOptions) => Promise<ConflictResponse>;
Read the ConflictDefinition for the given Conflict.
class ConflictResponse
class ConflictResponse extends ResourceResponse<ConflictDefinition & Resource> {}
constructor
constructor( resource: ConflictDefinition & Resource, headers: CosmosHeaders, statusCode: number, conflict: Conflict, diagnostics: CosmosDiagnostics);
property conflict
readonly conflict: Conflict;
A reference to the Conflict corresponding to the returned ConflictDefinition.
class Conflicts
class Conflicts {}
constructor
constructor(container: Container, clientContext: ClientContext);
property container
readonly container: Container;
method query
query: { (query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Queries all conflicts.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Parameter options
Use to set options like response page size, continuation tokens, etc.
Returns
QueryIterator Allows you to return results in an array or iterate over them one at a time.
Queries all conflicts.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Parameter options
Use to set options like response page size, continuation tokens, etc.
Returns
QueryIterator Allows you to return results in an array or iterate over them one at a time.
method readAll
readAll: (options?: FeedOptions) => QueryIterator<ConflictDefinition & Resource>;
Reads all conflicts
Parameter options
Use to set options like response page size, continuation tokens, etc.
class Container
class Container {}
Operations for reading, replacing, or deleting a specific, existing container by id.
See Also
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 singleitem.read()
call, to ensure the container exists; do this once on application start up.
constructor
constructor(database: Database, id: string, clientContext: ClientContext);
Returns a container instance. Note: You should get this from
database.container(id)
, rather than creating your own object.Parameter database
The parent Database.
Parameter id
The id of the given container.
property conflicts
readonly conflicts: Conflicts;
Operations for reading and querying conflicts for the given container.
For reading or deleting a specific conflict, use
.conflict(id)
.
property database
readonly database: Database;
property id
readonly id: string;
property items
readonly items: Items;
Operations for creating new items, and reading/querying all items
For reading, replacing, or deleting an existing item, use
.item(id)
.Example 1
Create a new item
const {body: createdItem} = await container.items.create({id: "<item id>", properties: {}});
property scripts
readonly scripts: Scripts;
All operations for Stored Procedures, Triggers, and User Defined Functions
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
method conflict
conflict: (id: string, partitionKey?: PartitionKey) => Conflict;
method delete
delete: (options?: RequestOptions) => Promise<ContainerResponse>;
Delete the container
method deleteAllItemsForPartitionKey
deleteAllItemsForPartitionKey: ( partitionKey: PartitionKey, options?: RequestOptions) => Promise<ContainerResponse>;
Delete all documents belong to the container for the provided partition key value
Parameter partitionKey
The partition key value of the items to be deleted
method getFeedRanges
getFeedRanges: () => Promise<ReadonlyArray<FeedRange>>;
Returns
all the feed ranges for which changefeed could be fetched.
method getPartitionKeyDefinition
getPartitionKeyDefinition: () => Promise< ResourceResponse<PartitionKeyDefinition>>;
Gets the partition key definition first by looking into the cache otherwise by reading the collection.
Deprecated
This method has been renamed to readPartitionKeyDefinition.
method getQueryPlan
getQueryPlan: ( query: string | SqlQuerySpec) => Promise<Response_2<PartitionedQueryExecutionInfo>>;
method item
item: (id: string, partitionKeyValue?: PartitionKey) => Item;
Used to read, replace, or delete a specific, existing Item by id.
Use
.items
for creating new items, or querying/reading all items.Parameter id
The id of the Item.
Parameter partitionKeyValue
The value of the Item partition key
Example 1
Replace an item
const {body: replacedItem} = await container.item("<item id>", "<partition key value>").replace({id: "<item id>", title: "Updated post", authorID: 5});
method read
read: (options?: RequestOptions) => Promise<ContainerResponse>;
Read the container's definition
method readInternal
readInternal: ( diagnosticNode: DiagnosticNodeInternal, options?: RequestOptions) => Promise<ContainerResponse>;
method readOffer
readOffer: (options?: RequestOptions) => Promise<OfferResponse>;
Gets offer on container. If none exists, returns an OfferResponse with undefined.
method readPartitionKeyDefinition
readPartitionKeyDefinition: ( diagnosticNode: DiagnosticNodeInternal) => Promise<ResourceResponse<PartitionKeyDefinition>>;
Gets the partition key definition first by looking into the cache otherwise by reading the collection.
method readPartitionKeyRanges
readPartitionKeyRanges: ( feedOptions?: FeedOptions) => QueryIterator<PartitionKeyRange>;
method replace
replace: ( body: ContainerDefinition, options?: RequestOptions) => Promise<ContainerResponse>;
Replace the container's definition
class ContainerResponse
class ContainerResponse extends ResourceResponse<ContainerDefinition & Resource> {}
Response object for Container operations
constructor
constructor( resource: ContainerDefinition & Resource, headers: CosmosHeaders, statusCode: number, container: Container, diagnostics: CosmosDiagnostics);
property container
readonly container: Container;
A reference to the Container that the returned ContainerDefinition corresponds to.
class Containers
class Containers {}
Operations for creating new containers, and reading/querying all containers
See Also
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 singleitem.read()
call, to ensure the container exists; do this once on application start up.
constructor
constructor(database: Database, clientContext: ClientContext);
property database
readonly database: Database;
method create
create: ( body: ContainerRequest, options?: RequestOptions) => Promise<ContainerResponse>;
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.
Parameter body
Represents the body of the container.
Parameter options
Use to set options like response page size, continuation tokens, etc.
method createIfNotExists
createIfNotExists: ( 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.
Parameter body
Represents the body of the container.
Parameter options
Use to set options like response page size, continuation tokens, etc.
method createInternal
createInternal: ( diagnosticNode: DiagnosticNodeInternal, body: ContainerRequest, options?: RequestOptions) => Promise<ContainerResponse>;
method query
query: { (query: SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Queries all containers.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Parameter options
Use to set options like response page size, continuation tokens, etc.
Returns
QueryIterator Allows you to return specific containers in an array or iterate over them one at a time.
Example 1
Read all containers to array.
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();Queries all containers.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Parameter options
Use to set options like response page size, continuation tokens, etc.
Returns
QueryIterator Allows you to return specific containers in an array or iterate over them one at a time.
Example 1
Read all containers to array.
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();
method readAll
readAll: ( options?: FeedOptions) => QueryIterator<ContainerDefinition & Resource>;
Read all containers.
Parameter options
Use to set options like response page size, continuation tokens, etc.
Returns
QueryIterator Allows you to return all containers in an array or iterate over them one at a time.
Example 1
Read all containers to array.
const {body: containerList} = await client.database("<db id>").containers.readAll().fetchAll();
class CosmosClient
class CosmosClient {}
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 1
Instantiate a client and create a new database
const client = new CosmosClient({endpoint: "<URL HERE>", key: "<KEY HERE>"});await client.databases.create({id: "<database name here>"});Example 2
Instantiate a client with custom Connection Policy
const client = new CosmosClient({endpoint: "<URL HERE>",key: "<KEY HERE>",connectionPolicy: {requestTimeout: 10000,},});
constructor
constructor(connectionString: string);
Creates a new CosmosClient object from a connection string. Your database connection string can be found in the Azure Portal
constructor
constructor(options: CosmosClientOptions);
Creates a new CosmosClient object. See CosmosClientOptions for more details on what options you can use.
Parameter options
bag of options; require at least endpoint and auth to be configured
property databases
readonly databases: Databases;
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 1
Create a new database
const {resource: databaseDefinition, database} = await client.databases.create({id: "<name here>"});
property offers
readonly offers: Offers;
Used for querying & reading all offers.
Use
.offer(id)
to read, or replace existing offers.
method database
database: (id: string) => Database;
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 Database object.Parameter id
The id of the database.
Example 1
Create a new container off of an existing database
const container = client.database("<database id>").containers.create("<container id>");Example 2
Delete an existing database
await client.database("<id here>").delete();
method dispose
dispose: () => void;
Clears background endpoint refresher. Use client.dispose() when destroying the CosmosClient within another process.
method getDatabaseAccount
getDatabaseAccount: ( options?: RequestOptions) => Promise<ResourceResponse<DatabaseAccount>>;
Get information about the current DatabaseAccount (including which regions are supported, etc.)
method getDatabaseAccountInternal
getDatabaseAccountInternal: ( diagnosticNode: DiagnosticNodeInternal, options?: RequestOptions) => Promise<ResourceResponse<DatabaseAccount>>;
method getReadEndpoint
getReadEndpoint: () => 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.
method getReadEndpoints
getReadEndpoints: () => 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.
method getWriteEndpoint
getWriteEndpoint: () => Promise<string>;
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.
method getWriteEndpoints
getWriteEndpoints: () => Promise<readonly 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.
method offer
offer: (id: string) => Offer;
Used for reading, or updating a existing offer by id.
Parameter id
The id of the offer.
class CosmosDiagnostics
class CosmosDiagnostics {}
* This is a Cosmos Diagnostic type that holds collected diagnostic information during a client operations. ie. Item.read(), Container.create(). It has three members - 1.
clientSideRequestStatistics
member contains aggregate diagnostic information, including - - metadata lookups. Here all the server requests, apart from the final intended resource are considered as metadata calls. i.e. for item.read(id), if the client makes server call to discover endpoints it would be considered as metadata call. - retries - endpoints contacted. - request, response payload stats. - gatewayStatistics - Information corresponding to main operation. For example during Item.read(), the client might perform many operations i.e. metadata lookup etc, but gatewayStatistics represents the diagnostics information for actual read operation.2. diagnosticNode - Is a tree like structure which captures detailed diagnostic information. By default it is disabled, and is intended to be used only for debugging on non production environments. The kind of details captured in diagnosticNode is controlled by
CosmosDbDiagnosticLevel
. - CosmosDbDiagnosticLevel.info - Is default value. In this level only clientSideRequestStatistics are captured. Is is meant for production environments. - CosmosDbDiagnosticLevel.debug - Captures diagnosticNode and clientConfig. No request and response payloads are captured. Is not meant to be used in production environment. - CosmosDbDiagnosticLevel.debug-unsafe - In addition to data captured in CosmosDbDiagnosticLevel.debug, also captures request and response payloads. Is not meant to be used in production environment. 3. clientConfig - Captures information related to how client was configured during initialization.
property clientConfig
readonly clientConfig?: ClientConfigDiagnostic;
property clientSideRequestStatistics
readonly clientSideRequestStatistics: ClientSideRequestStatistics;
property diagnosticNode
readonly diagnosticNode: DiagnosticNode;
class Database
class Database {}
Operations for reading or deleting an existing database.
See Also
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 singleitem.read()
call, to ensure the database exists; do this once on application start up.
constructor
constructor(client: CosmosClient, id: string, clientContext: ClientContext);
Returns a new Database instance.
Note: the intention is to get this object from CosmosClient via
client.database(id)
, not to instantiate it yourself.
property client
readonly client: CosmosClient;
property containers
readonly containers: Containers;
Used for creating new containers, or querying/reading all containers.
Use
.database(id)
to read, replace, or delete a specific, existing Database by id.Example 1
Create a new container
const {body: containerDefinition, container} = await client.database("<db id>").containers.create({id: "<container id>"});
property id
readonly id: string;
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
property users
readonly users: Users;
Used for creating new users, or querying/reading all users.
Use
.user(id)
to read, replace, or delete a specific, existing User by id.
method container
container: (id: string) => Container;
Used to read, replace, or delete a specific, existing Database by id.
Use
.containers
creating new containers, or querying/reading all containers.Example 1
Delete a container
await client.database("<db id>").container("<container id>").delete();
method delete
delete: (options?: RequestOptions) => Promise<DatabaseResponse>;
Delete the given Database.
method read
read: (options?: RequestOptions) => Promise<DatabaseResponse>;
Read the definition of the given Database.
method readInternal
readInternal: ( diagnosticNode: DiagnosticNodeInternal, options?: RequestOptions) => Promise<DatabaseResponse>;
method readOffer
readOffer: (options?: RequestOptions) => Promise<OfferResponse>;
Gets offer on database. If none exists, returns an OfferResponse with undefined.
method user
user: (id: string) => User;
Used to read, replace, or delete a specific, existing User by id.
Use
.users
for creating new users, or querying/reading all users.
class DatabaseAccount
class DatabaseAccount {}
Represents a DatabaseAccount in the Azure Cosmos DB database service.
constructor
constructor(body: { [key: string]: any }, headers: CosmosHeaders);
property consistencyPolicy
readonly consistencyPolicy: ConsistencyLevel;
Gets the UserConsistencyPolicy settings.
property ConsistencyPolicy
readonly ConsistencyPolicy: ConsistencyLevel;
Gets the UserConsistencyPolicy settings.
Deprecated
use
consistencyPolicy
property currentMediaStorageUsageInMB
readonly currentMediaStorageUsageInMB: number;
Current attachment content (media) usage in MBs (Retrieved from gateway )
Value is returned from cached information updated periodically and is not guaranteed to be real time.
property CurrentMediaStorageUsageInMB
readonly CurrentMediaStorageUsageInMB: number;
Current attachment content (media) usage in MBs (Retrieved from gateway )
Value is returned from cached information updated periodically and is not guaranteed to be real time.
Deprecated
use
currentMediaStorageUsageInMB
property databasesLink
readonly databasesLink: string;
The self-link for Databases in the databaseAccount.
property DatabasesLink
readonly DatabasesLink: string;
The self-link for Databases in the databaseAccount.
Deprecated
Use
databasesLink
property enableMultipleWritableLocations
readonly enableMultipleWritableLocations: boolean;
property maxMediaStorageUsageInMB
readonly maxMediaStorageUsageInMB: number;
Attachment content (media) storage quota in MBs ( Retrieved from gateway ).
property MaxMediaStorageUsageInMB
readonly MaxMediaStorageUsageInMB: number;
Attachment content (media) storage quota in MBs ( Retrieved from gateway ).
Deprecated
use
maxMediaStorageUsageInMB
property mediaLink
readonly mediaLink: string;
The self-link for Media in the databaseAccount.
property MediaLink
readonly MediaLink: string;
The self-link for Media in the databaseAccount.
Deprecated
Use
mediaLink
property readableLocations
readonly readableLocations: Location[];
The list of readable locations for a geo-replicated database account.
property writableLocations
readonly writableLocations: Location[];
The list of writable locations for a geo-replicated database account.
class DatabaseResponse
class DatabaseResponse extends ResourceResponse<DatabaseDefinition & Resource> {}
Response object for Database operations
constructor
constructor( resource: DatabaseDefinition & Resource, headers: CosmosHeaders, statusCode: number, database: Database, diagnostics: CosmosDiagnostics);
property database
readonly database: Database;
A reference to the Database that the returned DatabaseDefinition corresponds to.
class Databases
class Databases {}
Operations for creating new databases, and reading/querying all databases
See Also
Database for reading or deleting an existing database; use
client.database(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
databases.readAll()
before every singleitem.read()
call, to ensure the database exists; do this once on application start up.
constructor
constructor(client: CosmosClient, clientContext: ClientContext);
Parameter client
The parent CosmosClient for the Database.
property client
readonly client: CosmosClient;
method create
create: ( body: DatabaseRequest, options?: RequestOptions) => Promise<DatabaseResponse>;
Send a request for creating a database.
A database manages users, permissions and a set of containers. Each Azure Cosmos DB Database Account is able to support multiple independent named databases, with the database being the logical container for data.
Each Database consists of one or more containers, each of which in turn contain one or more documents. Since databases are an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.
Parameter body
The DatabaseDefinition that represents the Database to be created.
Parameter options
Use to set options like response page size, continuation tokens, etc.
method createIfNotExists
createIfNotExists: ( body: DatabaseRequest, options?: RequestOptions) => Promise<DatabaseResponse>;
Check if a database exists, and if it doesn't, create it. This will make a read operation based on the id in the
body
, then if it is not found, a create operation.A database manages users, permissions and a set of containers. Each Azure Cosmos DB Database Account is able to support multiple independent named databases, with the database being the logical container for data.
Each Database consists of one or more containers, each of which in turn contain one or more documents. Since databases are an an administrative resource, the Service Master Key will be required in order to access and successfully complete any action using the User APIs.
Parameter body
The DatabaseDefinition that represents the Database to be created.
Parameter options
Additional options for the request
method createInternal
createInternal: ( diagnosticNode: DiagnosticNodeInternal, body: DatabaseRequest, options?: RequestOptions) => Promise<DatabaseResponse>;
method query
query: { (query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Queries all databases.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Parameter options
Use to set options like response page size, continuation tokens, etc.
Returns
QueryIterator Allows you to return all databases in an array or iterate over them one at a time.
Example 1
Read all databases to array.
const querySpec: SqlQuerySpec = {query: "SELECT * FROM root r WHERE r.id = @db",parameters: [{name: "@db", value: "Todo"}]};const {body: databaseList} = await client.databases.query(querySpec).fetchAll();Queries all databases.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Parameter options
Use to set options like response page size, continuation tokens, etc.
Returns
QueryIterator Allows you to return all databases in an array or iterate over them one at a time.
Example 1
Read all databases to array.
const querySpec: SqlQuerySpec = {query: "SELECT * FROM root r WHERE r.id = @db",parameters: [{name: "@db", value: "Todo"}]};const {body: databaseList} = await client.databases.query(querySpec).fetchAll();
method readAll
readAll: (options?: FeedOptions) => QueryIterator<DatabaseDefinition & Resource>;
Reads all databases.
Parameter options
Use to set options like response page size, continuation tokens, etc.
Returns
QueryIterator Allows you to return all databases in an array or iterate over them one at a time.
Example 1
Read all databases to array.
const {body: databaseList} = await client.databases.readAll().fetchAll();
class DiagnosticNodeInternal
class DiagnosticNodeInternal implements DiagnosticNode {}
This is Internal Representation for DiagnosticNode. It contains useful helper functions to collect diagnostic information throughout the lifetime of Diagnostic session. The functions toDiagnosticNode() & toDiagnostic() are given to convert it to public facing counterpart.
property children
children: DiagnosticNodeInternal[];
property data
data: Partial<DiagnosticDataValue>;
property diagnosticLevel
diagnosticLevel: CosmosDbDiagnosticLevel;
property durationInMs
durationInMs: number;
property id
id: string;
property nodeType
nodeType: DiagnosticNodeType;
property parent
parent: DiagnosticNodeInternal;
property startTimeUTCInMs
startTimeUTCInMs: number;
class ErrorResponse
class ErrorResponse extends Error {}
property activityId
activityId?: string;
property body
body?: ErrorBody;
property code
code?: string | number;
property diagnostics
diagnostics?: CosmosDiagnostics;
property headers
headers?: CosmosHeaders;
property retryAfterInMilliseconds
retryAfterInMilliseconds?: number;
property retryAfterInMs
retryAfterInMs?: number;
property substatus
substatus?: number;
class FeedRange
abstract class FeedRange {}
Specifies a feed range for the changefeed.
property maxExclusive
readonly maxExclusive: string;
Max value for the feed range.
property minInclusive
readonly minInclusive: string;
Min value for the feed range.
class FeedResponse
class FeedResponse<TResource> {}
constructor
constructor( resources: TResource[], headers: CosmosHeaders, hasMoreResults: boolean, diagnostics: CosmosDiagnostics);
property activityId
readonly activityId: string;
property continuation
readonly continuation: string;
property continuationToken
readonly continuationToken: string;
property correlatedActivityId
readonly correlatedActivityId: string;
property diagnostics
readonly diagnostics: CosmosDiagnostics;
property hasMoreResults
readonly hasMoreResults: boolean;
property indexMetrics
readonly indexMetrics: string;
property queryMetrics
readonly queryMetrics: string;
property requestCharge
readonly requestCharge: number;
property resources
readonly resources: TResource[];
class GlobalEndpointManager
class GlobalEndpointManager {}
This internal class implements the logic for endpoint management for geo-replicated database accounts.
property enableEndpointDiscovery
enableEndpointDiscovery: boolean;
Flag to enable/disable automatic redirecting of requests based on read/write operations.
property preferredLocationsCount
preferredLocationsCount: number;
method canUseMultipleWriteLocations
canUseMultipleWriteLocations: ( resourceType?: ResourceType, operationType?: OperationType) => boolean;
method getReadEndpoint
getReadEndpoint: (diagnosticNode: DiagnosticNodeInternal) => Promise<string>;
Gets the current read endpoint from the endpoint cache.
method getReadEndpoints
getReadEndpoints: () => Promise<ReadonlyArray<string>>;
method getWriteEndpoint
getWriteEndpoint: (diagnosticNode: DiagnosticNodeInternal) => Promise<string>;
Gets the current write endpoint from the endpoint cache.
method getWriteEndpoints
getWriteEndpoints: () => Promise<ReadonlyArray<string>>;
method markCurrentLocationUnavailableForRead
markCurrentLocationUnavailableForRead: ( diagnosticNode: DiagnosticNodeInternal, endpoint: string) => Promise<void>;
method markCurrentLocationUnavailableForWrite
markCurrentLocationUnavailableForWrite: ( diagnosticNode: DiagnosticNodeInternal, endpoint: string) => Promise<void>;
method refreshEndpointList
refreshEndpointList: (diagnosticNode: DiagnosticNodeInternal) => Promise<void>;
Refreshes the endpoint list by clearning stale unavailability and then retrieving the writable and readable locations from the geo-replicated database account and then updating the locations cache. We skip the refreshing if enableEndpointDiscovery is set to False
method resolveServiceEndpoint
resolveServiceEndpoint: ( diagnosticNode: DiagnosticNodeInternal, resourceType: ResourceType, operationType: OperationType, startServiceEndpointIndex?: number) => Promise<string>;
class Item
class Item {}
Used to perform operations on a specific item.
See Also
Items for operations on all items; see
container.items
.
constructor
constructor( container: Container, id: string, clientContext: ClientContext, partitionKey?: PartitionKey);
property container
readonly container: Container;
property id
readonly id: string;
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
method delete
delete: <T extends ItemDefinition = any>( options?: RequestOptions) => Promise<ItemResponse<T>>;
Delete the item.
Any provided type, T, is not necessarily enforced by the SDK. You may get more or less properties and it's up to your logic to enforce it.
Parameter options
Additional options for the request
method patch
patch: <T extends ItemDefinition = any>( body: PatchRequestBody, options?: RequestOptions) => Promise<ItemResponse<T>>;
Perform a JSONPatch on the item.
Any provided type, T, is not necessarily enforced by the SDK. You may get more or less properties and it's up to your logic to enforce it.
Parameter options
Additional options for the request
method read
read: <T extends ItemDefinition = any>( options?: RequestOptions) => Promise<ItemResponse<T>>;
Read the item's definition.
Any provided type, T, is not necessarily enforced by the SDK. You may get more or less properties and it's up to your logic to enforce it. If the type, T, is a class, it won't pass
typeof
comparisons, because it won't have a match prototype. It's recommended to only use interfaces.There is no set schema for JSON items. They may contain any number of custom properties.
Parameter options
Additional options for the request
Example 1
Using custom type for response
interface TodoItem {title: string;done: bool;id: string;}let item: TodoItem;({body: item} = await item.read<TodoItem>());
method replace
replace: { (body: ItemDefinition, options?: RequestOptions): Promise< ItemResponse<ItemDefinition> >; <T extends ItemDefinition>(body: T, options?: RequestOptions): Promise< ItemResponse<T> >;};
Replace the item's definition.
There is no set schema for JSON items. They may contain any number of custom properties.
Parameter body
The definition to replace the existing Item's definition with.
Parameter options
Additional options for the request
Replace the item's definition.
Any provided type, T, is not necessarily enforced by the SDK. You may get more or less properties and it's up to your logic to enforce it.
There is no set schema for JSON items. They may contain any number of custom properties.
Parameter body
The definition to replace the existing Item's definition with.
Parameter options
Additional options for the request
class ItemResponse
class ItemResponse<T extends ItemDefinition> extends ResourceResponse< T & Resource> {}
constructor
constructor( resource: ItemDefinition & Resource, headers: CosmosHeaders, statusCode: number, subsstatusCode: number, item: Item, diagnostics: CosmosDiagnostics);
property item
readonly item: Item;
Reference to the Item the response corresponds to.
class Items
class Items {}
Operations for creating new items, and reading/querying all items
See Also
Item for reading, replacing, or deleting an existing container; use
.item(id)
.
constructor
constructor(container: Container, clientContext: ClientContext);
property container
readonly container: Container;
method batch
batch: ( operations: OperationInput[], partitionKey?: PartitionKey, options?: RequestOptions) => Promise<Response_2<OperationResponse[]>>;
Execute transactional batch operations on items.
Batch takes an array of Operations which are typed based on what the operation does. Batch is transactional and will rollback all operations if one fails. The choices are: Create, Upsert, Read, Replace, and Delete
Usage example:
// The partitionKey is a required second argument. If it’s undefined, it defaults to the expected partition key format.const operations: OperationInput[] = [{operationType: "Create",resourceBody: { id: "doc1", name: "sample", key: "A" }},{operationType: "Upsert",resourceBody: { id: "doc2", name: "other", key: "A" }}]await database.container.items.batch(operations, "A")Parameter operations
List of operations. Limit 100
Parameter options
Used for modifying the request
method bulk
bulk: ( operations: OperationInput[], bulkOptions?: BulkOptions, options?: RequestOptions) => Promise<BulkOperationResponse>;
Execute bulk operations on items.
Bulk takes an array of Operations which are typed based on what the operation does. The choices are: Create, Upsert, Read, Replace, and Delete
Usage example:
// partitionKey is optional at the top level if present in the resourceBodyconst operations: OperationInput[] = [{operationType: "Create",resourceBody: { id: "doc1", name: "sample", key: "A" }},{operationType: "Upsert",partitionKey: 'A',resourceBody: { id: "doc2", name: "other", key: "A" }}]await database.container.items.bulk(operations)Parameter operations
List of operations. Limit 100
Parameter bulkOptions
Optional options object to modify bulk behavior. Pass { continueOnError: false } to stop executing operations when one fails. (Defaults to true)
Parameter options
Used for modifying the request.
method changeFeed
changeFeed: { ( partitionKey: PartitionKey, changeFeedOptions?: ChangeFeedOptions ): ChangeFeedIterator<any>; (changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<any>; <T>( partitionKey: PartitionKey, changeFeedOptions?: ChangeFeedOptions ): ChangeFeedIterator<T>; <T>(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<T>;};
Create a
ChangeFeedIterator
to iterate over pages of changesExample 1
Read from the beginning of the change feed.
const iterator = items.readChangeFeed({ startFromBeginning: true });const firstPage = await iterator.fetchNext();const firstPageResults = firstPage.resultconst secondPage = await iterator.fetchNext();Create a
ChangeFeedIterator
to iterate over pages of changes
method create
create: <T extends ItemDefinition = any>( body: T, options?: RequestOptions) => Promise<ItemResponse<T>>;
Create an item.
Any provided type, T, is not necessarily enforced by the SDK. You may get more or less properties and it's up to your logic to enforce it.
There is no set schema for JSON items. They may contain any number of custom properties.
Parameter body
Represents the body of the item. Can contain any number of user defined properties.
Parameter options
Used for modifying the request (for instance, specifying the partition key).
method getChangeFeedIterator
getChangeFeedIterator: <T>( changeFeedIteratorOptions?: ChangeFeedIteratorOptions) => ChangeFeedPullModelIterator<T>;
Returns an iterator to iterate over pages of changes. The iterator returned can be used to fetch changes for a single partition key, feed range or an entire container.
method query
query: { (query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: string | SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Queries all items.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Parameter options
Used for modifying the request (for instance, specifying the partition key).
Example 1
Read all items to array.
const querySpec: SqlQuerySpec = {query: "SELECT * FROM Families f WHERE f.lastName = @lastName",parameters: [{name: "@lastName", value: "Hendricks"}]};const {result: items} = await items.query(querySpec).fetchAll();Queries all items.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Parameter options
Used for modifying the request (for instance, specifying the partition key).
Example 1
Read all items to array.
const querySpec: SqlQuerySpec = {query: "SELECT firstname FROM Families f WHERE f.lastName = @lastName",parameters: [{name: "@lastName", value: "Hendricks"}]};const {result: items} = await items.query<{firstName: string}>(querySpec).fetchAll();
method readAll
readAll: { (options?: FeedOptions): QueryIterator<ItemDefinition>; <T extends ItemDefinition>(options?: FeedOptions): QueryIterator<T>;};
Read all items.
There is no set schema for JSON items. They may contain any number of custom properties.
Parameter options
Used for modifying the request (for instance, specifying the partition key).
Example 1
Read all items to array.
const {body: containerList} = await items.readAll().fetchAll();Read all items.
Any provided type, T, is not necessarily enforced by the SDK. You may get more or less properties and it's up to your logic to enforce it.
There is no set schema for JSON items. They may contain any number of custom properties.
Parameter options
Used for modifying the request (for instance, specifying the partition key).
Example 1
Read all items to array.
const {body: containerList} = await items.readAll().fetchAll();
method readChangeFeed
readChangeFeed: { ( partitionKey: PartitionKey, changeFeedOptions?: ChangeFeedOptions ): ChangeFeedIterator<any>; (changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<any>; <T>( partitionKey: PartitionKey, changeFeedOptions?: ChangeFeedOptions ): ChangeFeedIterator<T>; <T>(changeFeedOptions?: ChangeFeedOptions): ChangeFeedIterator<T>;};
Create a
ChangeFeedIterator
to iterate over pages of changesExample 1
Read from the beginning of the change feed.
const iterator = items.readChangeFeed({ startFromBeginning: true });const firstPage = await iterator.fetchNext();const firstPageResults = firstPage.resultconst secondPage = await iterator.fetchNext();Deprecated
Use
changeFeed
instead.Create a
ChangeFeedIterator
to iterate over pages of changesDeprecated
Use
changeFeed
instead.Create a
ChangeFeedIterator
to iterate over pages of changesDeprecated
Use
changeFeed
instead.
method upsert
upsert: { (body: unknown, options?: RequestOptions): Promise< ItemResponse<ItemDefinition> >; <T extends ItemDefinition>(body: T, options?: RequestOptions): Promise< ItemResponse<T> >;};
Upsert an item.
There is no set schema for JSON items. They may contain any number of custom properties.
Parameter body
Represents the body of the item. Can contain any number of user defined properties.
Parameter options
Used for modifying the request (for instance, specifying the partition key).
Upsert an item.
Any provided type, T, is not necessarily enforced by the SDK. You may get more or less properties and it's up to your logic to enforce it.
There is no set schema for JSON items. They may contain any number of custom properties.
Parameter body
Represents the body of the item. Can contain any number of user defined properties.
Parameter options
Used for modifying the request (for instance, specifying the partition key).
class Offer
class Offer {}
constructor
constructor(client: CosmosClient, id: string, clientContext: ClientContext);
Parameter client
The parent CosmosClient for the Database Account.
Parameter id
The id of the given Offer.
property client
readonly client: CosmosClient;
property id
readonly id: string;
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
method read
read: (options?: RequestOptions) => Promise<OfferResponse>;
Read the OfferDefinition for the given Offer.
method replace
replace: ( body: OfferDefinition, options?: RequestOptions) => Promise<OfferResponse>;
Replace the given Offer with the specified OfferDefinition.
Parameter body
The specified OfferDefinition
class OfferResponse
class OfferResponse extends ResourceResponse<OfferDefinition & Resource> {}
constructor
constructor( resource: OfferDefinition & Resource, headers: CosmosHeaders, statusCode: number, diagnostics: CosmosDiagnostics, offer?: Offer);
property offer
readonly offer: Offer;
A reference to the Offer corresponding to the returned OfferDefinition.
class Offers
class Offers {}
constructor
constructor(client: CosmosClient, clientContext: ClientContext);
Parameter client
The parent CosmosClient for the offers.
property client
readonly client: CosmosClient;
method query
query: { (query: SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Query all offers.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
method readAll
readAll: (options?: FeedOptions) => QueryIterator<OfferDefinition & Resource>;
Read all offers.
Example 1
Read all offers to array.
const {body: offerList} = await client.offers.readAll().fetchAll();
class PartitionKeyBuilder
class PartitionKeyBuilder {}
Builder class for building PartitionKey.
property values
readonly values: PrimitivePartitionKeyValue[];
method addNoneValue
addNoneValue: () => PartitionKeyBuilder;
method addNullValue
addNullValue: () => PartitionKeyBuilder;
method addValue
addValue: (value: string | boolean | number) => PartitionKeyBuilder;
method build
build: () => PartitionKey;
class Permission
class Permission {}
Use to read, replace, or delete a given Permission by id.
See Also
Permissions to create, upsert, query, or read all Permissions.
constructor
constructor(user: User, id: string, clientContext: ClientContext);
property id
readonly id: string;
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
property user
readonly user: User;
method delete
delete: (options?: RequestOptions) => Promise<PermissionResponse>;
Delete the given Permission.
method read
read: (options?: RequestOptions) => Promise<PermissionResponse>;
Read the PermissionDefinition of the given Permission.
method replace
replace: ( body: PermissionDefinition, options?: RequestOptions) => Promise<PermissionResponse>;
Replace the given Permission with the specified PermissionDefinition.
Parameter body
The specified PermissionDefinition.
class PermissionResponse
class PermissionResponse extends ResourceResponse< PermissionDefinition & PermissionBody & Resource> {}
constructor
constructor( resource: PermissionDefinition & PermissionBody & Resource, headers: CosmosHeaders, statusCode: number, permission: Permission, diagnostics: CosmosDiagnostics);
property permission
readonly permission: Permission;
A reference to the Permission corresponding to the returned PermissionDefinition.
class Permissions
class Permissions {}
Use to create, replace, query, and read all Permissions.
See Also
Permission to read, replace, or delete a specific permission by id.
constructor
constructor(user: User, clientContext: ClientContext);
Parameter user
The parent User.
property user
readonly user: User;
method create
create: ( body: PermissionDefinition, options?: RequestOptions) => Promise<PermissionResponse>;
Create a permission.
A permission represents a per-User Permission to access a specific resource e.g. Item or Container.
Parameter body
Represents the body of the permission.
method query
query: { (query: SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Query all permissions.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
method readAll
readAll: ( options?: FeedOptions) => QueryIterator<PermissionDefinition & Resource>;
Read all permissions.
Example 1
Read all permissions to array.
const {body: permissionList} = await user.permissions.readAll().fetchAll();
method upsert
upsert: ( body: PermissionDefinition, options?: RequestOptions) => Promise<PermissionResponse>;
Upsert a permission.
A permission represents a per-User Permission to access a specific resource e.g. Item or Container.
class QueryIterator
class QueryIterator<T> {}
Represents a QueryIterator Object, an implementation of feed or query response that enables traversal and iterating over the response in the Azure Cosmos DB database service.
constructor
constructor( clientContext: ClientContext, query: string | SqlQuerySpec, options: FeedOptions, fetchFunctions: FetchFunctionCallback | FetchFunctionCallback[], resourceLink?: string, resourceType?: ResourceType);
method fetchAll
fetchAll: () => Promise<FeedResponse<T>>;
Fetch all pages for the query and return a single FeedResponse.
method fetchAllInternal
fetchAllInternal: ( diagnosticNode: DiagnosticNodeInternal) => Promise<FeedResponse<T>>;
method fetchNext
fetchNext: () => Promise<FeedResponse<T>>;
Retrieve the next batch from the feed.
This may or may not fetch more pages from the backend depending on your settings and the type of query. Aggregate queries will generally fetch all backend pages before returning the first batch of responses.
method getAsyncIterator
getAsyncIterator: () => AsyncIterable<FeedResponse<T>>;
Gets an async iterator that will yield results until completion.
NOTE: AsyncIterators are a very new feature and you might need to use polyfils/etc. in order to use them in your code.
If you're using TypeScript, you can use the following polyfill as long as you target ES6 or higher and are running on Node 6 or higher.
if (!Symbol || !Symbol.asyncIterator) {(Symbol as any).asyncIterator = Symbol.for("Symbol.asyncIterator");}Example 1
Iterate over all databases
for await(const { resources: db } of client.databases.readAll().getAsyncIterator()) {console.log(`Got ${db} from AsyncIterator`);}
method hasMoreResults
hasMoreResults: () => boolean;
Determine if there are still remaining resources to process based on the value of the continuation token or the elements remaining on the current batch in the QueryIterator.
Returns
true if there is other elements to process in the QueryIterator.
method reset
reset: () => void;
Reset the QueryIterator to the beginning and clear all the resources inside it
class QueryMetrics
class QueryMetrics {}
constructor
constructor( retrievedDocumentCount: number, retrievedDocumentSize: number, outputDocumentCount: number, outputDocumentSize: number, indexHitDocumentCount: number, totalQueryExecutionTime: TimeSpan, queryPreparationTimes: QueryPreparationTimes, indexLookupTime: TimeSpan, documentLoadTime: TimeSpan, vmExecutionTime: TimeSpan, runtimeExecutionTimes: RuntimeExecutionTimes, documentWriteTime: TimeSpan, clientSideMetrics: ClientSideMetrics);
property clientSideMetrics
readonly clientSideMetrics: ClientSideMetrics;
property documentLoadTime
readonly documentLoadTime: TimeSpan;
property documentWriteTime
readonly documentWriteTime: TimeSpan;
property indexHitDocumentCount
readonly indexHitDocumentCount: number;
property indexHitRatio
readonly indexHitRatio: number;
Gets the IndexHitRatio
property indexLookupTime
readonly indexLookupTime: TimeSpan;
property outputDocumentCount
readonly outputDocumentCount: number;
property outputDocumentSize
readonly outputDocumentSize: number;
property queryPreparationTimes
readonly queryPreparationTimes: QueryPreparationTimes;
property retrievedDocumentCount
readonly retrievedDocumentCount: number;
property retrievedDocumentSize
readonly retrievedDocumentSize: number;
property runtimeExecutionTimes
readonly runtimeExecutionTimes: RuntimeExecutionTimes;
property totalQueryExecutionTime
readonly totalQueryExecutionTime: TimeSpan;
property vmExecutionTime
readonly vmExecutionTime: TimeSpan;
property zero
static readonly zero: QueryMetrics;
method add
add: (queryMetricsArray: QueryMetrics[]) => QueryMetrics;
returns a new QueryMetrics instance that is the addition of this and the arguments.
method createFromArray
static createFromArray: (queryMetricsArray: QueryMetrics[]) => QueryMetrics;
Returns a new instance of the QueryMetrics class that is the aggregation of an array of query metrics.
method createFromDelimitedString
static createFromDelimitedString: ( delimitedString: string, clientSideMetrics?: ClientSideMetrics) => QueryMetrics;
Returns a new instance of the QueryMetrics class this is deserialized from a delimited string.
method toDelimitedString
toDelimitedString: () => string;
Output the QueryMetrics as a delimited string.
class QueryPreparationTimes
class QueryPreparationTimes {}
constructor
constructor( queryCompilationTime: TimeSpan, logicalPlanBuildTime: TimeSpan, physicalPlanBuildTime: TimeSpan, queryOptimizationTime: TimeSpan);
property logicalPlanBuildTime
readonly logicalPlanBuildTime: TimeSpan;
property physicalPlanBuildTime
readonly physicalPlanBuildTime: TimeSpan;
property queryCompilationTime
readonly queryCompilationTime: TimeSpan;
property queryOptimizationTime
readonly queryOptimizationTime: TimeSpan;
property zero
static readonly zero: QueryPreparationTimes;
method add
add: ( ...queryPreparationTimesArray: QueryPreparationTimes[]) => QueryPreparationTimes;
returns a new QueryPreparationTimes instance that is the addition of this and the arguments.
method createFromArray
static createFromArray: ( queryPreparationTimesArray: QueryPreparationTimes[]) => QueryPreparationTimes;
Returns a new instance of the QueryPreparationTimes class that is the aggregation of an array of QueryPreparationTimes.
method createFromDelimitedString
static createFromDelimitedString: ( delimitedString: string) => QueryPreparationTimes;
Returns a new instance of the QueryPreparationTimes class this is deserialized from a delimited string.
method toDelimitedString
toDelimitedString: () => string;
Output the QueryPreparationTimes as a delimited string.
class ResourceResponse
class ResourceResponse<TResource> {}
constructor
constructor( resource: {}, headers: CosmosHeaders_2, statusCode: number, diagnostics: CosmosDiagnostics, substatus?: number);
property activityId
readonly activityId: string;
property diagnostics
readonly diagnostics: CosmosDiagnostics;
property etag
readonly etag: string;
property headers
readonly headers: CosmosHeaders_2;
property requestCharge
readonly requestCharge: number;
property resource
readonly resource: {};
property statusCode
readonly statusCode: number;
property substatus
readonly substatus?: number;
class RuntimeExecutionTimes
class RuntimeExecutionTimes {}
constructor
constructor( queryEngineExecutionTime: TimeSpan, systemFunctionExecutionTime: TimeSpan, userDefinedFunctionExecutionTime: TimeSpan);
property queryEngineExecutionTime
readonly queryEngineExecutionTime: TimeSpan;
property systemFunctionExecutionTime
readonly systemFunctionExecutionTime: TimeSpan;
property userDefinedFunctionExecutionTime
readonly userDefinedFunctionExecutionTime: TimeSpan;
property zero
static readonly zero: RuntimeExecutionTimes;
method add
add: ( ...runtimeExecutionTimesArray: RuntimeExecutionTimes[]) => RuntimeExecutionTimes;
returns a new RuntimeExecutionTimes instance that is the addition of this and the arguments.
method createFromArray
static createFromArray: ( runtimeExecutionTimesArray: RuntimeExecutionTimes[]) => RuntimeExecutionTimes;
Returns a new instance of the RuntimeExecutionTimes class that is the aggregation of an array of RuntimeExecutionTimes.
method createFromDelimitedString
static createFromDelimitedString: ( delimitedString: string) => RuntimeExecutionTimes;
Returns a new instance of the RuntimeExecutionTimes class this is deserialized from a delimited string.
method toDelimitedString
toDelimitedString: () => string;
Output the RuntimeExecutionTimes as a delimited string.
class SasTokenProperties
class SasTokenProperties {}
property containerName
containerName: string;
property controlPlaneReaderScope
controlPlaneReaderScope: number;
property controlPlaneWriterScope
controlPlaneWriterScope: number;
property cosmosContainerChildResourceKind
cosmosContainerChildResourceKind: CosmosContainerChildResourceKind;
property cosmosKeyType
cosmosKeyType: CosmosKeyType;
property databaseName
databaseName: string;
property dataPlaneReaderScope
dataPlaneReaderScope: number;
property dataPlaneWriterScope
dataPlaneWriterScope: number;
property expiryTime
expiryTime: Date;
property keyType
keyType: number | CosmosKeyType;
property partitionKeyValueRanges
partitionKeyValueRanges: string[];
property resourceKind
resourceKind: CosmosContainerChildResourceKind;
property resourceName
resourceName: string;
property resourcePath
resourcePath: string;
property startTime
startTime: Date;
property user
user: string;
property userTag
userTag: string;
class Scripts
class Scripts {}
constructor
constructor(container: Container, clientContext: ClientContext);
Parameter container
The parent Container.
property container
readonly container: Container;
property storedProcedures
readonly storedProcedures: StoredProcedures;
Operations for creating new stored procedures, and reading/querying all stored procedures.
For reading, replacing, or deleting an existing stored procedure, use
.storedProcedure(id)
.
property triggers
readonly triggers: Triggers;
Operations for creating new triggers, and reading/querying all triggers.
For reading, replacing, or deleting an existing trigger, use
.trigger(id)
.
property userDefinedFunctions
readonly userDefinedFunctions: UserDefinedFunctions;
Operations for creating new user defined functions, and reading/querying all user defined functions.
For reading, replacing, or deleting an existing user defined function, use
.userDefinedFunction(id)
.
method storedProcedure
storedProcedure: (id: string) => StoredProcedure;
Used to read, replace, or delete a specific, existing StoredProcedure by id.
Use
.storedProcedures
for creating new stored procedures, or querying/reading all stored procedures.Parameter id
The id of the StoredProcedure.
method trigger
trigger: (id: string) => Trigger;
method userDefinedFunction
userDefinedFunction: (id: string) => UserDefinedFunction;
Used to read, replace, or delete a specific, existing UserDefinedFunction by id.
Use
.userDefinedFunctions
for creating new user defined functions, or querying/reading all user defined functions.Parameter id
The id of the UserDefinedFunction.
class StoredProcedure
class StoredProcedure {}
Operations for reading, replacing, deleting, or executing a specific, existing stored procedure by id.
For operations to create, read all, or query Stored Procedures,
constructor
constructor(container: Container, id: string, clientContext: ClientContext);
Creates a new instance of StoredProcedure linked to the parent Container.
Parameter container
The parent Container.
Parameter id
The id of the given StoredProcedure.
property container
readonly container: Container;
property id
readonly id: string;
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
method delete
delete: (options?: RequestOptions) => Promise<StoredProcedureResponse>;
Delete the given StoredProcedure.
method execute
execute: <T = any>( partitionKey: PartitionKey, params?: any[], options?: RequestOptions) => Promise<ResourceResponse<T>>;
Execute the given StoredProcedure.
The specified type, T, is not enforced by the client. Be sure to validate the response from the stored procedure matches the type, T, you provide.
Parameter partitionKey
The partition key to use when executing the stored procedure
Parameter params
Array of parameters to pass as arguments to the given StoredProcedure.
Parameter options
Additional options, such as the partition key to invoke the StoredProcedure on.
method read
read: (options?: RequestOptions) => Promise<StoredProcedureResponse>;
Read the StoredProcedureDefinition for the given StoredProcedure.
method replace
replace: ( body: StoredProcedureDefinition, options?: RequestOptions) => Promise<StoredProcedureResponse>;
Replace the given StoredProcedure with the specified StoredProcedureDefinition.
Parameter body
The specified StoredProcedureDefinition to replace the existing definition.
class StoredProcedureResponse
class StoredProcedureResponse extends ResourceResponse< StoredProcedureDefinition & Resource> {}
constructor
constructor( resource: StoredProcedureDefinition & Resource, headers: CosmosHeaders, statusCode: number, storedProcedure: StoredProcedure, diagnostics: CosmosDiagnostics);
property sproc
readonly sproc: StoredProcedure;
Alias for storedProcedure.
A reference to the StoredProcedure which the StoredProcedureDefinition corresponds to.
property storedProcedure
readonly storedProcedure: StoredProcedure;
A reference to the StoredProcedure which the StoredProcedureDefinition corresponds to.
class StoredProcedures
class StoredProcedures {}
Operations for creating, upserting, or reading/querying all Stored Procedures.
For operations to read, replace, delete, or execute a specific, existing stored procedure by id, see
container.storedProcedure()
.
constructor
constructor(container: Container, clientContext: ClientContext);
Parameter container
The parent Container.
property container
readonly container: Container;
method create
create: ( body: StoredProcedureDefinition, options?: RequestOptions) => Promise<StoredProcedureResponse>;
Create a StoredProcedure.
Azure Cosmos DB allows stored procedures to be executed in the storage tier, directly against an item container. The script gets executed under ACID transactions on the primary storage partition of the specified container. For additional details, refer to the server-side JavaScript API documentation.
method query
query: { (query: SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Query all Stored Procedures.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
Example 1
Read all stored procedures to array.
const querySpec: SqlQuerySpec = {query: "SELECT * FROM root r WHERE r.id = @sproc",parameters: [{name: "@sproc", value: "Todo"}]};const {body: sprocList} = await containers.storedProcedures.query(querySpec).fetchAll();
method readAll
readAll: ( options?: FeedOptions) => QueryIterator<StoredProcedureDefinition & Resource>;
Read all stored procedures.
Example 1
Read all stored procedures to array.
const {body: sprocList} = await containers.storedProcedures.readAll().fetchAll();
class TimeoutError
class TimeoutError extends Error {}
constructor
constructor(message?: string);
property code
readonly code: string;
class TimeSpan
class TimeSpan {}
Represents a time interval.
Parameter days
Number of days.
Parameter hours
Number of hours.
Parameter minutes
Number of minutes.
Parameter seconds
Number of seconds.
Parameter milliseconds
Number of milliseconds.
constructor
constructor( days: number, hours: number, minutes: number, seconds: number, milliseconds: number);
property maxValue
static readonly maxValue: TimeSpan;
property minValue
static readonly minValue: TimeSpan;
property zero
static readonly zero: TimeSpan;
method add
add: (ts: TimeSpan) => TimeSpan;
Returns a new TimeSpan object whose value is the sum of the specified TimeSpan object and this instance.
Parameter ts
The time interval to add.
method additionDoesOverflow
static additionDoesOverflow: (a: number, b: number) => boolean;
method compare
static compare: (t1: TimeSpan, t2: TimeSpan) => 1 | 0 | -1;
method compareTo
compareTo: (value: TimeSpan) => 1 | -1 | 0;
Compares this instance to a specified object and returns an integer that indicates whether this instance is shorter than, equal to, or longer than the specified object.
Parameter value
The time interval to add.
method days
days: () => number;
method duration
duration: () => TimeSpan;
Returns a new TimeSpan object whose value is the absolute value of the current TimeSpan object.
method equals
equals: (value: TimeSpan) => boolean;
Returns a value indicating whether this instance is equal to a specified object.
Parameter value
The time interval to check for equality.
method fromDays
static fromDays: (value: number) => TimeSpan;
method fromHours
static fromHours: (value: number) => TimeSpan;
method fromMilliseconds
static fromMilliseconds: (value: number) => TimeSpan;
method fromMinutes
static fromMinutes: (value: number) => TimeSpan;
method fromSeconds
static fromSeconds: (value: number) => TimeSpan;
method fromTicks
static fromTicks: (value: number) => TimeSpan;
method hours
hours: () => number;
method interval
static interval: (value: number, scale: number) => TimeSpan;
method isTimeSpan
static isTimeSpan: (timespan: TimeSpan) => number;
method milliseconds
milliseconds: () => number;
method negate
negate: () => TimeSpan;
Returns a new TimeSpan object whose value is the negated value of this instance.
Parameter value
The time interval to check for equality.
method seconds
seconds: () => number;
method subtract
subtract: (ts: TimeSpan) => TimeSpan;
Returns a new TimeSpan object whose value is the difference of the specified TimeSpan object and this instance.
Parameter ts
The time interval to subtract.
method subtractionDoesUnderflow
static subtractionDoesUnderflow: (a: number, b: number) => boolean;
method ticks
ticks: () => number;
method totalDays
totalDays: () => number;
method totalHours
totalHours: () => number;
method totalMilliseconds
totalMilliseconds: () => number;
method totalMinutes
totalMinutes: () => number;
method totalSeconds
totalSeconds: () => number;
class Trigger
class Trigger {}
Operations to read, replace, or delete a Trigger.
Use
container.triggers
to create, upsert, query, or read all.
constructor
constructor(container: Container, id: string, clientContext: ClientContext);
property container
readonly container: Container;
property id
readonly id: string;
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
method delete
delete: (options?: RequestOptions) => Promise<TriggerResponse>;
Delete the given Trigger.
method read
read: (options?: RequestOptions) => Promise<TriggerResponse>;
Read the TriggerDefinition for the given Trigger.
method replace
replace: ( body: TriggerDefinition, options?: RequestOptions) => Promise<TriggerResponse>;
Replace the given Trigger with the specified TriggerDefinition.
Parameter body
The specified TriggerDefinition to replace the existing definition with.
class TriggerResponse
class TriggerResponse extends ResourceResponse<TriggerDefinition & Resource> {}
constructor
constructor( resource: TriggerDefinition & Resource, headers: CosmosHeaders, statusCode: number, trigger: Trigger, diagnostics: CosmosDiagnostics);
property trigger
readonly trigger: Trigger;
A reference to the Trigger corresponding to the returned TriggerDefinition.
class Triggers
class Triggers {}
Operations to create, upsert, query, and read all triggers.
Use
container.triggers
to read, replace, or delete a Trigger.
constructor
constructor(container: Container, clientContext: ClientContext);
Parameter container
The parent Container.
property container
readonly container: Container;
method create
create: ( body: TriggerDefinition, options?: RequestOptions) => Promise<TriggerResponse>;
Create a trigger.
Azure Cosmos DB supports pre and post triggers defined in JavaScript to be executed on creates, updates and deletes.
For additional details, refer to the server-side JavaScript API documentation.
method query
query: { (query: SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Query all Triggers.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
method readAll
readAll: (options?: FeedOptions) => QueryIterator<TriggerDefinition & Resource>;
Read all Triggers.
Example 1
Read all trigger to array.
const {body: triggerList} = await container.triggers.readAll().fetchAll();
class User
class User {}
Used to read, replace, and delete Users.
Additionally, you can access the permissions for a given user via
user.permission
anduser.permissions
.See Also
Users to create, upsert, query, or read all.
constructor
constructor(database: Database, id: string, clientContext: ClientContext);
Parameter database
The parent Database.
property database
readonly database: Database;
property id
readonly id: string;
property permissions
readonly permissions: Permissions;
Operations for creating, upserting, querying, or reading all operations.
See
client.permission(id)
to read, replace, or delete a specific Permission by id.
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
method delete
delete: (options?: RequestOptions) => Promise<UserResponse>;
Delete the given User.
method permission
permission: (id: string) => Permission;
Operations to read, replace, or delete a specific Permission by id.
See
client.permissions
for creating, upserting, querying, or reading all operations.
method read
read: (options?: RequestOptions) => Promise<UserResponse>;
Read the UserDefinition for the given User.
method replace
replace: ( body: UserDefinition, options?: RequestOptions) => Promise<UserResponse>;
Replace the given User's definition with the specified UserDefinition.
Parameter body
The specified UserDefinition to replace the definition.
class UserDefinedFunction
class UserDefinedFunction {}
Used to read, replace, or delete a specified User Definied Function by id.
See Also
UserDefinedFunction to create, upsert, query, read all User Defined Functions.
constructor
constructor(container: Container, id: string, clientContext: ClientContext);
property container
readonly container: Container;
property id
readonly id: string;
property url
readonly url: string;
Returns a reference URL to the resource. Used for linking in Permissions.
method delete
delete: (options?: RequestOptions) => Promise<UserDefinedFunctionResponse>;
Delete the given UserDefined.
method read
read: (options?: RequestOptions) => Promise<UserDefinedFunctionResponse>;
Read the UserDefinedFunctionDefinition for the given UserDefinedFunction.
method replace
replace: ( body: UserDefinedFunctionDefinition, options?: RequestOptions) => Promise<UserDefinedFunctionResponse>;
Replace the given UserDefinedFunction with the specified UserDefinedFunctionDefinition.
Parameter options
class UserDefinedFunctionResponse
class UserDefinedFunctionResponse extends ResourceResponse< UserDefinedFunctionDefinition & Resource> {}
constructor
constructor( resource: UserDefinedFunctionDefinition & Resource, headers: CosmosHeaders, statusCode: number, udf: UserDefinedFunction, diagnostics: CosmosDiagnostics);
property udf
readonly udf: UserDefinedFunction;
Alias for
userDefinedFunction(id)
.A reference to the UserDefinedFunction corresponding to the returned UserDefinedFunctionDefinition.
property userDefinedFunction
readonly userDefinedFunction: UserDefinedFunction;
A reference to the UserDefinedFunction corresponding to the returned UserDefinedFunctionDefinition.
class UserDefinedFunctions
class UserDefinedFunctions {}
Used to create, upsert, query, or read all User Defined Functions.
See Also
UserDefinedFunction to read, replace, or delete a given User Defined Function by id.
constructor
constructor(container: Container, clientContext: ClientContext);
Parameter container
The parent Container.
property container
readonly container: Container;
method create
create: ( body: UserDefinedFunctionDefinition, options?: RequestOptions) => Promise<UserDefinedFunctionResponse>;
Create a UserDefinedFunction.
Azure Cosmos DB supports JavaScript UDFs which can be used inside queries, stored procedures and triggers.
For additional details, refer to the server-side JavaScript API documentation.
method query
query: { (query: SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Query all User Defined Functions.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
method readAll
readAll: ( options?: FeedOptions) => QueryIterator<UserDefinedFunctionDefinition & Resource>;
Read all User Defined Functions.
Example 1
Read all User Defined Functions to array.
const {body: udfList} = await container.userDefinedFunctions.readAll().fetchAll();
class UserResponse
class UserResponse extends ResourceResponse<UserDefinition & Resource> {}
constructor
constructor( resource: UserDefinition & Resource, headers: CosmosHeaders, statusCode: number, user: User, diagnostics: CosmosDiagnostics);
property user
readonly user: User;
A reference to the User corresponding to the returned UserDefinition.
class Users
class Users {}
Used to create, upsert, query, and read all users.
See Also
User to read, replace, or delete a specific User by id.
constructor
constructor(database: Database, clientContext: ClientContext);
Parameter database
The parent Database.
property database
readonly database: Database;
method create
create: ( body: UserDefinition, options?: RequestOptions) => Promise<UserResponse>;
Create a database user with the specified UserDefinition.
Parameter body
The specified UserDefinition.
method query
query: { (query: SqlQuerySpec, options?: FeedOptions): QueryIterator<any>; <T>(query: SqlQuerySpec, options?: FeedOptions): QueryIterator<T>;};
Query all users.
Parameter query
Query configuration for the operation. See SqlQuerySpec for more info on how to configure a query.
method readAll
readAll: (options?: FeedOptions) => QueryIterator<UserDefinition & Resource>;
Read all users.-
Example 1
Read all users to array.
const {body: usersList} = await database.users.readAll().fetchAll();
method upsert
upsert: ( body: UserDefinition, options?: RequestOptions) => Promise<UserResponse>;
Upsert a database user with a specified UserDefinition.
Parameter body
The specified UserDefinition.
Interfaces
interface Agent
interface Agent {}
property maxFreeSockets
maxFreeSockets: number;
property maxSockets
maxSockets: number;
property requests
requests: any;
property sockets
sockets: any;
method destroy
destroy: () => void;
interface BulkOptions
interface BulkOptions {}
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
property continueOnError
continueOnError?: boolean;
interface ChangeFeedIteratorOptions
interface ChangeFeedIteratorOptions {}
Specifies options for the change feed
If none of those options are set, it will start reading changes from now for the entire container.
property changeFeedMode
changeFeedMode?: ChangeFeedMode;
Signals the mode in which the change feed needs to start.
property changeFeedStartFrom
changeFeedStartFrom?: ChangeFeedStartFrom;
Signals where to start from in the change feed.
property maxItemCount
maxItemCount?: number;
Max amount of items to return per page
property sessionToken
sessionToken?: string;
The session token to use. If not specified, will use the most recent captured session token to start with.
interface ChangeFeedOptions
interface ChangeFeedOptions {}
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.
property continuation
continuation?: string;
The continuation token to start from.
This is equivalent to the etag and continuation value from the
ChangeFeedResponse
property maxItemCount
maxItemCount?: number;
Max amount of items to return per page
property sessionToken
sessionToken?: string;
The session token to use. If not specified, will use the most recent captured session token to start with.
property startFromBeginning
startFromBeginning?: boolean;
Signals whether to start from the beginning or not.
property startTime
startTime?: Date;
Specified the start time to start reading changes from.
interface ChangeFeedPullModelIterator
interface ChangeFeedPullModelIterator<T> {}
Use
Items.getChangeFeedIterator()
to return an iterator that can iterate over all the changes for a partition key, feed range or an entire container.
property hasMoreResults
readonly hasMoreResults: boolean;
Always returns true, changefeed is an infinite stream.
method getAsyncIterator
getAsyncIterator: () => AsyncIterable< ChangeFeedIteratorResponse<Array<T & Resource>>>;
Gets an async iterator which will yield change feed results.
Example 1
Get changefeed for an entire container from now
const options = { changeFeedStartFrom: ChangeFeedStartFrom.Now() };for await(const res of container.items.getChangeFeedIterator(options).getAsyncIterator()) {//process res}
method readNext
readNext: () => Promise<ChangeFeedIteratorResponse<Array<T & Resource>>>;
Returns next set of results for the change feed.
interface CompositePath
interface CompositePath {}
Represents a composite path in the indexing policy.
interface ComputedProperty
interface ComputedProperty {}
property name
name: string;
The name of the computed property. Name of the computed property should be chosen such that it does not collide with any existing or future document properties.
property query
query: string;
index signature
[key: string]: any;
interface ConflictDefinition
interface ConflictDefinition {}
property content
content?: string;
property id
id?: string;
The id of the conflict
property operationType
operationType?: OperationType;
property resourceId
resourceId?: string;
Source resource id
property resourceType
resourceType?: ResourceType;
interface ConflictResolutionPolicy
interface ConflictResolutionPolicy {}
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.
property conflictResolutionPath
conflictResolutionPath?: string;
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 ConflictResolutionMode.LastWriterWins.
conflictResolutionPolicy.ConflictResolutionPath = "/name/first";
property conflictResolutionProcedure
conflictResolutionProcedure?: string;
Gets or sets the StoredProcedure which is used for conflict resolution in the Azure Cosmos DB service. This stored procedure may be created after the Container is created and can be changed as required.
1. This value should only be set when using 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.
conflictResolutionPolicy.ConflictResolutionProcedure = "resolveConflict"
property mode
mode?: keyof typeof ConflictResolutionMode;
Gets or sets the in the Azure Cosmos DB service. By default it is ConflictResolutionMode.LastWriterWins.
interface ConnectionPolicy
interface ConnectionPolicy {}
Represents the Connection policy associated with a CosmosClient in the Azure Cosmos DB database service.
property connectionMode
connectionMode?: ConnectionMode;
Determines which mode to connect to Cosmos with. (Currently only supports Gateway option)
property enableBackgroundEndpointRefreshing
enableBackgroundEndpointRefreshing?: boolean;
Flag to enable/disable background refreshing of endpoints. Defaults to false. Endpoint discovery using
enableEndpointsDiscovery
will still work for failed requests.
property enableEndpointDiscovery
enableEndpointDiscovery?: boolean;
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.
property endpointRefreshRateInMs
endpointRefreshRateInMs?: number;
Rate in milliseconds at which the client will refresh the endpoints list in the background
property preferredLocations
preferredLocations?: string[];
List of azure regions to be used as preferred locations for read requests.
property requestTimeout
requestTimeout?: number;
Request timeout (time to wait for response from network peer). Represented in milliseconds.
property retryOptions
retryOptions?: RetryOptions;
RetryOptions object which defines several configurable properties used during retry.
property useMultipleWriteLocations
useMultipleWriteLocations?: boolean;
The flag that enables writes on any locations (regions) for geo-replicated database accounts in the Azure Cosmos DB service. Default is
false
.
interface ContainerDefinition
interface ContainerDefinition {}
property changeFeedPolicy
changeFeedPolicy?: ChangeFeedPolicy;
Change feed policy related to the container
property computedProperties
computedProperties?: ComputedProperty[];
The computed properties of the container
property conflictResolutionPolicy
conflictResolutionPolicy?: ConflictResolutionPolicy;
The conflict resolution policy used to resolve conflicts in a container.
property defaultTtl
defaultTtl?: number;
The default time to live in seconds for items in a container.
property fullTextPolicy
fullTextPolicy?: FullTextPolicy;
The full text policy information for storing items in a container.
property geospatialConfig
geospatialConfig?: { type: GeospatialType;};
Geospatial configuration for a collection. Type is set to Geography by default
property id
id?: string;
The id of the container.
property indexingPolicy
indexingPolicy?: IndexingPolicy;
The indexing policy associated with the container.
property partitionKey
partitionKey?: PartitionKeyDefinition;
The partition key for the container.
property uniqueKeyPolicy
uniqueKeyPolicy?: UniqueKeyPolicy;
Policy for additional keys that must be unique per partition key
property vectorEmbeddingPolicy
vectorEmbeddingPolicy?: VectorEmbeddingPolicy;
The vector embedding policy information for storing items in a container.
interface ContainerRequest
interface ContainerRequest extends VerboseOmit<ContainerDefinition, 'partitionKey'> {}
property autoUpgradePolicy
autoUpgradePolicy?: { throughputPolicy: { incrementPercent: number; };};
property maxThroughput
maxThroughput?: number;
property partitionKey
partitionKey?: string | PartitionKeyDefinition;
property throughput
throughput?: number;
interface CosmosClientOptions
interface CosmosClientOptions {}
property aadCredentials
aadCredentials?: TokenCredential;
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
property agent
agent?: Agent;
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
property connectionPolicy
connectionPolicy?: ConnectionPolicy;
An instance of ConnectionPolicy class. This parameter is optional and the default connectionPolicy will be used if omitted.
property consistencyLevel
consistencyLevel?: keyof typeof ConsistencyLevel;
An optional parameter that represents the consistency level. It can take any value from ConsistencyLevel.
property defaultHeaders
defaultHeaders?: CosmosHeaders_2;
property diagnosticLevel
diagnosticLevel?: CosmosDbDiagnosticLevel;
property endpoint
endpoint: string;
The service endpoint to use to create the client.
property httpClient
httpClient?: HttpClient;
An optional custom
HttpClient
shape to customize how requests are made by the HTTP pipeline. See@azure/core-rest-pipeline
for details on how to implement this interface.
property key
key?: string;
The account master or readonly key
property permissionFeed
permissionFeed?: PermissionDefinition[];
An array of Permission objects.
property resourceTokens
resourceTokens?: { [resourcePath: string]: string;};
An object that contains resources tokens. Keys for the object are resource Ids and values are the resource tokens.
property tokenProvider
tokenProvider?: TokenProvider;
A user supplied function for resolving header authorization tokens. Allows users to generating their own auth tokens, potentially using a separate service
property userAgentSuffix
userAgentSuffix?: string;
A custom string to append to the default SDK user agent.
interface CosmosHeaders
interface CosmosHeaders {}
index signature
[key: string]: any;
interface CreateOperationInput
interface CreateOperationInput {}
property ifMatch
ifMatch?: string;
property ifNoneMatch
ifNoneMatch?: string;
property operationType
operationType: typeof BulkOperationType.Create;
property partitionKey
partitionKey?: PartitionKey;
property resourceBody
resourceBody: JSONObject;
interface DatabaseDefinition
interface DatabaseDefinition {}
property id
id?: string;
The id of the database.
interface DatabaseRequest
interface DatabaseRequest extends DatabaseDefinition {}
property autoUpgradePolicy
autoUpgradePolicy?: { throughputPolicy: { incrementPercent: number; };};
property maxThroughput
maxThroughput?: number;
property throughput
throughput?: number;
Throughput for this database.
interface DeleteOperationInput
interface DeleteOperationInput {}
property id
id: string;
property operationType
operationType: typeof BulkOperationType.Delete;
property partitionKey
partitionKey?: PartitionKey;
interface DiagnosticNode
interface DiagnosticNode {}
Represents a tree like structure, for capturing diagnostic information.
property children
children: DiagnosticNode[];
property data
data: { [key: string]: any;};
property durationInMs
durationInMs: number;
property id
id: string;
property nodeType
nodeType: string;
property startTimeUTCInMs
startTimeUTCInMs: number;
interface ErrorBody
interface ErrorBody {}
property additionalErrorInfo
additionalErrorInfo?: PartitionedQueryExecutionInfo;
property code
code: string;
property message
message: string;
interface FailedRequestAttemptDiagnostic
interface FailedRequestAttemptDiagnostic {}
This type captures diagnostic information regarding a failed request to server api.
property activityId
activityId: string;
property attemptNumber
attemptNumber: number;
property durationInMs
durationInMs: number;
property operationType
operationType?: OperationType;
property requestPayloadLengthInBytes
requestPayloadLengthInBytes: number;
property resourceType
resourceType?: ResourceType;
property responsePayloadLengthInBytes
responsePayloadLengthInBytes: number;
property startTimeUTCInMs
startTimeUTCInMs: number;
property statusCode
statusCode: number;
property substatusCode
substatusCode?: number;
interface FeedOptions
interface FeedOptions extends SharedOptions {}
The feed options and query methods.
property accessCondition
accessCondition?: { /** Conditional HTTP method header type (IfMatch or IfNoneMatch). */ type: string; /** Conditional HTTP method header value (the _etag field from the last version you read). */ condition: string;};
Conditions Associated with the request.
property allowUnboundedNonStreamingQueries
allowUnboundedNonStreamingQueries?: boolean;
Valid only for non streaming order by query. Default: false; When set to true, it allows queries to bypass the default behavior that blocks nonStreaming queries without top or limit clauses.
property bufferItems
bufferItems?: boolean;
Enable buffering additional items during queries. Default: false
This will buffer an additional page at a time (multiplied by maxDegreeOfParallelism) from the server in the background. This improves latency by fetching pages before they are needed by the client. If you're draining all of the results from the server, like
.fetchAll
, you should usually enable this. If you're only fetching one page at a time via continuation token, you should avoid this. If you're draining more than one page, but not the entire result set, it may help improve latency, but it will increase the total amount of RU/s use to serve the entire query (as some pages will be fetched more than once).
property continuation
continuation?: string;
Opaque token for continuing the enumeration. Default: undefined
Deprecated
Use continuationToken instead.
property continuationToken
continuationToken?: string;
Opaque token for continuing the enumeration. Default: undefined
property continuationTokenLimitInKB
continuationTokenLimitInKB?: number;
Limits the size of the continuation token in the response. Default: undefined
Continuation Tokens contain optional data that can be removed from the serialization before writing it out to a header. By default we are capping this to 1kb to avoid long headers (Node.js has a global header size limit). A user may set this field to allow for longer headers, which can help the backend optimize query execution."
property disableNonStreamingOrderByQuery
disableNonStreamingOrderByQuery?: boolean;
Disable the nonStreamingOrderBy query feature in supported query features. Default: false. Set to true to avoid error from an old gateway that doesn't support this feature.
property enableScanInQuery
enableScanInQuery?: boolean;
Allow scan on the queries which couldn't be served as indexing was opted out on the requested paths. Default: false
In general, it is best to avoid using this setting. Scans are relatively expensive and take a long time to serve.
property forceQueryPlan
forceQueryPlan?: boolean;
This setting forces the query to use a query plan. Default: false
Note: this will disable continuation token support, even for single partition queries.
For queries like aggregates and most cross partition queries, this happens anyway. However, since the library doesn't know what type of query it is until we get back the first response, some optimization can't happen until later.
If this setting is enabled, it will force query plan for the query, which will save some network requests and ensure parallelism can happen. Useful for when you know you're doing cross-partition or aggregate queries.
property maxDegreeOfParallelism
maxDegreeOfParallelism?: number;
The maximum number of concurrent operations that run client side during parallel query execution in the Azure Cosmos DB database service. Negative values make the system automatically decides the number of concurrent operations to run. Default: 0 (no parallelism)
property maxItemCount
maxItemCount?: number;
Max number of items to be returned in the enumeration operation. Default: undefined (server will defined payload)
Expirimenting with this value can usually result in the biggest performance changes to the query.
The smaller the item count, the faster the first result will be delivered (for non-aggregates). For larger amounts, it will take longer to serve the request, but you'll usually get better throughput for large queries (i.e. if you need 1000 items before you can do any other actions, set
maxItemCount
to 1000. If you can start doing work after the first 100, setmaxItemCount
to 100.)
property partitionKey
partitionKey?: PartitionKey;
Limits the query to a specific partition key. Default: undefined
Scoping a query to a single partition can be accomplished two ways:
container.items.query('SELECT * from c', { partitionKey: "foo" }).toArray()
container.items.query('SELECT * from c WHERE c.yourPartitionKey = "foo"').toArray()
The former is useful when the query body is out of your control but you still want to restrict it to a single partition. Example: an end user specified query.
property populateIndexMetrics
populateIndexMetrics?: boolean;
Enable returning index metrics in response headers. Default: false
property populateQueryMetrics
populateQueryMetrics?: boolean;
Enable returning query metrics in response headers. Default: false
Used for debugging slow or expensive queries. Also increases response size and if you're using a low max header size in Node.js, you can run into issues faster.
property useIncrementalFeed
useIncrementalFeed?: boolean;
Note: consider using changeFeed instead.
Indicates a change feed request. Must be set to "Incremental feed", or omitted otherwise. Default: false
property vectorSearchBufferSize
vectorSearchBufferSize?: number;
Specifies a custom maximum buffer size for storing final results for nonStreamingOrderBy queries. This value is ignored if the query includes top/offset+limit clauses.
interface FullTextIndex
interface FullTextIndex {}
Represents a full text index in the indexing policy.
property path
path: string;
The path in the JSON document to index.
interface FullTextPath
interface FullTextPath {}
Represents a full text path to be indexed in the Azure Cosmos DB service.
interface FullTextPolicy
interface FullTextPolicy {}
Represents a full text policy for a collection in the Azure Cosmos DB service.
property defaultLanguage
defaultLanguage: string;
The default language for the full text .
property fullTextPaths
fullTextPaths: FullTextPath[];
The paths to be indexed for full text search.
interface GroupByAliasToAggregateType
interface GroupByAliasToAggregateType {}
index signature
[key: string]: AggregateType;
interface HybridSearchQueryInfo
interface HybridSearchQueryInfo {}
Represents the hybrid search query information
property componentQueryInfos
componentQueryInfos: QueryInfo[];
Query information for the subsequent queries
property globalStatisticsQuery
globalStatisticsQuery: string;
The query to be used for fetching global statistics
property requiresGlobalStatistics
requiresGlobalStatistics: boolean;
Whether the query requires global statistics
property skip
skip: number;
The number of results to skip in the final result set
property take
take: number;
The number of results in the final result set
interface Index
interface Index {}
interface IndexedPath
interface IndexedPath {}
interface IndexingPolicy
interface IndexingPolicy {}
property automatic
automatic?: boolean;
property compositeIndexes
compositeIndexes?: CompositePath[][];
An array of CompositeIndexes representing composite indexes to be included.
property excludedPaths
excludedPaths?: IndexedPath[];
An array of IncludedPath represents the paths to be excluded for indexing.
property fullTextIndexes
fullTextIndexes?: FullTextIndex[];
An array of FullTextIndex representing full text indexes to be included.
property includedPaths
includedPaths?: IndexedPath[];
An array of IncludedPath represents the paths to be included for indexing.
property indexingMode
indexingMode?: keyof typeof IndexingMode;
The indexing mode (consistent or lazy) IndexingMode.
property spatialIndexes
spatialIndexes?: SpatialIndex[];
property vectorIndexes
vectorIndexes?: VectorIndex[];
An array of VectorIndex represents the vector index paths to be included for indexing.
interface ItemDefinition
interface ItemDefinition {}
Items in Cosmos DB are simply JSON objects. Most of the Item operations allow for your to provide your own type that extends the very simple ItemDefinition.
You cannot use any reserved keys. You can see the reserved key list in ItemBody
property id
id?: string;
The id of the item. User settable property. Uniquely identifies the item along with the partition key
property ttl
ttl?: number;
Time to live in seconds for collections with TTL enabled
index signature
[key: string]: any;
interface JSONArray
interface JSONArray extends ArrayLike<JSONValue> {}
interface JSONObject
interface JSONObject {}
index signature
[key: string]: JSONValue;
interface Location
interface Location {}
Used to specify the locations that are available, read is index 1 and write is index 0.
property databaseAccountEndpoint
databaseAccountEndpoint: string;
property lastUnavailabilityTimestampInMs
lastUnavailabilityTimestampInMs?: number;
property name
name: string;
property unavailable
unavailable?: boolean;
interface MetadataLookUpDiagnostic
interface MetadataLookUpDiagnostic {}
This type contains diagnostic information regarding a single metadata request to server.
property activityId
activityId: string;
property durationInMs
durationInMs: number;
property metaDataType
metaDataType: MetadataLookUpType;
property operationType
operationType?: OperationType;
property requestPayloadLengthInBytes
requestPayloadLengthInBytes: number;
property resourceType
resourceType?: ResourceType;
property responsePayloadLengthInBytes
responsePayloadLengthInBytes: number;
property startTimeUTCInMs
startTimeUTCInMs: number;
interface OfferDefinition
interface OfferDefinition {}
property content
content?: { offerThroughput: number; offerIsRUPerMinuteThroughputEnabled: boolean; offerMinimumThroughputParameters?: { maxThroughputEverProvisioned: number; maxConsumedStorageEverInKB: number; }; offerAutopilotSettings?: { tier: number; maximumTierThroughput: number; autoUpgrade: boolean; maxThroughput: number; };};
property id
id?: string;
property offerResourceId
offerResourceId?: string;
property offerType
offerType?: string;
property offerVersion
offerVersion?: string;
property resource
resource?: string;
interface OperationBase
interface OperationBase {}
property ifMatch
ifMatch?: string;
property ifNoneMatch
ifNoneMatch?: string;
property partitionKey
partitionKey?: string;
interface OperationResponse
interface OperationResponse {}
property eTag
eTag?: string;
property requestCharge
requestCharge: number;
property resourceBody
resourceBody?: JSONObject;
property statusCode
statusCode: number;
interface PartitionedQueryExecutionInfo
interface PartitionedQueryExecutionInfo {}
property hybridSearchQueryInfo
hybridSearchQueryInfo?: HybridSearchQueryInfo;
Represents hybrid query information.
property partitionedQueryExecutionInfoVersion
partitionedQueryExecutionInfoVersion: number;
property queryInfo
queryInfo?: QueryInfo;
property queryRanges
queryRanges: QueryRange[];
interface PartitionKeyDefinition
interface PartitionKeyDefinition {}
property kind
kind?: PartitionKeyKind;
What kind of partition key is being defined (default: "Hash")
property paths
paths: string[];
An array of paths for which data within the collection can be partitioned. Paths must not contain a wildcard or a trailing slash. For example, the JSON property “AccountNumber” is specified as “/AccountNumber”. The array must contain only a single value.
property systemKey
systemKey?: boolean;
property version
version?: PartitionKeyDefinitionVersion;
An optional field, if not specified the default value is 1. To use the large partition key set the version to 2. To learn about large partition keys, see [how to create containers with large partition key](https://docs.microsoft.com/en-us/azure/cosmos-db/large-partition-keys) article.
interface PartitionKeyRange
interface PartitionKeyRange {}
property id
id: string;
property maxExclusive
maxExclusive: string;
property minInclusive
minInclusive: string;
property parents
parents: string[];
property ridPrefix
ridPrefix: number;
property status
status: string;
property throughputFraction
throughputFraction: number;
interface PartitionKeyRangePropertiesNames
interface PartitionKeyRangePropertiesNames {}
property Id
Id: 'id';
property MaxExclusive
MaxExclusive: 'maxExclusive';
property MinInclusive
MinInclusive: 'minInclusive';
interface PatchOperationInput
interface PatchOperationInput {}
property id
id: string;
property ifMatch
ifMatch?: string;
property ifNoneMatch
ifNoneMatch?: string;
property operationType
operationType: typeof BulkOperationType.Patch;
property partitionKey
partitionKey?: PartitionKey;
property resourceBody
resourceBody: PatchRequestBody;
interface PermissionBody
interface PermissionBody {}
interface PermissionDefinition
interface PermissionDefinition {}
property id
id: string;
The id of the permission
property permissionMode
permissionMode: PermissionMode;
The mode of the permission, must be a value of PermissionMode
property resource
resource: string;
The link of the resource that the permission will be applied to.
property resourcePartitionKey
resourcePartitionKey?: string | any[];
interface PluginConfig
interface PluginConfig {}
Specifies which event to run for the specified plugin
interface QueryInfo
interface QueryInfo {}
property aggregates
aggregates?: AggregateType[];
property distinctType
distinctType: string;
property groupByAliasToAggregateType
groupByAliasToAggregateType: GroupByAliasToAggregateType;
property groupByExpressions
groupByExpressions?: GroupByExpressions;
property hasNonStreamingOrderBy
hasNonStreamingOrderBy: boolean;
determines whether the query is of non streaming orderby type.
property hasSelectValue
hasSelectValue: boolean;
property limit
limit?: number;
property offset
offset?: number;
property orderBy
orderBy?: any[];
property orderByExpressions
orderByExpressions?: any[];
property rewrittenQuery
rewrittenQuery?: any;
property top
top?: any;
interface QueryRange
interface QueryRange {}
property isMaxInclusive
isMaxInclusive: boolean;
property isMinInclusive
isMinInclusive: boolean;
property max
max: string;
property min
min: string;
interface ReadOperationInput
interface ReadOperationInput {}
property id
id: string;
property operationType
operationType: typeof BulkOperationType.Read;
property partitionKey
partitionKey?: PartitionKey;
interface ReplaceOperationInput
interface ReplaceOperationInput {}
property id
id: string;
property ifMatch
ifMatch?: string;
property ifNoneMatch
ifNoneMatch?: string;
property operationType
operationType: typeof BulkOperationType.Replace;
property partitionKey
partitionKey?: PartitionKey;
property resourceBody
resourceBody: JSONObject;
interface RequestContext
interface RequestContext {}
property body
body?: any;
property client
client?: ClientContext;
property connectionPolicy
connectionPolicy: ConnectionPolicy;
property endpoint
endpoint?: string;
property globalEndpointManager
globalEndpointManager: GlobalEndpointManager;
property headers
headers?: CosmosHeaders_2;
property httpClient
httpClient?: HttpClient;
property method
method: HTTPMethod;
property operationType
operationType?: OperationType;
property options
options: FeedOptions | RequestOptions;
property partitionKey
partitionKey?: PartitionKey;
property partitionKeyRangeId
partitionKeyRangeId?: string;
property path
path?: string;
property pipeline
pipeline?: Pipeline;
property plugins
plugins: PluginConfig[];
property requestAgent
requestAgent: Agent;
property resourceId
resourceId?: string;
property resourceType
resourceType?: ResourceType;
property retryCount
retryCount?: number;
interface RequestInfo
interface RequestInfo {}
property headers
headers: CosmosHeaders;
property path
path: string;
property resourceId
resourceId: string;
property resourceType
resourceType: ResourceType;
property verb
verb: HTTPMethod;
interface RequestOptions
interface RequestOptions extends SharedOptions {}
Options that can be specified for a requested issued to the Azure Cosmos DB servers.=
property accessCondition
accessCondition?: { /** Conditional HTTP method header type (IfMatch or IfNoneMatch). */ type: string; /** Conditional HTTP method header value (the _etag field from the last version you read). */ condition: string;};
Conditions Associated with the request.
property consistencyLevel
consistencyLevel?: string;
Consistency level required by the client.
property disableAutomaticIdGeneration
disableAutomaticIdGeneration?: boolean;
Disable automatic id generation (will cause creates to fail if id isn't on the definition)
property disableRUPerMinuteUsage
disableRUPerMinuteUsage?: boolean;
DisableRUPerMinuteUsage is used to enable/disable Request Units(RUs)/minute capacity to serve the request if regular provisioned RUs/second is exhausted.
property enableScriptLogging
enableScriptLogging?: boolean;
Enables or disables logging in JavaScript stored procedures.
property indexingDirective
indexingDirective?: string;
Specifies indexing directives (index, do not index .. etc).
property offerThroughput
offerThroughput?: number;
The offer throughput provisioned for a container in measurement of Requests-per-Unit.
property offerType
offerType?: string;
Offer type when creating document containers.
This option is only valid when creating a document container.
property populateQuotaInfo
populateQuotaInfo?: boolean;
Enables/disables getting document container quota related stats for document container read requests.
property postTriggerInclude
postTriggerInclude?: string | string[];
Indicates what is the post trigger to be invoked after the operation.
property preTriggerInclude
preTriggerInclude?: string | string[];
Indicates what is the pre trigger to be invoked before the operation.
property resourceTokenExpirySeconds
resourceTokenExpirySeconds?: number;
Expiry time (in seconds) for resource token associated with permission (applicable only for requests on permissions).
property urlConnection
urlConnection?: string;
(Advanced use case) The url to connect to.
interface Resource
interface Resource {}
property id
id: string;
Required. User settable property. Unique name that identifies the item, that is, no two items share the same ID within a database. The id must not exceed 255 characters.
interface Response
interface Response_2<T> {}
property code
code?: number;
property diagnostics
diagnostics?: CosmosDiagnostics;
property headers
headers: CosmosHeaders;
property result
result?: T;
property substatus
substatus?: number;
interface RetryOptions
interface RetryOptions {}
Represents the Retry policy assocated with throttled requests in the Azure Cosmos DB database service.
property fixedRetryIntervalInMilliseconds
fixedRetryIntervalInMilliseconds: number;
Fixed retry interval in milliseconds to wait between each retry ignoring the retryAfter returned as part of the response.
property maxRetryAttemptCount
maxRetryAttemptCount: number;
Max number of retries to be performed for a request. Default value 9.
property maxWaitTimeInSeconds
maxWaitTimeInSeconds: number;
Max wait time in seconds to wait for a request while the retries are happening. Default value 30 seconds.
interface SharedOptions
interface SharedOptions {}
Options that can be specified for a requested issued to the Azure Cosmos DB servers.=
property abortSignal
abortSignal?: AbortSignal;
abortSignal to pass to all underlying network requests created by this method call. See https://developer.mozilla.org/en-US/docs/Web/API/AbortController
Example 1
Cancel a read request
const controller = new AbortController()const {result: item} = await items.query('SELECT * from c', { abortSignal: controller.signal});controller.abort()
property bypassIntegratedCache
bypassIntegratedCache?: boolean;
Sets if integrated cache should be bypassed or enabled for the request in Azure CosmosDB service.
Default value is false. By default integrated cache is enabled
property initialHeaders
initialHeaders?: CosmosHeaders;
(Advanced use case) Initial headers to start with when sending requests to Cosmos
property maxIntegratedCacheStalenessInMs
maxIntegratedCacheStalenessInMs?: number;
Sets the staleness value associated with the request in the Azure CosmosDB service. For requests where the com.azure.cosmos.ConsistencyLevel is com.azure.cosmos.ConsistencyLevel#EVENTUAL or com.azure.cosmos.ConsistencyLevel#SESSION, responses from the integrated cache are guaranteed to be no staler than value indicated by this maxIntegratedCacheStaleness. When the consistency level is not set, this property is ignored.
Default value is null
Cache Staleness is supported in milliseconds granularity. Anything smaller than milliseconds will be ignored.
property priorityLevel
priorityLevel?: PriorityLevel;
Priority Level (Low/High) for each request. Low priority requests are always throttled before any high priority requests.
Default value is null. By default all requests are of High priority
property sessionToken
sessionToken?: string;
Enables/disables getting document container quota related stats for document container read requests.
interface SpatialIndex
interface SpatialIndex {}
property boundingBox
boundingBox: { xmin: number; ymin: number; xmax: number; ymax: number;};
property path
path: string;
property types
types: SpatialType[];
interface SqlParameter
interface SqlParameter {}
Represents a parameter in a Parameterized SQL query, specified in SqlQuerySpec
interface SqlQuerySpec
interface SqlQuerySpec {}
Represents a SQL query in the Azure Cosmos DB service.
Queries with inputs should be parameterized to protect against SQL injection.
Example 1
Parameterized SQL Query
const query: SqlQuerySpec = {query: "SELECT * FROM Families f where f.lastName = @lastName",parameters: [{name: "@lastName", value: "Wakefield"}]};
property parameters
parameters?: SqlParameter[];
The parameters you provide in the query
property query
query: string;
The text of the SQL query
interface StatusCodesType
interface StatusCodesType {}
property Accepted
Accepted: 202;
property BadRequest
BadRequest: 400;
property Conflict
Conflict: 409;
property Created
Created: 201;
property ENOTFOUND
ENOTFOUND: 'ENOTFOUND';
property Forbidden
Forbidden: 403;
property Gone
Gone: 410;
property InternalServerError
InternalServerError: 500;
property MethodNotAllowed
MethodNotAllowed: 405;
property NoContent
NoContent: 204;
property NotFound
NotFound: 404;
property NotModified
NotModified: 304;
property Ok
Ok: 200;
property OperationCancelled
OperationCancelled: 1201;
property OperationPaused
OperationPaused: 1200;
property PreconditionFailed
PreconditionFailed: 412;
property RequestEntityTooLarge
RequestEntityTooLarge: 413;
property RequestTimeout
RequestTimeout: 408;
property RetryWith
RetryWith: 449;
property ServiceUnavailable
ServiceUnavailable: 503;
property TooManyRequests
TooManyRequests: 429;
property Unauthorized
Unauthorized: 401;
interface StoredProcedureDefinition
interface StoredProcedureDefinition {}
property body
body?: string | ((...inputs: any[]) => void);
The body of the StoredProcedure. This is a JavaScript function.
property id
id?: string;
The id of the StoredProcedure.
interface TriggerDefinition
interface TriggerDefinition {}
property body
body: (() => void) | string;
The body of the trigger, it can also be passed as a stringifed function
property id
id?: string;
The id of the trigger.
property triggerOperation
triggerOperation: TriggerOperation;
The trigger operation, should be one of the values of TriggerOperation.
property triggerType
triggerType: TriggerType;
The type of the trigger, should be one of the values of TriggerType.
interface UniqueKey
interface UniqueKey {}
Interface for a single unique key passed as part of UniqueKeyPolicy
property paths
paths: string[];
interface UniqueKeyPolicy
interface UniqueKeyPolicy {}
Interface for setting unique keys on container creation
property uniqueKeys
uniqueKeys: UniqueKey[];
interface UpsertOperationInput
interface UpsertOperationInput {}
property ifMatch
ifMatch?: string;
property ifNoneMatch
ifNoneMatch?: string;
property operationType
operationType: typeof BulkOperationType.Upsert;
property partitionKey
partitionKey?: PartitionKey;
property resourceBody
resourceBody: JSONObject;
interface UserDefinedFunctionDefinition
interface UserDefinedFunctionDefinition {}
property body
body?: string | (() => void);
The body of the user defined function, it can also be passed as a stringifed function
property id
id?: string;
The id of the UserDefinedFunction
interface UserDefinition
interface UserDefinition {}
property id
id?: string;
The id of the user.
interface VectorEmbedding
interface VectorEmbedding {}
Represents a vector embedding. A vector embedding is used to define a vector field in the documents.
property dataType
dataType: VectorEmbeddingDataType;
The data type of the vector.
property dimensions
dimensions: number;
The number of dimensions in the vector.
property distanceFunction
distanceFunction: VectorEmbeddingDistanceFunction;
The distance function to use for distance calculation in between vectors.
property path
path: string;
The path to the vector field in the document.
interface VectorEmbeddingPolicy
interface VectorEmbeddingPolicy {}
Represents the policy configuration for vector embeddings in the Azure Cosmos DB service.
property vectorEmbeddings
vectorEmbeddings: VectorEmbedding[];
The vector embeddings to be configured.
interface VectorIndex
interface VectorIndex {}
Represents a vector index in the Azure Cosmos DB service. A vector index is used to index vector fields in the documents.
property indexingSearchListSize
indexingSearchListSize?: number;
The size of the candidate list of approximate neighbors stored while building the diskANN index as part of the optimization processes. This is an optional parameter and applies to index type DiskANN only. The allowed range is between 25 and 500.
property path
path: string;
The path to the vector field in the document. for example, path: "/path/to/vector".
property quantizationByteSize
quantizationByteSize?: number;
The number of bytes used in product quantization of the vectors. This is an optional parameter and applies to index types DiskANN and quantizedFlat. The allowed range for this parameter is between 1 and min(Dimensions, 512).
property type
type: VectorIndexType;
The index type of the vector. Currently, flat, diskANN, and quantizedFlat are supported.
property vectorIndexShardKey
vectorIndexShardKey?: string[];
The list of string containing the shard keys used for partitioning the vector indexes. This is an optional parameter and applies to index types DiskANN and quantizedFlat.
Enums
enum ChangeFeedMode
enum ChangeFeedMode { LatestVersion = 'Incremental Feed', AllVersionsAndDeletes = 'Full-Fidelity Feed',}
member AllVersionsAndDeletes
AllVersionsAndDeletes = 'Full-Fidelity Feed'
member LatestVersion
LatestVersion = 'Incremental Feed'
enum ConflictResolutionMode
enum ConflictResolutionMode { Custom = 'Custom', LastWriterWins = 'LastWriterWins',}
member Custom
Custom = 'Custom'
member LastWriterWins
LastWriterWins = 'LastWriterWins'
enum ConnectionMode
enum ConnectionMode { Gateway = 0,}
Determines the connection behavior of the CosmosClient. Note, we currently only support Gateway Mode.
member Gateway
Gateway = 0
Gateway mode talks to an intermediate gateway which handles the direct communication with your individual partitions.
enum ConsistencyLevel
enum ConsistencyLevel { Strong = 'Strong', BoundedStaleness = 'BoundedStaleness', Session = 'Session', Eventual = 'Eventual', ConsistentPrefix = 'ConsistentPrefix',}
Represents the consistency levels supported for Azure Cosmos DB client operations. 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.
member BoundedStaleness
BoundedStaleness = 'BoundedStaleness'
Bounded Staleness guarantees that reads are not too out-of-date. This can be configured based on number of operations (MaxStalenessPrefix) or time (MaxStalenessIntervalInSeconds).
member ConsistentPrefix
ConsistentPrefix = 'ConsistentPrefix'
ConsistentPrefix Consistency guarantees that reads will return some prefix of all writes with no gaps. All writes will be eventually be available for reads.
member Eventual
Eventual = 'Eventual'
Eventual Consistency guarantees that reads will return a subset of writes. All writes will be eventually be available for reads.
member Session
Session = 'Session'
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.
member Strong
Strong = 'Strong'
Strong Consistency guarantees that read operations always return the value that was last written.
enum CosmosDbDiagnosticLevel
enum CosmosDbDiagnosticLevel { info = 'info', debug = 'debug', debugUnsafe = 'debug-unsafe',}
Cosmos DB Diagnostic Level
enum DataType
enum DataType { Number = 'Number', String = 'String', Point = 'Point', LineString = 'LineString', Polygon = 'Polygon', MultiPolygon = 'MultiPolygon',}
Defines a target data type of an index path specification in the Azure Cosmos DB service.
member LineString
LineString = 'LineString'
Represents a line string data type.
member MultiPolygon
MultiPolygon = 'MultiPolygon'
Represents a multi-polygon data type.
member Number
Number = 'Number'
Represents a numeric data type.
member Point
Point = 'Point'
Represents a point data type.
member Polygon
Polygon = 'Polygon'
Represents a polygon data type.
member String
String = 'String'
Represents a string data type.
enum DiagnosticNodeType
enum DiagnosticNodeType { CLIENT_REQUEST_NODE = 'CLIENT_REQUEST_NODE', METADATA_REQUEST_NODE = 'METADATA_REQUEST_NODE', HTTP_REQUEST = 'HTTP_REQUEST', BATCH_REQUEST = 'BATCH_REQUEST', PARALLEL_QUERY_NODE = 'PARALLEL_QUERY_NODE', DEFAULT_QUERY_NODE = 'DEFAULT_QUERY_NODE', QUERY_REPAIR_NODE = 'QUERY_REPAIR_NODE', BACKGROUND_REFRESH_THREAD = 'BACKGROUND_REFRESH_THREAD', REQUEST_ATTEMPTS = 'REQUEST_ATTEMPTS',}
member BACKGROUND_REFRESH_THREAD
BACKGROUND_REFRESH_THREAD = 'BACKGROUND_REFRESH_THREAD'
member BATCH_REQUEST
BATCH_REQUEST = 'BATCH_REQUEST'
member CLIENT_REQUEST_NODE
CLIENT_REQUEST_NODE = 'CLIENT_REQUEST_NODE'
member DEFAULT_QUERY_NODE
DEFAULT_QUERY_NODE = 'DEFAULT_QUERY_NODE'
member HTTP_REQUEST
HTTP_REQUEST = 'HTTP_REQUEST'
member METADATA_REQUEST_NODE
METADATA_REQUEST_NODE = 'METADATA_REQUEST_NODE'
member PARALLEL_QUERY_NODE
PARALLEL_QUERY_NODE = 'PARALLEL_QUERY_NODE'
member QUERY_REPAIR_NODE
QUERY_REPAIR_NODE = 'QUERY_REPAIR_NODE'
member REQUEST_ATTEMPTS
REQUEST_ATTEMPTS = 'REQUEST_ATTEMPTS'
enum GeospatialType
enum GeospatialType { Geography = 'Geography', Geometry = 'Geometry',}
enum HTTPMethod
enum HTTPMethod { get = 'GET', patch = 'PATCH', post = 'POST', put = 'PUT', delete = 'DELETE',}
enum IndexingMode
enum IndexingMode { consistent = 'consistent', lazy = 'lazy', none = 'none',}
Specifies the supported indexing modes.
member consistent
consistent = 'consistent'
Index is updated synchronously with a create or update operation.
With consistent indexing, query behavior is the same as the default consistency level for the container. The index is always kept up to date with the data.
member lazy
lazy = 'lazy'
Index is updated asynchronously with respect to a create or update operation.
With lazy indexing, queries are eventually consistent. The index is updated when the container is idle.
member none
none = 'none'
No Index is provided.
enum IndexKind
enum IndexKind { Range = 'Range', Spatial = 'Spatial',}
Specifies the supported Index types.
enum MetadataLookUpType
enum MetadataLookUpType { PartitionKeyRangeLookUp = 'PARTITION_KEY_RANGE_LOOK_UP', DatabaseAccountLookUp = 'DATABASE_ACCOUNT_LOOK_UP', QueryPlanLookUp = 'QUERY_PLAN_LOOK_UP', DatabaseLookUp = 'DATABASE_LOOK_UP', ContainerLookUp = 'CONTAINER_LOOK_UP',}
This is enum for Type of Metadata lookups possible.
member ContainerLookUp
ContainerLookUp = 'CONTAINER_LOOK_UP'
member DatabaseAccountLookUp
DatabaseAccountLookUp = 'DATABASE_ACCOUNT_LOOK_UP'
member DatabaseLookUp
DatabaseLookUp = 'DATABASE_LOOK_UP'
member PartitionKeyRangeLookUp
PartitionKeyRangeLookUp = 'PARTITION_KEY_RANGE_LOOK_UP'
member QueryPlanLookUp
QueryPlanLookUp = 'QUERY_PLAN_LOOK_UP'
enum OperationType
enum OperationType { Create = 'create', Replace = 'replace', Upsert = 'upsert', Delete = 'delete', Read = 'read', Query = 'query', Execute = 'execute', Batch = 'batch', Patch = 'patch',}
enum PartitionKeyDefinitionVersion
enum PartitionKeyDefinitionVersion { V1 = 1, V2 = 2,}
PartitionKey Definition Version
enum PartitionKeyKind
enum PartitionKeyKind { Hash = 'Hash', MultiHash = 'MultiHash',}
Type of PartitionKey i.e. Hash, MultiHash
enum PermissionMode
enum PermissionMode { None = 'none', Read = 'read', All = 'all',}
Enum for permission mode values.
enum PluginOn
enum PluginOn { request = 'request', operation = 'operation',}
Used to specify which type of events to execute this plug in on.
enum PriorityLevel
enum PriorityLevel { High = 'High', Low = 'Low',}
Represents Priority Level associated with each Azure Cosmos DB client requests. The Low priority requests are always throttled before any High priority requests.
By default all requests are considered as High priority requests.
See https://aka.ms/CosmosDB/PriorityBasedExecution for more detailed documentation on Priority based throttling.
enum ResourceType
enum ResourceType { none = '', database = 'dbs', offer = 'offers', user = 'users', permission = 'permissions', container = 'colls', conflicts = 'conflicts', sproc = 'sprocs', udf = 'udfs', trigger = 'triggers', item = 'docs', pkranges = 'pkranges', partitionkey = 'partitionKey',}
member conflicts
conflicts = 'conflicts'
member container
container = 'colls'
member database
database = 'dbs'
member item
item = 'docs'
member none
none = ''
member offer
offer = 'offers'
member partitionkey
partitionkey = 'partitionKey'
member permission
permission = 'permissions'
member pkranges
pkranges = 'pkranges'
member sproc
sproc = 'sprocs'
member trigger
trigger = 'triggers'
member udf
udf = 'udfs'
member user
user = 'users'
enum SasTokenPermissionKind
enum SasTokenPermissionKind { ContainerCreateItems = 1, ContainerReplaceItems = 2, ContainerUpsertItems = 4, ContainerDeleteItems = 128, ContainerExecuteQueries = 1, ContainerReadFeeds = 2, ContainerCreateStoreProcedure = 16, ContainerReadStoreProcedure = 4, ContainerReplaceStoreProcedure = 32, ContainerDeleteStoreProcedure = 64, ContainerCreateTriggers = 256, ContainerReadTriggers = 16, ContainerReplaceTriggers = 512, ContainerDeleteTriggers = 1024, ContainerCreateUserDefinedFunctions = 2048, ContainerReadUserDefinedFunctions = 8, ContainerReplaceUserDefinedFunctions = 4096, ContainerDeleteUserDefinedFunctions = 8192, ContainerExecuteStoredProcedure = 128, ContainerReadConflicts = 32, ContainerDeleteConflicts = 16384, ContainerReadAny = 64, ContainerFullAccess = 4294967295, ItemReadAny = 65536, ItemFullAccess = 65, ItemRead = 64, ItemReplace = 65536, ItemUpsert = 131072, ItemDelete = 262144, StoreProcedureRead = 128, StoreProcedureReplace = 1048576, StoreProcedureDelete = 2097152, StoreProcedureExecute = 4194304, UserDefinedFuntionRead = 256, UserDefinedFuntionReplace = 8388608, UserDefinedFuntionDelete = 16777216, TriggerRead = 512, TriggerReplace = 33554432, TriggerDelete = 67108864,}
member ContainerCreateItems
ContainerCreateItems = 1
member ContainerCreateStoreProcedure
ContainerCreateStoreProcedure = 16
member ContainerCreateTriggers
ContainerCreateTriggers = 256
member ContainerCreateUserDefinedFunctions
ContainerCreateUserDefinedFunctions = 2048
member ContainerDeleteConflicts
ContainerDeleteConflicts = 16384
member ContainerDeleteItems
ContainerDeleteItems = 128
member ContainerDeleteStoreProcedure
ContainerDeleteStoreProcedure = 64
member ContainerDeleteTriggers
ContainerDeleteTriggers = 1024
member ContainerDeleteUserDefinedFunctions
ContainerDeleteUserDefinedFunctions = 8192
member ContainerExecuteQueries
ContainerExecuteQueries = 1
member ContainerExecuteStoredProcedure
ContainerExecuteStoredProcedure = 128
member ContainerFullAccess
ContainerFullAccess = 4294967295
member ContainerReadAny
ContainerReadAny = 64
member ContainerReadConflicts
ContainerReadConflicts = 32
member ContainerReadFeeds
ContainerReadFeeds = 2
member ContainerReadStoreProcedure
ContainerReadStoreProcedure = 4
member ContainerReadTriggers
ContainerReadTriggers = 16
member ContainerReadUserDefinedFunctions
ContainerReadUserDefinedFunctions = 8
member ContainerReplaceItems
ContainerReplaceItems = 2
member ContainerReplaceStoreProcedure
ContainerReplaceStoreProcedure = 32
member ContainerReplaceTriggers
ContainerReplaceTriggers = 512
member ContainerReplaceUserDefinedFunctions
ContainerReplaceUserDefinedFunctions = 4096
member ContainerUpsertItems
ContainerUpsertItems = 4
member ItemDelete
ItemDelete = 262144
member ItemFullAccess
ItemFullAccess = 65
member ItemRead
ItemRead = 64
member ItemReadAny
ItemReadAny = 65536
member ItemReplace
ItemReplace = 65536
member ItemUpsert
ItemUpsert = 131072
member StoreProcedureDelete
StoreProcedureDelete = 2097152
member StoreProcedureExecute
StoreProcedureExecute = 4194304
member StoreProcedureRead
StoreProcedureRead = 128
member StoreProcedureReplace
StoreProcedureReplace = 1048576
member TriggerDelete
TriggerDelete = 67108864
member TriggerRead
TriggerRead = 512
member TriggerReplace
TriggerReplace = 33554432
member UserDefinedFuntionDelete
UserDefinedFuntionDelete = 16777216
member UserDefinedFuntionRead
UserDefinedFuntionRead = 256
member UserDefinedFuntionReplace
UserDefinedFuntionReplace = 8388608
enum SpatialType
enum SpatialType { LineString = 'LineString', MultiPolygon = 'MultiPolygon', Point = 'Point', Polygon = 'Polygon',}
member LineString
LineString = 'LineString'
member MultiPolygon
MultiPolygon = 'MultiPolygon'
member Point
Point = 'Point'
member Polygon
Polygon = 'Polygon'
enum TriggerOperation
enum TriggerOperation { All = 'all', Create = 'create', Update = 'update', Delete = 'delete', Replace = 'replace',}
Enum for trigger operation values. specifies the operations on which a trigger should be executed.
enum TriggerType
enum TriggerType { Pre = 'pre', Post = 'post',}
Enum for trigger type values. Specifies the type of the trigger.
enum UserDefinedFunctionType
enum UserDefinedFunctionType { Javascript = 'Javascript',}
Enum for udf type values. Specifies the types of user defined functions.
member Javascript
Javascript = 'Javascript'
The User Defined Function is written in JavaScript. This is currently the only option.
enum VectorEmbeddingDataType
enum VectorEmbeddingDataType { Float32 = 'float32', UInt8 = 'uint8', Int8 = 'int8',}
Represents the data type of the vector.
enum VectorEmbeddingDistanceFunction
enum VectorEmbeddingDistanceFunction { Euclidean = 'euclidean', Cosine = 'cosine', DotProduct = 'dotproduct',}
Represents the distance function to use for distance calculation in between vectors.
member Cosine
Cosine = 'cosine'
Represents cosine distance function.
member DotProduct
DotProduct = 'dotproduct'
Represents dot product distance function.
member Euclidean
Euclidean = 'euclidean'
Represents euclidean distance function.
enum VectorIndexType
enum VectorIndexType { Flat = 'flat', DiskANN = 'diskANN', QuantizedFlat = 'quantizedFlat',}
Represents the index type of the vector.
member DiskANN
DiskANN = 'diskANN'
Represents diskANN index type.
member Flat
Flat = 'flat'
Represents flat index type.
member QuantizedFlat
QuantizedFlat = 'quantizedFlat'
Represents quantizedFlat index type.
Type Aliases
type AggregateType
type AggregateType = | 'Average' | 'Count' | 'Max' | 'Min' | 'Sum' | 'MakeSet' | 'MakeList';
type BulkOperationResponse
type BulkOperationResponse = OperationResponse[] & { diagnostics: CosmosDiagnostics;};
type BulkPatchOperation
type BulkPatchOperation = OperationBase & { operationType: typeof BulkOperationType.Patch; id: string;};
type ClientConfigDiagnostic
type ClientConfigDiagnostic = { /** * End point configured during client initialization. */ endpoint: string; /** * True if `resourceTokens` was supplied during client initialization. */ resourceTokensConfigured: boolean; /** * True if `tokenProvider` was supplied during client initialization. */ tokenProviderConfigured: boolean; /** * True if `aadCredentials` was supplied during client initialization. */ aadCredentialsConfigured: boolean; /** * True if `connectionPolicy` was supplied during client initialization. */ connectionPolicyConfigured: boolean; /** * `consistencyLevel` supplied during client initialization. */ consistencyLevel?: keyof typeof ConsistencyLevel; /** * `defaultHeaders` supplied during client initialization. */ defaultHeaders?: { [key: string]: any; }; /** * True if `connectionPolicy` were supplied during client initialization. */ agentConfigured: boolean; /** * `userAgentSuffix` supplied during client initialization. */ userAgentSuffix: string; /** * `diagnosticLevel` supplied during client initialization. */ diagnosticLevel?: CosmosDbDiagnosticLevel; /** * True if `plugins` were supplied during client initialization. */ pluginsConfigured: boolean; /** * SDK version */ sDKVersion: string;};
This type holds information related to initialization of
CosmosClient
type ClientSideRequestStatistics
type ClientSideRequestStatistics = { /** * This is the UTC timestamp for start of client operation. */ requestStartTimeUTCInMs: number; /** * This is the duration in milli seconds taken by client operation. */ requestDurationInMs: number; /** * This is the list of Location Endpoints contacted during the client operation. */ locationEndpointsContacted: string[]; /** * This field captures diagnostic information for retries happened during client operation. */ retryDiagnostics: RetryDiagnostics; /** * This field captures diagnostic information for meta data lookups happened during client operation. */ metadataDiagnostics: MetadataLookUpDiagnostics; /** * These are the statistics for main point look operation. */ gatewayStatistics: GatewayStatistics[]; /** * This is the cumulated Request Payload Length n bytes, this includes metadata calls along with the main operation. */ totalRequestPayloadLengthInBytes: number; /** * This is the cumulated Response Payload Length n bytes, this includes metadata calls along with the main operation. */ totalResponsePayloadLengthInBytes: number;};
This is a collection type for all client side diagnostic information.
type CreateOperation
type CreateOperation = OperationWithItem & { operationType: typeof BulkOperationType.Create;};
type DeleteOperation
type DeleteOperation = OperationBase & { operationType: typeof BulkOperationType.Delete; id: string;};
type DiagnosticDataValue
type DiagnosticDataValue = { selectedLocation: string; activityId: string; requestAttempNumber: number; requestPayloadLengthInBytes: number; responsePayloadLengthInBytes: number; responseStatus: number; readFromCache: boolean; operationType: OperationType; metadatOperationType: MetadataLookUpType; resourceType: ResourceType; failedAttempty: boolean; successfulRetryPolicy: string; partitionKeyRangeId: string; stateful: boolean; queryRecordsRead: number; queryMethodIdentifier: string; log: string[]; failure: boolean; startTimeUTCInMs: number; durationInMs: number; requestData: Partial<{ requestPayloadLengthInBytes: number; responsePayloadLengthInBytes: number; operationType: OperationType; resourceType: ResourceType; headers: CosmosHeaders_2; requestBody: any; responseBody: any; url: string; }>;};
type ExistingKeyOperation
type ExistingKeyOperation = { op: keyof typeof PatchOperationType; value: any; path: string;};
type GatewayStatistics
type GatewayStatistics = { /** * This is the activityId for request, made to server for fetching the requested resource. (As opposed to other potential meta data requests) */ activityId?: string; correlatedActivityId?: string; startTimeUTCInMs: number; durationInMs: number; operationType?: OperationType; resourceType?: ResourceType; statusCode?: number; subStatusCode?: number; requestCharge?: number; requestPayloadLengthInBytes: number; responsePayloadLengthInBytes: number;};
type GroupByExpressions
type GroupByExpressions = string[];
type JSONValue
type JSONValue = boolean | number | string | null | JSONArray | JSONObject;
type MetadataLookUpDiagnostics
type MetadataLookUpDiagnostics = { metadataLookups: MetadataLookUpDiagnostic[];};
This type contains diagnostic information regarding all metadata request to server during an CosmosDB client operation.
type Next
type Next<T> = (context: RequestContext) => Promise<Response_2<T>>;
Next is a function which takes in requestContext returns a promise. You must await/then that promise which will contain the response from further plugins, allowing you to log those results or handle errors.
type NonePartitionKeyType
type NonePartitionKeyType = { [K in any]: never;};
The returned object represents a partition key value that allows creating and accessing items without a value for partition key
type NullPartitionKeyType
type NullPartitionKeyType = null;
The returned object represents a partition key value that allows creating and accessing items with a null value for the partition key.
type Operation
type Operation = | CreateOperation | UpsertOperation | ReadOperation | DeleteOperation | ReplaceOperation | BulkPatchOperation;
type OperationInput
type OperationInput = | CreateOperationInput | UpsertOperationInput | ReadOperationInput | DeleteOperationInput | ReplaceOperationInput | PatchOperationInput;
type OperationWithItem
type OperationWithItem = OperationBase & { resourceBody: JSONObject;};
type PartitionKey
type PartitionKey = PrimitivePartitionKeyValue | PrimitivePartitionKeyValue[];
PartitionKey of a container.
Remarks
- PartitionKeyDefinition is no longer part of PartitionKey. So please use PartitionKeyDefinition type directly where appropriate.
type PatchOperation
type PatchOperation = ExistingKeyOperation | RemoveOperation;
type PatchRequestBody
type PatchRequestBody = | { operations: PatchOperation[]; condition?: string; } | PatchOperation[];
type Plugin
type Plugin<T> = ( context: RequestContext, diagnosticNode: DiagnosticNodeInternal, next: Next<T>) => Promise<Response_2<T>>;
Plugins allow you to customize the behavior of the SDk with additional logging, retry, or additional functionality.
A plugin is a function which returns a
Promise<Response<T>>
, and is passed a RequestContext and Next object.Next is a function which takes in requestContext returns a promise. You must await/then that promise which will contain the response from further plugins, allowing you to log those results or handle errors.
RequestContext is an object which controls what operation is happening, against which endpoint, and more. Modifying this and passing it along via next is how you modify future SDK behavior.
type PrimitivePartitionKeyValue
type PrimitivePartitionKeyValue = | string | number | boolean | NullPartitionKeyType | NonePartitionKeyType;
A primitive Partition Key value.
type ReadOperation
type ReadOperation = OperationBase & { operationType: typeof BulkOperationType.Read; id: string;};
type RemoveOperation
type RemoveOperation = { op: 'remove'; path: string;};
type ReplaceOperation
type ReplaceOperation = OperationWithItem & { operationType: typeof BulkOperationType.Replace; id: string;};
type RetryDiagnostics
type RetryDiagnostics = { failedAttempts: FailedRequestAttemptDiagnostic[];};
This type captures diagnostic information regarding retries attempt during an CosmosDB client operation.
type StatusCode
type StatusCode = number;
type SubStatusCode
type SubStatusCode = number;
type TokenProvider
type TokenProvider = (requestInfo: RequestInfo) => Promise<string>;
type UpsertOperation
type UpsertOperation = OperationWithItem & { operationType: typeof BulkOperationType.Upsert;};
Package Files (1)
Dependencies (10)
Dev Dependencies (25)
- @azure/dev-tool
- @azure/eslint-plugin-azure-sdk
- @azure/identity
- @azure/logger
- @sinonjs/fake-timers
- @types/chai
- @types/debug
- @types/mocha
- @types/node
- @types/priorityqueuejs
- @types/semaphore
- @types/sinon
- @types/sinonjs__fake-timers
- @types/underscore
- chai
- dotenv
- eslint
- execa
- mocha
- nock
- requirejs
- sinon
- source-map-support
- ts-node
- typescript
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@azure/cosmos
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@azure/cosmos)
- HTML<a href="https://www.jsdocs.io/package/@azure/cosmos"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 14471 ms. - Missing or incorrect documentation? Open an issue for this package.