public async mergeOrWriteDocument()

in packages/azure-services/src/storage/cosmos-container-client.ts [84:133]


    public async mergeOrWriteDocument<T extends CosmosDocument>(
        document: T,
        partitionKey?: string,
        throwIfNotSuccess: boolean = true,
    ): Promise<CosmosOperationResponse<T>> {
        if (document.id === undefined) {
            return Promise.reject(
                'Document id property is undefined. Storage document merge operation must have a valid document id property value.',
            );
        }

        const effectivePartitionKey = this.getEffectivePartitionKey(document, partitionKey);
        const response = await this.cosmosClientWrapper.readItem<T>(
            document.id,
            this.dbName,
            this.collectionName,
            effectivePartitionKey,
            false,
        );
        if (response.statusCode === 404) {
            return this.cosmosClientWrapper.upsertItem<T>(
                document,
                this.dbName,
                this.collectionName,
                effectivePartitionKey,
                throwIfNotSuccess,
            );
        }

        const mergedDocument = response.item;
        _.mergeWith(mergedDocument, document, (target: T, source: T, key) => {
            // preserve the storage document _etag value
            if (key === '_etag') {
                return target;
            }

            return undefined;
        });

        // normalize document properties by converting from null to undefined
        const normalizedDocument = <T>this.getNormalizeMergedDocument(mergedDocument);

        return this.cosmosClientWrapper.upsertItem<T>(
            normalizedDocument,
            this.dbName,
            this.collectionName,
            effectivePartitionKey,
            throwIfNotSuccess,
        );
    }