This repository was archived by the owner on Jul 28, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDiscoveryFunction.cs
More file actions
70 lines (59 loc) · 2.63 KB
/
DiscoveryFunction.cs
File metadata and controls
70 lines (59 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using Azure.Storage.Queues;
using Microsoft.Azure.Functions.Worker;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NHS.MESH.Client.Contracts.Services;
using ServiceLayer.Mesh.Data;
using ServiceLayer.Mesh.Models;
namespace ServiceLayer.Mesh.Functions
{
public class DiscoveryFunction
{
private readonly ILogger _logger;
private readonly IMeshInboxService _meshInboxService;
private readonly ServiceLayerDbContext _serviceLayerDbContext;
private readonly QueueClient _queueClient;
public DiscoveryFunction(ILogger<DiscoveryFunction> logger, IMeshInboxService meshInboxService, ServiceLayerDbContext serviceLayerDbContext, QueueClient queueClient)
{
_logger = logger;
_meshInboxService = meshInboxService;
_serviceLayerDbContext = serviceLayerDbContext;
_queueClient = queueClient;
}
[Function("DiscoveryFunction")]
public async Task Run([TimerTrigger("%DiscoveryTimerExpression%")] TimerInfo myTimer)
{
_logger.LogInformation($"DiscoveryFunction started at: {DateTime.Now}");
var mailboxId = Environment.GetEnvironmentVariable("MailboxId")
?? throw new InvalidOperationException($"Environment variable 'MailboxId' is not set or is empty.");
var response = await _meshInboxService.GetMessagesAsync(mailboxId);
_queueClient.CreateIfNotExists();
foreach (var messageId in response.Response.Messages)
{
using var transaction = await _serviceLayerDbContext.Database.BeginTransactionAsync();
var existing = await _serviceLayerDbContext.MeshFiles
.AsNoTracking()
.FirstOrDefaultAsync(f => f.FileId == messageId);
if (existing == null)
{
_serviceLayerDbContext.MeshFiles.Add(new MeshFile
{
FileId = messageId,
FileType = MeshFileType.NbssAppointmentEvents,
MailboxId = mailboxId,
Status = MeshFileStatus.Discovered,
FirstSeenUtc = DateTime.UtcNow,
LastUpdatedUtc = DateTime.UtcNow
});
await _serviceLayerDbContext.SaveChangesAsync();
await transaction.CommitAsync();
_queueClient.SendMessage(messageId);
}
else
{
await transaction.RollbackAsync();
}
}
}
}
}