-
-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathCountController.cs
More file actions
361 lines (341 loc) · 13.2 KB
/
CountController.cs
File metadata and controls
361 lines (341 loc) · 13.2 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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
using Microsoft.AspNetCore.Mvc;
using Nocturne.API.Attributes;
using Nocturne.Core.Contracts.Entries;
using Nocturne.Core.Contracts.Repositories;
namespace Nocturne.API.Controllers.V1;
/// <summary>
/// Count controller that provides 1:1 compatibility with Nightscout count endpoints.
/// Implements the /api/v1/count/* endpoints from the legacy JavaScript implementation.
/// </summary>
/// <seealso cref="IEntryStore"/>
/// <seealso cref="ITreatmentRepository"/>
/// <seealso cref="IDeviceStatusRepository"/>
/// <seealso cref="IProfileRepository"/>
/// <seealso cref="IFoodRepository"/>
/// <seealso cref="IActivityRepository"/>
[ApiController]
[Route("api/v1/[controller]")]
public class CountController : ControllerBase
{
private readonly IEntryStore _entryStore;
private readonly ITreatmentRepository _treatmentRepository;
private readonly IDeviceStatusRepository _deviceStatusRepository;
private readonly IProfileRepository _profileRepository;
private readonly IFoodRepository _foodRepository;
private readonly IActivityRepository _activityRepository;
private readonly ILogger<CountController> _logger;
/// <summary>
/// Initializes a new instance of <see cref="CountController"/>.
/// </summary>
/// <param name="entryStore">Store for glucose entry records.</param>
/// <param name="treatmentRepository">Repository for treatment records.</param>
/// <param name="deviceStatusRepository">Repository for device status records.</param>
/// <param name="profileRepository">Repository for profile records.</param>
/// <param name="foodRepository">Repository for food records.</param>
/// <param name="activityRepository">Repository for activity records.</param>
/// <param name="logger">Logger instance.</param>
public CountController(
IEntryStore entryStore,
ITreatmentRepository treatmentRepository,
IDeviceStatusRepository deviceStatusRepository,
IProfileRepository profileRepository,
IFoodRepository foodRepository,
IActivityRepository activityRepository,
ILogger<CountController> logger
)
{
_entryStore = entryStore;
_treatmentRepository = treatmentRepository;
_deviceStatusRepository = deviceStatusRepository;
_profileRepository = profileRepository;
_foodRepository = foodRepository;
_activityRepository = activityRepository;
_logger = logger;
}
/// <summary>
/// Count entries matching specific criteria
/// </summary>
/// <param name="find">MongoDB-style find query filters (JSON format)</param>
/// <param name="type">Entry type filter (sgv, mbg, cal)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Count of entries matching the criteria</returns>
[HttpGet("entries/where")]
[NightscoutEndpoint("/api/v1/count/entries/where")]
[ProducesResponseType(typeof(CountResponse), 200)]
public async Task<ActionResult<CountResponse>> CountEntries(
[FromQuery] string? find = null,
[FromQuery] string? type = null,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug(
"Count entries endpoint requested with find: {Find}, type: {Type} from {RemoteIpAddress}",
find,
type,
HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown"
);
try
{
var count = await _entryStore.CountAsync(find, type, cancellationToken);
_logger.LogDebug("Found {Count} entries matching criteria", count);
return Ok(new CountResponse { Count = count });
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Error counting entries with find: {Find}, type: {Type}",
find,
type
);
return StatusCode(
500,
new
{
status = 500,
message = "Internal server error while counting entries",
type = "internal",
}
);
}
}
/// <summary>
/// Count treatments matching specific criteria
/// </summary>
/// <param name="find">MongoDB-style find query filters (JSON format)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Count of treatments matching the criteria</returns>
[HttpGet("treatments/where")]
[NightscoutEndpoint("/api/v1/count/treatments/where")]
[ProducesResponseType(typeof(CountResponse), 200)]
public async Task<ActionResult<CountResponse>> CountTreatments(
[FromQuery] string? find = null,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug(
"Count treatments endpoint requested with find: {Find} from {RemoteIpAddress}",
find,
HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown"
);
try
{
var count = await _treatmentRepository.CountTreatmentsAsync(find, cancellationToken);
_logger.LogDebug("Found {Count} treatments matching criteria", count);
return Ok(new CountResponse { Count = count });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error counting treatments with find: {Find}", find);
return StatusCode(
500,
new
{
status = 500,
message = "Internal server error while counting treatments",
type = "internal",
}
);
}
}
/// <summary>
/// Count device status entries matching specific criteria
/// </summary>
/// <param name="find">MongoDB-style find query filters (JSON format)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Count of device status entries matching the criteria</returns>
[HttpGet("devicestatus/where")]
[NightscoutEndpoint("/api/v1/count/devicestatus/where")]
[ProducesResponseType(typeof(CountResponse), 200)]
public async Task<ActionResult<CountResponse>> CountDeviceStatus(
[FromQuery] string? find = null,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug(
"Count device status endpoint requested with find: {Find} from {RemoteIpAddress}",
find,
HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown"
);
try
{
var count = await _deviceStatusRepository.CountDeviceStatusAsync(find, cancellationToken);
_logger.LogDebug("Found {Count} device status entries matching criteria", count);
return Ok(new CountResponse { Count = count });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error counting device status with find: {Find}", find);
return StatusCode(
500,
new
{
status = 500,
message = "Internal server error while counting device status",
type = "internal",
}
);
}
}
/// <summary>
/// Count activity entries matching specific criteria
/// </summary>
/// <param name="find">MongoDB-style find query filters (JSON format)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Count of activity entries matching the criteria</returns>
[HttpGet("activity/where")]
[NightscoutEndpoint("/api/v1/count/activity/where")]
[ProducesResponseType(typeof(CountResponse), 200)]
public async Task<ActionResult<CountResponse>> CountActivity(
[FromQuery] string? find = null,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug(
"Count activity endpoint requested with find: {Find} from {RemoteIpAddress}",
find,
HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown"
);
try
{
var count = await _activityRepository.CountActivitiesAsync(find, cancellationToken);
_logger.LogDebug("Found {Count} activity entries matching criteria", count);
return Ok(new CountResponse { Count = count });
}
catch (Exception ex)
{
_logger.LogError(ex, "Error counting activity with find: {Find}", find);
return StatusCode(
500,
new
{
status = 500,
message = "Internal server error while counting activity",
type = "internal",
}
);
}
}
/// <summary>
/// Generic count endpoint for any storage type</summary>
/// <param name="storage">Storage type (entries, treatments, devicestatus, profile, food, activity)</param>
/// <param name="find">MongoDB-style find query filters (JSON format)</param>
/// <param name="type">Additional type filter (for entries: sgv, mbg, cal)</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>Count of records matching the criteria</returns>
[HttpGet("{storage}/where")]
[NightscoutEndpoint("/api/v1/count/:storage/where")]
[ProducesResponseType(typeof(CountResponse), 200)]
[ProducesResponseType(400)]
[ProducesResponseType(500)]
public async Task<ActionResult<CountResponse>> CountGeneric(
string storage,
[FromQuery] string? find = null,
[FromQuery] string? type = null,
CancellationToken cancellationToken = default
)
{
_logger.LogDebug(
"Generic count endpoint requested for storage: {Storage}, find: {Find}, type: {Type} from {RemoteIpAddress}",
storage,
find,
type,
HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "unknown"
);
try
{
// Validate storage type
var validStorageTypes = new[]
{
"entries",
"treatments",
"devicestatus",
"profile",
"food",
"activity",
};
if (!validStorageTypes.Contains(storage.ToLowerInvariant()))
{
_logger.LogWarning("Invalid storage type requested: {Storage}", storage);
return BadRequest(
new
{
status = 400,
message = $"Invalid storage type: {storage}. Supported types: {string.Join(", ", validStorageTypes)}",
type = "client",
}
);
}
long count;
switch (storage.ToLowerInvariant())
{
case "entries":
count = await _entryStore.CountAsync(
find,
type,
cancellationToken
);
break;
case "treatments":
count = await _treatmentRepository.CountTreatmentsAsync(find, cancellationToken);
break;
case "devicestatus":
count = await _deviceStatusRepository.CountDeviceStatusAsync(
find,
cancellationToken
);
break;
case "profile":
count = await _profileRepository.CountProfilesAsync(find, cancellationToken);
break;
case "food":
count = await _foodRepository.CountFoodAsync(find, type, cancellationToken);
break;
case "activity":
count = await _activityRepository.CountActivitiesAsync(find, cancellationToken);
break;
default:
// This shouldn't happen due to validation above, but just in case
return BadRequest(
new
{
status = 400,
message = $"Unsupported storage type: {storage}",
type = "client",
}
);
}
_logger.LogDebug("Found {Count} {Storage} records matching criteria", count, storage);
return Ok(new CountResponse { Count = count });
}
catch (Exception ex)
{
_logger.LogError(
ex,
"Error counting {Storage} with find: {Find}, type: {Type}",
storage,
find,
type
);
return StatusCode(
500,
new
{
status = 500,
message = $"Internal server error while counting {storage}",
type = "internal",
}
);
}
}
}
/// <summary>
/// Response object for count endpoints
/// </summary>
public class CountResponse
{
/// <summary>
/// Number of records matching the query criteria
/// </summary>
public long Count { get; set; }
}