从 azure 函数有条件地插入 Cosmos DB

Conditionally Insert in Cosmos DB from azure functions

我需要从 azure 函数向 Cosmos DB 中插入数据,下面是工作代码

    [FunctionName("ABC")]
    public static IActionResult Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = "deals")] HttpRequest req,
    [CosmosDB(databaseName: "XXX",
                        collectionName: "YYY",
                        ConnectionStringSetting = "OnChangeTrigger_ConnectionString")] out dynamic deal,
    ILogger log)
    {
       string requestBody = new StreamReader(req.Body).ReadToEnd();
        
        deal = JsonConvert.DeserializeObject(requestBody);
        if (string.IsNullOrEmpty(deal.Id?.ToString()))
            {
                deal.Id = Guid.NewGuid();
            }
        deal.id = deal.Id;
        return new OkObjectResult(deal.Id.ToString());
     }

是否可以在插入前放一些过滤器(或检查数据)?

使用AsyncCollector:

    [FunctionName("ABC")]
        public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = "deals")] HttpRequest req,
        [CosmosDB(databaseName: "XXX",
                            collectionName: "YYY",
                            ConnectionStringSetting = "OnChangeTrigger_ConnectionString")] IAsyncCollector<dynamic> dealsCollector,
        ILogger log)
        {
           string requestBody = new StreamReader(req.Body).ReadToEnd();
            if (someCondition)
            {
                deal = JsonConvert.DeserializeObject(requestBody);
                if (string.IsNullOrEmpty(deal.Id?.ToString()))
                    {
                        deal.Id = Guid.NewGuid();
                    }
                deal.id = deal.Id;
                await dealsCollector.AddAsync(deal);
                return new OkObjectResult(deal.Id.ToString());
            }
            
            // return something else?
            return new OkObjectResult();
         }