Skip to content

Commit

Permalink
1️⃣1️⃣ sync todoitem overdue status
Browse files Browse the repository at this point in the history
  • Loading branch information
Ami Hollander committed Jan 6, 2024
1 parent 121ffbf commit 880fbd3
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
5 changes: 5 additions & 0 deletions infra/app/db.bicep
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ param containers array = [
id: 'VirusTotal'
partitionKey: '/id'
}
{
name: 'Leases'
id: 'Leases'
partitionKey: '/id'
}
]

param databaseName string = ''
Expand Down
68 changes: 68 additions & 0 deletions src/backend/CosmosTodoItemTrigger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using System;
using System.Collections.Generic;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using backend.Entities;
using backend.Models;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Extensions.DurableTask;
namespace backend
{
public class CosmosTodoItemTrigger
{
[FunctionName("CosmosTodoItemTrigger")]
public async Task Run(
[CosmosDBTrigger(
databaseName: "%CosmosDatabaseName%",
containerName: "TodoItem",
Connection = "CosmosConnectionOptions",
LeaseContainerName = "Leases",
StartFromBeginning = true,
CreateLeaseContainerIfNotExists = false)] IReadOnlyList<TodoItem> input,
[CosmosDB(
databaseName: "%CosmosDatabaseName%",
containerName: "TodoItem",
Connection = "CosmosConnectionOptions")]
IAsyncCollector<TodoItem> output,
[DurableClient] IDurableEntityClient durableEntityClient)
{
if (input != null && input.Count > 0)
{
foreach (var item in input)
{
bool updated = await UpdateDbState(output, item);

if (!updated)
{
await UpdateEntityState(durableEntityClient, item);
}
}
}
}

private async Task<bool> UpdateDbState(IAsyncCollector<TodoItem> output, TodoItem item)
{
if (item.State != TodoItemState.Overdue && item.IsOverdue())
{
item.State = TodoItemState.Overdue;
item.UpdatedDate = DateTimeOffset.UtcNow.DateTime;
await output.AddAsync(item);

return true;
}

return false;
}

private async Task UpdateEntityState(IDurableEntityClient durableEntityClient, TodoItem item)
{
if (item.DueDate is null || item.IsOverdue())
{
await durableEntityClient.SignalEntityAsync<ITodoItemEntity>(item.Id, proxy => proxy.Delete());
return;
}

await durableEntityClient.SignalEntityAsync<ITodoItemEntity>(item.Id, proxy => proxy.Create(item));
}
}
}

0 comments on commit 880fbd3

Please sign in to comment.