This repository was archived by the owner on Nov 5, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathCosmosLibraryStore.cs
More file actions
142 lines (127 loc) · 5.17 KB
/
CosmosLibraryStore.cs
File metadata and controls
142 lines (127 loc) · 5.17 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Microsoft.Azure.Cosmos;
using ServerlessLibrary.Models;
namespace ServerlessLibrary
{
/// <summary>
/// Cosmos db Library store
/// </summary>
public class CosmosLibraryStore : ILibraryStore
{
public CosmosLibraryStore()
{
CosmosDBRepository<LibraryItem>.Initialize();
}
public async Task Add(LibraryItem libraryItem)
{
await CosmosDBRepository<LibraryItem>.CreateItemAsync(libraryItem);
}
async public Task<IList<LibraryItem>> GetAllItems()
{
IEnumerable<LibraryItem> libraryItems = await CosmosDBRepository<LibraryItem>.GetAllItemsAsync();
return libraryItems.ToList();
}
}
/// <summary>
/// Cosmos db APIs
/// </summary>
/// <typeparam name="T"></typeparam>
static class CosmosDBRepository<T> where T : class
{
private static readonly string DatabaseId = ServerlessLibrarySettings.Database;
private static readonly string CollectionId = ServerlessLibrarySettings.Collection;
private static Container container;
public static async Task<T> GetItemAsync(string id)
{
try
{
ItemResponse<T> response = await container.ReadItemAsync<T>(id, PartitionKey.None);
return response.Resource;
}
catch (CosmosException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
else
{
throw;
}
}
}
public static async Task<List<T>> GetAllItemsAsync()
{
FeedIterator<T> query = container.GetItemQueryIterator<T>(
queryDefinition: null,
requestOptions: new QueryRequestOptions() { MaxItemCount = -1 }); // NOTE: FeedOptions.EnableCrossPartitionQuery is removed in SDK v3 (https://docs.microsoft.com/en-us/azure/cosmos-db/sql/migrate-dotnet-v3?tabs=dotnet-v3#changes-to-feedoptions-queryrequestoptions-in-v30-sdk)
List<T> results = new List<T>();
using (query)
{
while (query.HasMoreResults)
{
results.AddRange(await query.ReadNextAsync());
}
}
return results;
}
public static async Task<T> CreateItemAsync(T item)
{
ItemResponse<T> response = await container.CreateItemAsync(item, PartitionKey.None);
return response.Resource;
}
public static async Task<T> UpdateItemAsync(string id, T item)
{
ItemResponse<T> response = await container.UpsertItemAsync(item, PartitionKey.None);
return response.Resource;
}
public static async Task DeleteItemAsync(string id)
{
await container.DeleteItemAsync<T>(id, PartitionKey.None);
}
public static void Initialize()
{
if (container == null)
{
CosmosClient client;
// Use DefaultAzureCredential as the default authentication method (recommended for Azure workloads)
if (!string.IsNullOrEmpty(ServerlessLibrarySettings.CosmosEndpoint))
{
try
{
// Create DefaultAzureCredential with basic options compatible with .NET Core 2.1
TokenCredential credential = new DefaultAzureCredential();
client = new CosmosClient(ServerlessLibrarySettings.CosmosEndpoint, credential);
}
catch
{
// Fallback to connection string authentication if DefaultAzureCredential fails
if (!string.IsNullOrEmpty(ServerlessLibrarySettings.CosmosAuthkey))
{
client = new CosmosClient(
ServerlessLibrarySettings.CosmosEndpoint,
ServerlessLibrarySettings.CosmosAuthkey);
}
else
{
throw new System.InvalidOperationException(
"Unable to authenticate with Cosmos DB. Ensure either managed identity is configured or CosmosAuthkey is provided.");
}
}
}
else
{
throw new System.InvalidOperationException("CosmosEndpoint must be configured.");
}
DatabaseResponse databaseResponse = client.CreateDatabaseIfNotExistsAsync(DatabaseId).Result;
Database database = databaseResponse;
ContainerResponse containerResponse = database.CreateContainerIfNotExistsAsync(id: CollectionId, partitionKeyPath: "/_partitionKey", throughput: 400).Result;
container = containerResponse;
}
}
}
}