@azure/cosmos
Version:
Microsoft Azure Cosmos DB Service Node.js SDK for NOSQL API
241 lines (240 loc) • 9.27 kB
JavaScript
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 Containers_exports = {};
__export(Containers_exports, {
Containers: () => Containers
});
module.exports = __toCommonJS(Containers_exports);
var import_common = require("../../common/index.js");
var import_partitionKeys = require("../../common/partitionKeys.js");
var import_queryExecutionContext = require("../../queryExecutionContext/index.js");
var import_queryIterator = require("../../queryIterator.js");
var import_Container = require("./Container.js");
var import_ContainerResponse = require("./ContainerResponse.js");
var import_offers = require("../../utils/offers.js");
var import_diagnostics = require("../../utils/diagnostics.js");
class Containers {
/**
* @hidden
* @param database - The parent {@link Database}.
*/
constructor(database, clientContext, encryptionManager) {
this.database = database;
this.clientContext = clientContext;
this.encryptionManager = encryptionManager;
}
query(query, options) {
const path = (0, import_common.getPathFromLink)(this.database.url, import_common.ResourceType.container);
const id = (0, import_common.getIdFromLink)(this.database.url);
return new import_queryIterator.QueryIterator(
this.clientContext,
query,
options,
(diagNode, innerOptions) => {
return this.clientContext.queryFeed({
path,
resourceType: import_common.ResourceType.container,
resourceId: id,
resultFn: (result) => result.DocumentCollections,
query,
options: innerOptions,
diagnosticNode: diagNode
});
}
);
}
/**
* Creates a container.
*
* A container is a named logical container for items.
*
* A database may contain zero or more named containers and each container consists of
* zero or more JSON items.
*
* Being schema-free, the items in a container do not need to share the same structure or fields.
*
*
* Since containers are application resources, they can be authorized using either the
* master key or resource keys.
*
* @param body - Represents the body of the container.
* @param options - Use to set options like response page size, continuation tokens, etc.
* @example
* ```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>",
* });
* ```
*/
async create(body, options = {}) {
return (0, import_diagnostics.withDiagnostics)(async (diagnosticNode) => {
return this.createInternal(diagnosticNode, body, options);
}, this.clientContext);
}
/**
* @hidden
*/
async createInternal(diagnosticNode, body, options = {}) {
const err = {};
if (!(0, import_common.isResourceValid)(body, err)) {
throw err;
}
const path = (0, import_common.getPathFromLink)(this.database.url, import_common.ResourceType.container);
const id = (0, import_common.getIdFromLink)(this.database.url);
(0, import_offers.validateOffer)(body);
if (body.maxThroughput) {
const autoscaleParams = {
maxThroughput: body.maxThroughput
};
if (body.autoUpgradePolicy) {
autoscaleParams.autoUpgradePolicy = body.autoUpgradePolicy;
}
const autoscaleHeader = JSON.stringify(autoscaleParams);
options.initialHeaders = Object.assign({}, options.initialHeaders, {
[import_common.Constants.HttpHeaders.AutoscaleSettings]: autoscaleHeader
});
delete body.maxThroughput;
delete body.autoUpgradePolicy;
}
if (body.throughput) {
options.initialHeaders = Object.assign({}, options.initialHeaders, {
[import_common.Constants.HttpHeaders.OfferThroughput]: body.throughput
});
delete body.throughput;
}
if (typeof body.partitionKey === "string") {
if (!body.partitionKey.startsWith("/")) {
throw new Error("Partition key must start with '/'");
}
body.partitionKey = {
paths: [body.partitionKey]
};
}
if (!body.partitionKey || !body.partitionKey.paths) {
body.partitionKey = {
paths: [import_partitionKeys.DEFAULT_PARTITION_KEY_PATH]
};
}
if (this.clientContext.enableEncryption && body.clientEncryptionPolicy) {
body.clientEncryptionPolicy.policyFormatVersion = body.clientEncryptionPolicy.policyFormatVersion ?? 1;
(0, import_common.validateClientEncryptionPolicy)(body.clientEncryptionPolicy, body.partitionKey);
}
const response = await this.clientContext.create({
body,
path,
resourceType: import_common.ResourceType.container,
resourceId: id,
diagnosticNode,
options
});
const ref = new import_Container.Container(
this.database,
response.result.id,
this.clientContext,
this.encryptionManager,
response.result._rid
);
this.clientContext.partitionKeyDefinitionCache[ref.url] = response.result.partitionKey;
return new import_ContainerResponse.ContainerResponse(
response.result,
response.headers,
response.code,
ref,
(0, import_diagnostics.getEmptyCosmosDiagnostics)()
);
}
/**
* Checks if a Container exists, and, if it doesn't, creates it.
* This will make a read operation based on the id in the `body`, then if it is not found, a create operation.
* You should confirm that the output matches the body you passed in for non-default properties (i.e. indexing policy/etc.)
*
* A container is a named logical container for items.
*
* A database may contain zero or more named containers and each container consists of
* zero or more JSON items.
*
* Being schema-free, the items in a container do not need to share the same structure or fields.
*
*
* Since containers are application resources, they can be authorized using either the
* master key or resource keys.
*
* @param body - Represents the body of the container.
* @param options - Use to set options like response page size, continuation tokens, etc.
* @example
* ```ts snippet:ReadmeSampleCreateContainer
* 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 { database } = await client.databases.createIfNotExists({ id: "Test Database" });
* const { container } = await database.containers.createIfNotExists({ id: "Test Container" });
* ```
*/
async createIfNotExists(body, options) {
if (!body || body.id === null || body.id === void 0) {
throw new Error("body parameter must be an object with an id property");
}
return (0, import_diagnostics.withDiagnostics)(async (diagnosticNode) => {
try {
const readResponse = await this.database.container(body.id).readInternal(diagnosticNode, options);
return readResponse;
} catch (err) {
if (err.code === import_common.StatusCodes.NotFound) {
const createResponse = await this.createInternal(diagnosticNode, body, options);
(0, import_queryExecutionContext.mergeHeaders)(createResponse.headers, err.headers);
return createResponse;
} else {
throw err;
}
}
}, this.clientContext);
}
/**
* Read all containers.
* @param options - Use to set options like response page size, continuation tokens, etc.
* @returns {@link QueryIterator} Allows you to return all containers in an array or iterate over them one at a time.
* @example Read all containers to array.
* ```ts snippet:ContainersReadAllContainers
* 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 { resources: containerList } = await client
* .database("<db id>")
* .containers.readAll()
* .fetchAll();
* ```
*/
readAll(options) {
return this.query(void 0, options);
}
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Containers
});