-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCosmosSelectionRepository.cs
More file actions
56 lines (47 loc) · 1.78 KB
/
CosmosSelectionRepository.cs
File metadata and controls
56 lines (47 loc) · 1.78 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
using F1.Core.Interfaces;
using F1.Core.Models;
using Microsoft.Azure.Cosmos;
using Microsoft.Extensions.Configuration;
namespace F1.Infrastructure.Repositories;
public class CosmosSelectionRepository : ISelectionRepository
{
private readonly Container _container;
public CosmosSelectionRepository(CosmosClient cosmosClient, IConfiguration configuration)
{
var databaseName = configuration["CosmosDb:DatabaseName"];
_container = cosmosClient.GetContainer(databaseName, "Selections");
}
public async Task<Selection?> GetSelectionAsync(string raceId, string userId)
{
var queryDefinition = new QueryDefinition(
"SELECT TOP 1 * FROM c WHERE c.raceId = @raceId AND c.userId = @userId ORDER BY c._ts DESC")
.WithParameter("@raceId", raceId)
.WithParameter("@userId", userId);
var query = _container.GetItemQueryIterator<Selection>(
queryDefinition,
requestOptions: new QueryRequestOptions
{
PartitionKey = new PartitionKey(raceId)
});
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
var selection = response.FirstOrDefault();
if (selection is not null)
{
return selection;
}
}
return null;
}
public async Task<Selection> UpsertSelectionAsync(Selection selection)
{
if (selection.Id == Guid.Empty)
{
var existing = await GetSelectionAsync(selection.RaceId, selection.UserId);
selection.Id = existing?.Id ?? Guid.NewGuid();
}
var response = await _container.UpsertItemAsync(selection, new PartitionKey(selection.RaceId));
return response.Resource;
}
}