UNPKG

@azure/cosmos

Version:
513 lines (512 loc) • 20 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 Item_exports = {}; __export(Item_exports, { Item: () => Item }); module.exports = __toCommonJS(Item_exports); var import_common = require("../../common/index.js"); var import_documents = require("../../documents/index.js"); var import_request = require("../../request/index.js"); var import_patch = require("../../utils/patch.js"); var import_ItemResponse = require("./ItemResponse.js"); var import_diagnostics = require("../../utils/diagnostics.js"); var import_extractPartitionKey = require("../../extractPartitionKey.js"); var import_ClientUtils = require("../ClientUtils.js"); class Item { /** * @hidden * @param container - The parent {@link Container}. * @param id - The id of the given {@link Item}. * @param partitionKey - The primary key of the given {@link Item} (only for partitioned containers). */ constructor(container, id, clientContext, partitionKey) { this.container = container; this.id = id; this.clientContext = clientContext; this.partitionKey = partitionKey === void 0 ? void 0 : (0, import_documents.convertToInternalPartitionKey)(partitionKey); } partitionKey; /** * Returns a reference URL to the resource. Used for linking in Permissions. */ get url() { return (0, import_common.createDocumentUri)(this.container.database.id, this.container.id, this.id); } /** * 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. * * @param options - Additional options for the request * * @example Using custom type for response * ```ts snippet:ItemRead * 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" }); * * interface TodoItem { * title: string; * done: boolean; * id: string; * } * * const { resource: item } = await container.item("id", "<pkValue>").read<TodoItem>(); * ``` */ async read(options = {}) { return (0, import_diagnostics.withDiagnostics)(async (diagnosticNode) => { this.partitionKey = await (0, import_extractPartitionKey.setPartitionKeyIfUndefined)( diagnosticNode, this.container, this.partitionKey ); let url = this.url; let partitionKey = this.partitionKey; let response; try { if (this.clientContext.enableEncryption) { await this.container.checkAndInitializeEncryption(); options.containerRid = this.container._rid; let count = 0; diagnosticNode.beginEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsEncryptOperation ); const { partitionKeyList: encryptedPartitionKey, encryptedCount } = await this.container.encryptionProcessor.getEncryptedPartitionKeyValue( this.partitionKey ); partitionKey = encryptedPartitionKey; count += encryptedCount; if (await this.container.encryptionProcessor.isPathEncrypted("/id")) { url = await this.container.encryptionProcessor.getEncryptedUrl(this.url); count++; } diagnosticNode.endEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsEncryptOperation, count ); } const path = (0, import_common.getPathFromLink)(url); const id = (0, import_common.getIdFromLink)(url); const isPartitionLevelFailOverEnabled = this.clientContext.isPartitionLevelFailOverEnabled(); const partitionKeyRangeId = await (0, import_ClientUtils.computePartitionKeyRangeId)( diagnosticNode, partitionKey, this.clientContext.partitionKeyRangeCache, isPartitionLevelFailOverEnabled, this.container ); response = await this.clientContext.read({ path, resourceType: import_common.ResourceType.item, resourceId: id, options, partitionKey, diagnosticNode, partitionKeyRangeId }); } catch (error) { if (this.clientContext.enableEncryption) { await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(error); } if (error.code !== import_common.StatusCodes.NotFound) { throw error; } response = error; } if (this.clientContext.enableEncryption) { diagnosticNode.beginEncryptionDiagnostics(import_common.Constants.Encryption.DiagnosticsDecryptOperation); const { body, propertiesDecryptedCount } = await this.container.encryptionProcessor.decrypt( response.result ); diagnosticNode.endEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsDecryptOperation, propertiesDecryptedCount ); response.result = body; } return new import_ItemResponse.ItemResponse( response.result, response.headers, response.code, response.substatus, this, (0, import_diagnostics.getEmptyCosmosDiagnostics)() ); }, this.clientContext); } async replace(body, options = {}) { return (0, import_diagnostics.withDiagnostics)(async (diagnosticNode) => { this.partitionKey = await (0, import_extractPartitionKey.setPartitionKeyIfUndefined)( diagnosticNode, this.container, this.partitionKey ); let partitionKey = this.partitionKey; const err = {}; if (!(0, import_common.isItemResourceValid)(body, err)) { throw err; } let url = this.url; let response; try { if (this.clientContext.enableEncryption) { body = (0, import_common.copyObject)(body); options = options || {}; await this.container.checkAndInitializeEncryption(); options.containerRid = this.container._rid; let count = 0; diagnosticNode.beginEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsEncryptOperation ); const { body: encryptedBody, propertiesEncryptedCount } = await this.container.encryptionProcessor.encrypt(body); body = encryptedBody; count += propertiesEncryptedCount; const { partitionKeyList: encryptedPartitionKeyList, encryptedCount } = await this.container.encryptionProcessor.getEncryptedPartitionKeyValue( this.partitionKey ); partitionKey = encryptedPartitionKeyList; count += encryptedCount; if (await this.container.encryptionProcessor.isPathEncrypted("/id")) { url = await this.container.encryptionProcessor.getEncryptedUrl(this.url); count++; } diagnosticNode.endEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsEncryptOperation, count ); } const path = (0, import_common.getPathFromLink)(url); const id = (0, import_common.getIdFromLink)(url); const isPartitionLevelFailOverEnabled = this.clientContext.isPartitionLevelFailOverEnabled(); const partitionKeyRangeId = await (0, import_ClientUtils.computePartitionKeyRangeId)( diagnosticNode, partitionKey, this.clientContext.partitionKeyRangeCache, isPartitionLevelFailOverEnabled, this.container ); response = await this.clientContext.replace({ body, path, resourceType: import_common.ResourceType.item, resourceId: id, options, partitionKey, diagnosticNode, partitionKeyRangeId }); } catch (error) { if (this.clientContext.enableEncryption) { await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(error); } throw error; } if (this.clientContext.enableEncryption) { try { diagnosticNode.beginEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsDecryptOperation ); const { body: result, propertiesDecryptedCount } = await this.container.encryptionProcessor.decrypt(response.result); response.result = result; diagnosticNode.endEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsDecryptOperation, propertiesDecryptedCount ); } catch (error) { const decryptionError = new import_request.ErrorResponse( `Item replace operation was successful but response decryption failed: + ${error.message}` ); decryptionError.code = import_common.StatusCodes.ServiceUnavailable; throw decryptionError; } } return new import_ItemResponse.ItemResponse( response.result, response.headers, response.code, response.substatus, this, (0, import_diagnostics.getEmptyCosmosDiagnostics)() ); }, this.clientContext); } /** * 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. * * @param options - Additional options for the request * @example * ```ts snippet:ItemDelete * 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" }); * * interface TodoItem { * title: string; * done: boolean; * id: string; * } * * const { resource: item } = await container.item("id", "<pkValue>").read<TodoItem>(); * * await container.item("id").delete<TodoItem>(); * ``` */ async delete(options = {}) { return (0, import_diagnostics.withDiagnostics)(async (diagnosticNode) => { this.partitionKey = await (0, import_extractPartitionKey.setPartitionKeyIfUndefined)( diagnosticNode, this.container, this.partitionKey ); let partitionKey = this.partitionKey; let url = this.url; let response; try { if (this.clientContext.enableEncryption) { await this.container.checkAndInitializeEncryption(); options.containerRid = this.container._rid; let count = 0; diagnosticNode.beginEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsEncryptOperation ); const { partitionKeyList, encryptedCount } = await this.container.encryptionProcessor.getEncryptedPartitionKeyValue( this.partitionKey ); partitionKey = partitionKeyList; count += encryptedCount; if (await this.container.encryptionProcessor.isPathEncrypted("/id")) { url = await this.container.encryptionProcessor.getEncryptedUrl(this.url); count++; } diagnosticNode.endEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsEncryptOperation, count ); } const path = (0, import_common.getPathFromLink)(url); const id = (0, import_common.getIdFromLink)(url); const isPartitionLevelFailOverEnabled = this.clientContext.isPartitionLevelFailOverEnabled(); const partitionKeyRangeId = await (0, import_ClientUtils.computePartitionKeyRangeId)( diagnosticNode, partitionKey, this.clientContext.partitionKeyRangeCache, isPartitionLevelFailOverEnabled, this.container ); response = await this.clientContext.delete({ path, resourceType: import_common.ResourceType.item, resourceId: id, options, partitionKey, diagnosticNode, partitionKeyRangeId }); } catch (error) { if (this.clientContext.enableEncryption) { await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(error); } throw error; } return new import_ItemResponse.ItemResponse( response.result, response.headers, response.code, response.substatus, this, (0, import_diagnostics.getEmptyCosmosDiagnostics)() ); }, this.clientContext); } /** * 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. * * @param options - Additional options for the request * @example * ```ts snippet:ItemPatch * import { CosmosClient } from "@azure/cosmos"; * * const endpoint = "https://your-account.documents.azure.com"; * const key = "<database account masterkey>"; * const client = new CosmosClient({ endpoint, key }); * * interface TodoItem { * title: string; * done: boolean; * id: string; * } * * const { database } = await client.databases.createIfNotExists({ id: "Test Database" }); * * const { container } = await database.containers.createIfNotExists({ id: "Test Container" }); * * const { resource: item } = await container.item("id", "<pkValue>").read<TodoItem>(); * * const { resource: patchedItem } = await container.item("id").patch<TodoItem>([ * { * op: "replace", // Operation type (can be replace, add, remove, set, incr) * path: "/title", // The path to the property to update * value: "new-title", // New value for the property * }, * { * op: "remove", * path: "/done", * }, * ]); * ``` */ async patch(body, options = {}) { return (0, import_diagnostics.withDiagnostics)(async (diagnosticNode) => { this.partitionKey = await (0, import_extractPartitionKey.setPartitionKeyIfUndefined)( diagnosticNode, this.container, this.partitionKey ); let url = this.url; let partitionKey = this.partitionKey; let response; try { if (this.clientContext.enableEncryption) { await this.container.checkAndInitializeEncryption(); options.containerRid = this.container._rid; body = (0, import_common.copyObject)(body); const operations = Array.isArray(body) ? body : body.operations; diagnosticNode.beginEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsEncryptOperation ); let propertiesEncryptedCount = 0; for (const operation of operations) { if (operation.op === import_patch.PatchOperationType.remove) { continue; } const isPathEncrypted = await this.container.encryptionProcessor.isPathEncrypted( operation.path ); if (!isPathEncrypted) { continue; } if (operation.op === import_patch.PatchOperationType.incr) { throw new import_request.ErrorResponse( `Increment patch operation is not allowed for encrypted path '${operation.path}'` ); } if ("value" in operation) { operation.value = await this.container.encryptionProcessor.encryptProperty( operation.path, operation.value ); } propertiesEncryptedCount++; } const { partitionKeyList, encryptedCount } = await this.container.encryptionProcessor.getEncryptedPartitionKeyValue(partitionKey); partitionKey = partitionKeyList; propertiesEncryptedCount += encryptedCount; if (await this.container.encryptionProcessor.isPathEncrypted("/id")) { url = await this.container.encryptionProcessor.getEncryptedUrl(this.url); propertiesEncryptedCount++; } diagnosticNode.endEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsEncryptOperation, propertiesEncryptedCount ); } const path = (0, import_common.getPathFromLink)(url); const id = (0, import_common.getIdFromLink)(url); const isPartitionLevelFailOverEnabled = this.clientContext.isPartitionLevelFailOverEnabled(); const partitionKeyRangeId = await (0, import_ClientUtils.computePartitionKeyRangeId)( diagnosticNode, partitionKey, this.clientContext.partitionKeyRangeCache, isPartitionLevelFailOverEnabled, this.container ); response = await this.clientContext.patch({ body, path, resourceType: import_common.ResourceType.item, resourceId: id, options, partitionKey, diagnosticNode, partitionKeyRangeId }); } catch (error) { if (this.clientContext.enableEncryption) { await this.container.throwIfRequestNeedsARetryPostPolicyRefresh(error); } throw error; } if (this.clientContext.enableEncryption) { try { diagnosticNode.beginEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsDecryptOperation ); const { body: result, propertiesDecryptedCount } = await this.container.encryptionProcessor.decrypt(response.result); response.result = result; diagnosticNode.endEncryptionDiagnostics( import_common.Constants.Encryption.DiagnosticsDecryptOperation, propertiesDecryptedCount ); } catch (error) { const decryptionError = new import_request.ErrorResponse( `Item patch operation was successful but response decryption failed: + ${error.message}` ); decryptionError.code = import_common.StatusCodes.ServiceUnavailable; throw decryptionError; } } return new import_ItemResponse.ItemResponse( response.result, response.headers, response.code, response.substatus, this, (0, import_diagnostics.getEmptyCosmosDiagnostics)() ); }, this.clientContext); } } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Item });