3

I have a Blazor, Azure Stacic Web App that is using Azure HTTP Trigger Functions to perform CRUD operations on an Azure CosmosDB. I am unsure how to remove a single item from the database? GET and POST actions seem to be well documented for HTTP Trigger Functions but I am struggling to find out how to perform a DELETE on just a single item. I have the id property of the item, so would be choosing the item to be removed by it's id.

For my POST actions I am using the IAsyncCollector object and it's Add method, but there doesn't look to be an equivalent for removing.

This is my first question on StackOverflow so if I need more detail/specifics then please let me know :) . I am also relatively new to Azure Functions so if I am fundamentally misunderstanding something then that would be great to know.

Thank you!

  • 1
    Welcome to Stack Overflow, Matt! Please edit your question and include the code you have written so far. That will help folks to understand your problem better. – Gaurav Mantri May 23 '21 at 13:14
  • Thank you @GauravMantri that would have helped wouldn't it! I will definitely put the code I have written so far in next time. – Matt Ingham May 23 '21 at 15:15

1 Answers1

4

This has already been answered here. However, that is with the func code editor using portal.

You can instead bind an instance of DocumentClient directly to your HTTP trigger function:

[FunctionName("Function1")]
public async Task<IActionResult> DeleteProduct(
    [HttpTrigger(
        authLevel: AuthorizationLevel.Anonymous,
        methods: "delete",
        Route = "products/{productId}")] HttpRequest request,
    [CosmosDB(
        databaseName: "my-database",
        collectionName: "products")] DocumentClient client,
    Guid productId)
{
    Uri productUri = UriFactory.CreateDocumentUri("my-database", "products", productId.ToString());
    PartitionKey partitionKey = new PartitionKey("my-partition-key");
    RequestOptions requestOptions = new RequestOptions { PartitionKey = partitionKey };

    ResourceResponse<Document> response = await client.DeleteDocumentAsync(productUri, requestOptions);
    // Use response for something or not...

    return new NoContentResult();
}

The example requires you to have a Cosmos DB connection string configured with the key "CosmosDBConnection". This must be set in local.settings.json for local development:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "CosmosDBConnection": "my-cosmos-db-connection"
  }
}

And in your function app's application settings on portal.

You'll need the following packages to make it work:

  • Microsoft.Azure.Cosmos
  • Microsoft.Azure.WebJobs.Extensions.CosmosDB
Kristin
  • 1,336
  • 7
  • 23