网站搜索

javascript - 如何使用 Azure Functions 和 Cosmos Node SDK 检查 CosmosDB 中的项目是否过期?


我目前在数据库中有一个项目,两个用户都在尝试更新它。如果一个用户更新了该项目,我希望另一个用户的更新失败并重试。我找到了一个使用内部 eTag 的 C# 示例代码,但找不到 JavaScript 的等效代码。

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

这是我想使用 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;
};

我也在阅读关于更改 feed 处理器的文档,并想知道是否有方法可以在读取到项已更改后然后使更新失败。我不确定如何在更改 feed 处理器中实现检查更改,因此任何相关的帮助也将不胜感激。谢谢!

答案#1

我找到了 etag 的 JavaScript 等效项,并做了以下修复:

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

文档在此处找到:https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-nodejs-samples

代码示例:https://github.com/Azure/azure-cosmos-js/blob/master/samples/ItemManagement.ts#L98-L135