UNPKG

@azure/cosmos

Version:
307 lines (306 loc) • 13.9 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var CosmosClient_exports = {}; __export(CosmosClient_exports, { CosmosClient: () => CosmosClient }); module.exports = __toCommonJS(CosmosClient_exports); var import_Database = require("./client/Database/index.js"); var import_Offer = require("./client/Offer/index.js"); var import_ClientContext = require("./ClientContext.js"); var import_common = require("./common/index.js"); var import_constants = require("./common/constants.js"); var import_platform = require("./common/platform.js"); var import_diagnostics = require("./diagnostics/index.js"); var import_DiagnosticNodeInternal = require("./diagnostics/DiagnosticNodeInternal.js"); var import_documents = require("./documents/index.js"); var import_EncryptionManager = require("./encryption/EncryptionManager.js"); var import_globalEndpointManager = require("./globalEndpointManager.js"); var import_request = require("./request/index.js"); var import_checkURL = require("./utils/checkURL.js"); var import_diagnostics2 = require("./utils/diagnostics.js"); var import_globalPartitionEndpointManager = require("./globalPartitionEndpointManager.js"); class CosmosClient { /** * Used for creating new databases, or querying/reading all databases. * * Use `.database(id)` to read, replace, or delete a specific, existing database by id. * * @example Create a new database * ```ts snippet:CosmosClientDatabases * import { CosmosClient } from "@azure/cosmos"; * * const endpoint = "https://your-account.documents.azure.com"; * const key = "<database account masterkey>"; * const client = new CosmosClient({ endpoint, key }); * const { resource: databaseDefinition, database } = await client.databases.create({ * id: "<name here>", * }); * ``` */ databases; /** * Used for querying & reading all offers. * * Use `.offer(id)` to read, or replace existing offers. */ offers; clientContext; endpointRefresher; /** * @internal */ encryptionManager; /** @internal */ globalPartitionEndpointManager; constructor(optionsOrConnectionString) { if (typeof optionsOrConnectionString === "string") { optionsOrConnectionString = (0, import_common.parseConnectionString)(optionsOrConnectionString); } else if (optionsOrConnectionString.connectionString) { const { endpoint: endpoint2, key } = (0, import_common.parseConnectionString)(optionsOrConnectionString.connectionString); optionsOrConnectionString.endpoint = endpoint2; optionsOrConnectionString.key = key; } const endpoint = (0, import_checkURL.checkURL)(optionsOrConnectionString.endpoint); if (!endpoint) { throw new Error("Invalid endpoint specified"); } if (optionsOrConnectionString.clientEncryptionOptions) { if (!optionsOrConnectionString.clientEncryptionOptions.keyEncryptionKeyResolver) { throw new Error( "KeyEncryptionKeyResolver needs to be provided to enable client-side encryption." ); } if (optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds && optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds < 60) { throw new Error("EncryptionKeyTimeToLiveInSeconds needs to be >= 60 seconds."); } this.encryptionManager = new import_EncryptionManager.EncryptionManager( optionsOrConnectionString.clientEncryptionOptions.keyEncryptionKeyResolver, optionsOrConnectionString.clientEncryptionOptions.encryptionKeyTimeToLiveInSeconds ); } const clientConfig = this.initializeClientConfigDiagnostic(optionsOrConnectionString); optionsOrConnectionString.connectionPolicy = Object.assign( {}, import_documents.defaultConnectionPolicy, optionsOrConnectionString.connectionPolicy ); if (!optionsOrConnectionString.connectionPolicy.enableEndpointDiscovery) { optionsOrConnectionString.connectionPolicy.enablePartitionLevelFailover = false; optionsOrConnectionString.connectionPolicy.enablePartitionLevelCircuitBreaker = false; } optionsOrConnectionString.defaultHeaders = optionsOrConnectionString.defaultHeaders || {}; optionsOrConnectionString.defaultHeaders[import_constants.Constants.HttpHeaders.CacheControl] = "no-cache"; optionsOrConnectionString.defaultHeaders[import_constants.Constants.HttpHeaders.Version] = import_constants.Constants.CurrentVersion; if (optionsOrConnectionString.consistencyLevel !== void 0) { optionsOrConnectionString.defaultHeaders[import_constants.Constants.HttpHeaders.ConsistencyLevel] = optionsOrConnectionString.consistencyLevel; } if (optionsOrConnectionString.throughputBucket !== void 0) { optionsOrConnectionString.defaultHeaders[import_constants.Constants.HttpHeaders.ThroughputBucket] = optionsOrConnectionString.throughputBucket; } const userAgent = (0, import_platform.getUserAgent)(optionsOrConnectionString); optionsOrConnectionString.defaultHeaders[import_constants.Constants.HttpHeaders.UserAgent] = userAgent; optionsOrConnectionString.defaultHeaders[import_constants.Constants.HttpHeaders.CustomUserAgent] = userAgent; const globalEndpointManager = new import_globalEndpointManager.GlobalEndpointManager( optionsOrConnectionString, async (diagnosticNode, opts) => this.getDatabaseAccountInternal(diagnosticNode, opts) ); if (optionsOrConnectionString.connectionPolicy.enablePartitionLevelFailover || optionsOrConnectionString.connectionPolicy.enablePartitionLevelCircuitBreaker) { this.globalPartitionEndpointManager = new import_globalPartitionEndpointManager.GlobalPartitionEndpointManager( optionsOrConnectionString, globalEndpointManager ); globalEndpointManager.onEnablePartitionLevelFailoverConfigChanged = (isEnabled) => { this.globalPartitionEndpointManager?.changeCircuitBreakerFailbackLoop(isEnabled); }; } this.clientContext = new import_ClientContext.ClientContext( optionsOrConnectionString, globalEndpointManager, clientConfig, (0, import_diagnostics.determineDiagnosticLevel)( optionsOrConnectionString.diagnosticLevel, (0, import_diagnostics.getDiagnosticLevelFromEnvironment)() ), this.globalPartitionEndpointManager ); if (optionsOrConnectionString.connectionPolicy?.enableEndpointDiscovery && optionsOrConnectionString.connectionPolicy?.enableBackgroundEndpointRefreshing) { this.backgroundRefreshEndpointList( globalEndpointManager, optionsOrConnectionString.connectionPolicy.endpointRefreshRateInMs || import_documents.defaultConnectionPolicy.endpointRefreshRateInMs ); } this.databases = new import_Database.Databases(this, this.clientContext, this.encryptionManager); this.offers = new import_Offer.Offers(this, this.clientContext); } initializeClientConfigDiagnostic(optionsOrConnectionString) { return { endpoint: optionsOrConnectionString.endpoint, resourceTokensConfigured: optionsOrConnectionString.resourceTokens !== void 0, tokenProviderConfigured: optionsOrConnectionString.tokenProvider !== void 0, aadCredentialsConfigured: optionsOrConnectionString.aadCredentials !== void 0, connectionPolicyConfigured: optionsOrConnectionString.connectionPolicy !== void 0, consistencyLevel: optionsOrConnectionString.consistencyLevel, defaultHeaders: optionsOrConnectionString.defaultHeaders, agentConfigured: optionsOrConnectionString.agent !== void 0, userAgentSuffix: optionsOrConnectionString.userAgentSuffix, diagnosticLevel: optionsOrConnectionString.diagnosticLevel, pluginsConfigured: optionsOrConnectionString.plugins !== void 0, sDKVersion: import_constants.Constants.SDKVersion, aadScopeOverride: optionsOrConnectionString.aadScope !== void 0 }; } /** * Get information about the current {@link DatabaseAccount} (including which regions are supported, etc.) */ async getDatabaseAccount(options) { return (0, import_diagnostics2.withDiagnostics)(async (diagnosticNode) => { return this.getDatabaseAccountInternal(diagnosticNode, options); }, this.clientContext); } /** * @hidden */ async getDatabaseAccountInternal(diagnosticNode, options) { const response = await this.clientContext.getDatabaseAccount(diagnosticNode, options); return new import_request.ResourceResponse( response.result, response.headers, response.code, (0, import_diagnostics2.getEmptyCosmosDiagnostics)(), response.substatus ); } /** * 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. */ async getWriteEndpoint() { return (0, import_diagnostics2.withDiagnostics)(async (diagnosticNode) => { return this.clientContext.getWriteEndpoint(diagnosticNode); }, this.clientContext); } /** * 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. */ async getReadEndpoint() { return (0, import_diagnostics2.withDiagnostics)(async (diagnosticNode) => { return this.clientContext.getReadEndpoint(diagnosticNode); }, this.clientContext); } /** * Gets the known write endpoints. Useful for troubleshooting purposes. * * The urls may contain a region suffix (e.g. "-eastus") if we're using location specific endpoints. */ getWriteEndpoints() { return this.clientContext.getWriteEndpoints(); } /** * Gets the currently used read endpoint. Useful for troubleshooting purposes. * * The url may contain a region suffix (e.g. "-eastus") if we're using location specific endpoints. */ getReadEndpoints() { return this.clientContext.getReadEndpoints(); } /** * Used for reading, updating, or deleting a existing database by id or accessing containers belonging to that database. * * This does not make a network call. Use `.read` to get info about the database after getting the {@link Database} object. * * @param id - The id of the database. * @example Create a new container off of an existing database * ```ts snippet:CosmosClientDatabaseCreateContainer * import { CosmosClient } from "@azure/cosmos"; * * const endpoint = "https://your-account.documents.azure.com"; * const key = "<database account masterkey>"; * const client = new CosmosClient({ endpoint, key }); * const container = client.database("<database id>").containers.create({ * id: "<name here>", * }); * ``` * * @example Delete an existing database * ```ts snippet:CosmosClientDatabaseDelete * import { CosmosClient } from "@azure/cosmos"; * * const endpoint = "https://your-account.documents.azure.com"; * const key = "<database account masterkey>"; * const client = new CosmosClient({ endpoint, key }); * await client.database("<id here>").delete(); * ``` */ database(id) { return new import_Database.Database(this, id, this.clientContext, this.encryptionManager); } /** * Used for reading, or updating a existing offer by id. * @param id - The id of the offer. */ offer(id) { return new import_Offer.Offer(this, id, this.clientContext); } /** * Clears background endpoint refresher. Use client.dispose() when destroying the CosmosClient within another process. */ dispose() { clearTimeout(this.endpointRefresher); if (this.clientContext.enableEncryption) { clearTimeout(this.encryptionManager.encryptionKeyStoreProvider.cacheRefresher); clearTimeout(this.encryptionManager.protectedDataEncryptionKeyCache.cacheRefresher); } if (this.globalPartitionEndpointManager) { this.globalPartitionEndpointManager.dispose(); } } async backgroundRefreshEndpointList(globalEndpointManager, refreshRate) { this.endpointRefresher = setInterval(() => { try { return (0, import_diagnostics2.withDiagnostics)( async (diagnosticNode) => { return globalEndpointManager.refreshEndpointList(diagnosticNode); }, this.clientContext, import_DiagnosticNodeInternal.DiagnosticNodeType.BACKGROUND_REFRESH_THREAD ); } catch (e) { console.warn("Failed to refresh endpoints", e); } }, refreshRate); if (this.endpointRefresher.unref && typeof this.endpointRefresher.unref === "function") { this.endpointRefresher.unref(); } } /** * Update the host framework. If provided host framework will be used to generate the defualt SDK user agent. * @param hostFramework - A custom string. * @internal */ async updateHostFramework(hostFramework) { this.clientContext.refreshUserAgent(hostFramework); } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CosmosClient });