【问题标题】:Delete CosmosDB entry using Azure Function使用 Azure 函数删除 CosmosDB 条目
【发布时间】:2020-10-13 00:02:15
【问题描述】:

我一直在寻找一种使用 Azure Functions 删除 Cosmos 数据库中项目的技术,使用浏览器内代码编辑器。我不想在 VS 上使用本地开发的代码有很多原因。

我正在使用的代码是可用的here,我正在使用带有 CosmosDB 输入和输出绑定的 HttpTrigger。它们的命名相当明显(inputDocument、outputDocument)。

这段代码在从数据库读取项目和编写新文档方面效果惊人,但是我希望能够删除单个项目。我正在制作一个游戏“拍卖行”系统,要“购买”一件物品,我需要将其从数据库中删除。

我现在已经搜索了很多地方,很多人说要使用 DocumentDB,但我认为浏览器编辑器不能支持这一点,我无法识别正确的 Azure 库来使用它。如果我错过了一个步骤,请告诉我。当我添加时它失败了

#r "Microsoft.Azure.Documents.Client"
using Microsoft.Azure.Documents.Client;

编辑 在与 Azure 支持人员交谈后,我发现 v3 使用 Documents.Core,而不是 Documents.Client。如果有人可以提供 Documents.Core 的文档,我将不胜感激!

谢谢。代码复制如下;

    #r "Newtonsoft.Json"

    using System.Net;
    using System.Linq;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Primitives;
    using Newtonsoft.Json;

    public class AuctionItem
    {
        [JsonProperty("itemID")]
        public string itemID { get; set; }
    
        [JsonProperty("price")]
        public string Price { get; set; }
    
        [JsonProperty("amount")]
        public string Amount { get; set; }
    }

    public static IActionResult Run(HttpRequest req, out object outputDocument, 
    IEnumerable<AuctionItem> inputDocument, ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = req.Query["name"];
        string price = req.Query["price"];
        string amount = req.Query["amount"];

        string command = req.Query["command"];

        outputDocument = null;

        if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(price) && !string.IsNullOrEmpty(amount)) 
        {
            string responseMessage = "{\"Message\":\"Success\",\n\"Data\": [" + "\n";
               
            if (!string.IsNullOrEmpty(command)) {
                if (command == "1") {
                    foreach (var item in inputDocument) {
                        responseMessage += "{\n\t\"itemID\":\"" + item.itemID + "\"," + "\n";
                        responseMessage += "\t\"price\":\"" + item.Price + "\"," + "\n";
                        responseMessage += "\t\"amount\":\"" + item.Amount + "\"}," + "\n";
                    }
                } else if (command == "2") {
                    var item = inputDocument.Where(x => x.itemID == name).FirstOrDefault();
                    if (item != null) {
                        inputDocument = inputDocument.Where(x => x != item);
                    }
                } else if (command == "3") {
                    responseMessage += "{\n\t\"itemID\":\"" + name + "\",\n";
                    responseMessage += "\t\"price\":\"" + price + "\",\n";
                    responseMessage += "\t\"amount\":\"" + amount + "\"}\n";
                

                    log.LogInformation(responseMessage);
                    outputDocument = new {
                        itemID = name,
                        price = price,
                        amount = amount
                    };
                }
            }
        
            responseMessage += "]}";
            return new OkObjectResult(responseMessage);
        } else {
            outputDocument = null;
            return new BadRequestResult();
        }
            
    }

【问题讨论】:

    标签: azure azure-functions azure-cosmosdb


    【解决方案1】:

    您需要在您的 http 触发器中创建一个名为“function.proj”的文件。

    内容:

    <Project Sdk="Microsoft.NET.Sdk">
        <PropertyGroup>
            <TargetFramework>netcoreapp3.0</TargetFramework>
        </PropertyGroup>
        <ItemGroup>
            <PackageReference Include="Microsoft.Azure.DocumentDB.Core" Version="2.12.0" />
        </ItemGroup>
    </Project>
    

    创建步骤:

    1.切换到经典体验

    2.创建文件

    下面是我的测试代码,可以正常运行:

    #r "Newtonsoft.Json"
    #r "Microsoft.Azure.DocumentDB.Core"
    
    using System.Net;
    using System.Linq;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Primitives;
    using Newtonsoft.Json;
    using Microsoft.Azure.Documents;
    using Microsoft.Azure.Documents.Client;
    using System;
    using System.Threading.Tasks;
    
    private static DocumentClient client;
    
    public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");
    
        client = new DocumentClient(new Uri("endpointUrl"), "authorizationKey");
        ResourceResponse<Document> response = await client.DeleteDocumentAsync(
            UriFactory.CreateDocumentUri("databaseName", "collectionName", "id"),
            new RequestOptions { PartitionKey = new PartitionKey("partition-key-value") });
    
        log.LogInformation("Request charge of delete operation: {0}", response.RequestCharge);
        log.LogInformation("StatusCode of operation: {0}", response.StatusCode);
    
    
        return new OkResult();    
    }
    

    顺便说一下,你可以找到文档here

    【讨论】:

    • 一开始的那一点魔力似乎让我的代码接受了 DocumentClient!非常感谢您的帮助:)
    • 抱歉添加到问题中,但是您将如何将 Run 函数作为异步任务运行,但保留输出绑定的“输出输出文档”?异步函数不能有变量
    • 异步方法不支持 out-by-reference 参数。你可以使用CreateDocumentAsync()方法代替out参数。
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多