How to check if item is out of date in cosmosDB using azure functions and the cosmos node sdk? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to check if item is out of date in cosmosDB using azure functions and the cosmos node sdk? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I currently have an item in the database that two users are trying to update. If one updates the item, I want the other user’s update to fail then retry. I found a sample code for C# using the internal eTag, but I can’t find the javascript equivalent.

https://github.com/Azure/azure-cosmos-dotnet-v3/blob/e22f9593a1245d3b1c98db78bacc89e4786d96e7/Microsoft.Azure.Cosmos.Samples/Usage/ItemManagement/Program.cs#L683-L734

Here is some pseudocode for what I want to do using the etag:

const patchItem = async function(container: Container, incomingItem: ItemData, currentItem: ItemData)
{
    // state is an array of objects and this just adds to it
    incomingItem.state.forEach(c => currentItem.state.push(c));
    const appendedItem = 
    {
        id: currentItem.id,
        state: currentItem.state
        _etag: currentItem._eTag
    };
    const { resource: updatedItem } = await container.item(incomingItem.id).replace(appendedItem, {IfMatchETag = appendedItem._eTag});
    return updatedItem;
};

I am also reading the documentation on the change feed processor and wondering if there is a way I can read the item has been changed then fail the update. I’m not sure how to implement checking for changes in the change feed processor so any help with that would also be appreciated. Thank you!

Answer

I found the javascript equivalent for the etag and made the following fix:

const { resource: updatedItem } = await container.item(incomingItem.id).replace(appendedItem,  { accessCondition: { type: "IfMatch", condition: currentItem._etag } });

Documentation found here: https://docs.microsoft.com/en-us/azure/cosmos-db/sql-api-nodejs-samples

Code Example: https://github.com/Azure/azure-cosmos-js/blob/master/samples/ItemManagement.ts#L98-L135

We are here to answer your question about How to check if item is out of date in cosmosDB using azure functions and the cosmos node sdk? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji