-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonApiController.cs
More file actions
620 lines (547 loc) · 20.8 KB
/
Copy pathJsonApiController.cs
File metadata and controls
620 lines (547 loc) · 20.8 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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
using JsonApiToolkit.Configuration;
using JsonApiToolkit.Extensions;
using JsonApiToolkit.Extensions.Projection;
using JsonApiToolkit.Extensions.Querying;
using JsonApiToolkit.Filters;
using JsonApiToolkit.Helpers;
using JsonApiToolkit.Mapping;
using JsonApiToolkit.Models.Documents;
using JsonApiToolkit.Models.Errors;
using JsonApiToolkit.Models.Metadata;
using JsonApiToolkit.Models.Querying;
using JsonApiToolkit.Models.Resources;
using JsonApiToolkit.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace JsonApiToolkit.Controllers;
/// <summary>
/// Base controller for JSON:API compliant responses.
/// Handles content negotiation and applies JsonApiExceptionFilter automatically.
/// </summary>
[Produces("application/vnd.api+json")]
[Consumes("application/vnd.api+json")]
[ServiceFilter(typeof(JsonApiExceptionFilter))]
public abstract class JsonApiController : ControllerBase
{
/// <summary>
/// Gets the logger instance.
/// </summary>
protected ILogger<JsonApiController> Logger =>
field ??= HttpContext.RequestServices.GetRequiredService<ILogger<JsonApiController>>();
/// <summary>
/// Gets the query parser service.
/// </summary>
protected IJsonApiQueryParser QueryParser =>
field ??= HttpContext.RequestServices.GetRequiredService<IJsonApiQueryParser>();
/// <summary>
/// Gets the configured JsonApiOptions.
/// </summary>
protected JsonApiOptions Options =>
field ??= HttpContext.RequestServices.GetRequiredService<IOptions<JsonApiOptions>>().Value;
/// <summary>
/// Parses JSON:API query parameters (filter, sort, page, include).
/// </summary>
protected QueryParameters GetJsonApiQueryParameters()
{
return QueryParser.Parse(Request);
}
/// <summary>
/// Applies only filtering from JSON:API query parameters to a queryable.
/// Useful when you need to filter before aggregation/projection to DTOs.
/// </summary>
/// <typeparam name="T">The entity type to filter.</typeparam>
/// <param name="queryable">The queryable to apply filters to.</param>
/// <returns>The filtered queryable.</returns>
/// <remarks>
/// Use this when working with projections/DTOs where you need to apply filters
/// to the source entity before grouping or projecting to a DTO.
/// </remarks>
protected IQueryable<T> ApplyFiltersOnly<T>(IQueryable<T> queryable)
where T : class
{
QueryParameters parameters = GetJsonApiQueryParameters();
if (parameters.Filter == null)
return queryable;
return queryable.ApplyFilters(parameters.Filter, Logger);
}
/// <summary>
/// Returns 200 OK with a single resource as JSON:API document.
/// </summary>
protected IActionResult JsonApiOk<T>(T entity, string resourceType)
where T : class
{
QueryParameters parameters = GetJsonApiQueryParameters();
var mappedIncludes = EfIncludePathHelper.MapIncludePathsToClrProperties<T>(
parameters.Include
);
string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.Path}";
JsonApiDocument<ResourceObject> document = JsonApiMapper.ToDocument(
entity,
resourceType,
baseUrl,
mappedIncludes,
Logger,
parameters.Fields
);
return Ok(document);
}
/// <summary>
/// Returns 200 OK for a single resource queryable with JSON:API query support (filter, include).
/// Use this when you need includes to be automatically loaded from the database.
/// </summary>
protected async Task<IActionResult> JsonApiOkAsync<T>(
IQueryable<T> queryable,
string resourceType
)
where T : class
{
QueryParameters parameters = GetJsonApiQueryParameters();
var mappedIncludes = EfIncludePathHelper.MapIncludePathsToClrProperties<T>(
parameters.Include
);
var (mainFilters, includeFilters) = IncludeFilterParser.SeparateIncludeFilters(
parameters.Filter,
parameters.Include
);
IQueryable<T> filteredQuery = queryable;
// Apply main entity filters
if (mainFilters != null)
filteredQuery = filteredQuery.ApplyFilters(mainFilters, Logger);
// Apply includes (with or without filters)
if (includeFilters.Count > 0)
{
filteredQuery = filteredQuery.ApplyFilteredIncludes(
mappedIncludes,
includeFilters,
Logger
);
}
else if (mappedIncludes.Count > 0)
{
filteredQuery = filteredQuery.ApplyIncludes(mappedIncludes);
}
// Execute query for single entity
T? entity = await filteredQuery.FirstOrDefaultAsync().ConfigureAwait(false);
if (entity == null)
return JsonApiNotFound();
// Use existing JsonApiOk - entity now has includes loaded
return JsonApiOk(entity, resourceType);
}
/// <summary>
/// Returns 200 OK with a collection of resources as JSON:API document.
/// </summary>
protected IActionResult JsonApiOk<T>(
IEnumerable<T> entities,
string resourceType,
PaginationMeta? paginationMeta = null
)
where T : class
{
QueryParameters parameters = GetJsonApiQueryParameters();
var mappedIncludes = EfIncludePathHelper.MapIncludePathsToClrProperties<T>(
parameters.Include
);
string baseUrl = GetFullRequestUrl();
JsonApiCollectionDocument<ResourceObject> document = JsonApiMapper.ToCollectionDocument(
entities,
resourceType,
baseUrl,
paginationMeta,
mappedIncludes,
Logger,
parameters.Fields
);
return Ok(document);
}
/// <summary>
/// Returns 200 OK for queryable with full JSON:API query support (filter, sort, page, include).
/// </summary>
protected async Task<IActionResult> JsonApiQueryAsync<T>(
IQueryable<T> queryable,
string resourceType
)
where T : class
{
QueryParameters parameters = GetJsonApiQueryParameters();
string baseUrl = GetFullRequestUrl();
var mappedIncludes = EfIncludePathHelper.MapIncludePathsToClrProperties<T>(
parameters.Include
);
LogQueryParameters<T>(parameters, mappedIncludes);
IQueryable<T> filteredQuery = ApplyFiltersAndIncludes(
queryable,
parameters,
mappedIncludes
);
if (parameters.Sort?.Count > 0)
filteredQuery = filteredQuery.ApplySorting(parameters.Sort, Logger);
int totalCount = await filteredQuery.CountAsync().ConfigureAwait(false);
LogCountResults<T>(parameters, totalCount);
if (Options.StrictPagination && parameters.Pagination != null && totalCount > 0)
{
int totalPages = (int)Math.Ceiling(totalCount / (double)parameters.Pagination.Size);
if (parameters.Pagination.Number > totalPages)
{
throw new JsonApiNotFoundException(
$"Page {parameters.Pagination.Number} does not exist. "
+ $"This collection has {totalPages} page(s). Request a page between 1 and {totalPages}.",
JsonApiErrorCodes.InvalidPageNumber,
new ErrorSource { Parameter = "page[number]" },
new Dictionary<string, object>
{
["value"] = parameters.Pagination.Number,
["totalPages"] = totalPages,
["totalResources"] = totalCount,
}
);
}
}
if (parameters.Pagination != null)
filteredQuery = filteredQuery.ApplyPagination(parameters.Pagination, totalCount);
PaginationMeta? paginationMeta =
parameters.Pagination != null
? PaginationHandler.CreatePaginationMeta(parameters.Pagination, totalCount)
: null;
Logger.LogDebug(
"Executing query for {EntityType}: TotalCount={TotalCount}, Returning={ReturnCount}",
typeof(T).Name,
totalCount,
parameters.Pagination?.Size ?? totalCount
);
IActionResult? projectionResult = await TryApplyDatabaseProjection(
filteredQuery,
resourceType,
baseUrl,
paginationMeta,
mappedIncludes,
parameters
);
if (projectionResult != null)
return projectionResult;
List<T> results = await filteredQuery.ToListAsync().ConfigureAwait(false);
JsonApiCollectionDocument<ResourceObject> document = JsonApiMapper.ToCollectionDocument(
results,
resourceType,
baseUrl,
paginationMeta,
mappedIncludes,
Logger,
parameters.Fields
);
return Ok(document);
}
/// <summary>
/// Builds a JSON:API query with filters, includes, and sorting applied, but WITHOUT pagination.
/// Use this for custom operations like CSV exports, aggregations, or projections.
/// </summary>
/// <typeparam name="T">The entity type to query.</typeparam>
/// <param name="queryable">The queryable to process.</param>
/// <param name="resourceType">The JSON:API resource type name.</param>
/// <param name="includeCount">Whether to execute a COUNT query. Set to false to skip for performance.</param>
/// <returns>A result containing the processed query, parameters, and optional count.</returns>
protected async Task<JsonApiQueryResult<T>> BuildJsonApiQueryAsync<T>(
IQueryable<T> queryable,
string resourceType,
bool includeCount = true
)
where T : class
{
QueryParameters parameters = GetJsonApiQueryParameters();
Logger.LogDebug(
"BuildQuery for {EntityType}: Filters={FilterCount}, Sorts={SortCount}, Includes={IncludeCount}, Fields={FieldsCount}",
typeof(T).Name,
parameters.Filter?.Filters?.Count ?? 0,
parameters.Sort?.Count ?? 0,
parameters.Include?.Count ?? 0,
parameters.Fields?.Count ?? 0
);
var mappedIncludes = EfIncludePathHelper.MapIncludePathsToClrProperties<T>(
parameters.Include
);
if (parameters.Include?.Count > 0 && mappedIncludes.Count == 0)
{
Logger.LogWarning(
"No valid includes for {EntityType}. Requested: {Includes}",
typeof(T).Name,
string.Join(", ", parameters.Include)
);
}
var (mainFilters, includeFilters) = IncludeFilterParser.SeparateIncludeFilters(
parameters.Filter,
parameters.Include
);
IQueryable<T> processedQuery = queryable;
// Apply main entity filters
if (mainFilters != null)
processedQuery = processedQuery.ApplyFilters(mainFilters, Logger);
// Apply includes (with or without filters)
if (includeFilters.Count > 0)
{
Logger.LogDebug(
"Applying {FilterCount} filtered includes for {EntityType}",
includeFilters.Count,
typeof(T).Name
);
processedQuery = processedQuery.ApplyFilteredIncludes(
mappedIncludes,
includeFilters,
Logger
);
}
else if (mappedIncludes.Count > 0)
{
// Use standard includes (no pagination optimization needed since we're not paginating)
processedQuery = processedQuery.ApplyIncludes(mappedIncludes);
Logger.LogDebug(
"Applied {IncludeCount} includes for {EntityType}",
mappedIncludes.Count,
typeof(T).Name
);
}
// Apply sorting
if (parameters.Sort?.Count > 0)
processedQuery = processedQuery.ApplySorting(parameters.Sort, Logger);
// Get count if requested
int totalCount = 0;
if (includeCount)
{
totalCount = await processedQuery.CountAsync().ConfigureAwait(false);
Logger.LogDebug(
"BuildQuery for {EntityType}: TotalCount={TotalCount}",
typeof(T).Name,
totalCount
);
}
return new JsonApiQueryResult<T>
{
Query = processedQuery,
Parameters = parameters,
TotalCount = totalCount,
};
}
/// <summary>
/// Returns 201 Created with new resource and Location header.
/// </summary>
protected IActionResult JsonApiCreated<T>(T entity, string resourceType, string id)
where T : class
{
QueryParameters parameters = GetJsonApiQueryParameters();
var mappedIncludes = EfIncludePathHelper.MapIncludePathsToClrProperties<T>(
parameters.Include
);
string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}{Request.Path}";
string selfUrl = $"{baseUrl}/{id}";
JsonApiDocument<ResourceObject> document = JsonApiMapper.ToDocument(
entity,
resourceType,
selfUrl,
mappedIncludes,
Logger,
parameters.Fields
);
return Created(selfUrl, document);
}
/// <summary>
/// Returns 204 No Content (for DELETE/PUT operations).
/// </summary>
protected IActionResult JsonApiNoContent() => NoContent();
/// <summary>
/// Returns 404 Not Found with JSON:API error.
/// </summary>
protected IActionResult JsonApiNotFound(string detail = "Resource not found")
{
var error = new JsonApiError
{
Status = "404",
Title = "Not Found",
Detail = detail,
};
return NotFound(new JsonApiErrorResponse { Errors = [error] });
}
/// <summary>
/// Returns 400 Bad Request with JSON:API error.
/// </summary>
protected IActionResult JsonApiBadRequest(string detail)
{
var error = new JsonApiError
{
Status = "400",
Title = "Bad Request",
Detail = detail,
};
return BadRequest(new JsonApiErrorResponse { Errors = [error] });
}
/// <summary>
/// Gets full request URL for self/pagination links.
/// </summary>
protected string GetFullRequestUrl() =>
$"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}";
private void LogQueryParameters<T>(QueryParameters parameters, List<string> mappedIncludes)
{
Logger.LogDebug(
"Query for {EntityType}: Filters={FilterCount}, Sorts={SortCount}, Includes={IncludeCount}, Pagination={HasPagination}, Fields={FieldsCount}",
typeof(T).Name,
parameters.Filter?.Filters?.Count ?? 0,
parameters.Sort?.Count ?? 0,
parameters.Include?.Count ?? 0,
parameters.Pagination != null,
parameters.Fields?.Count ?? 0
);
if (parameters.Filter?.Filters?.Count > 20)
{
Logger.LogInformation(
"Complex query with {Count} filters on {EntityType}",
parameters.Filter.Filters.Count,
typeof(T).Name
);
}
if (parameters.Include?.Count > 0 && mappedIncludes.Count == 0)
{
Logger.LogWarning(
"No valid includes for {EntityType}. Requested: {Includes}",
typeof(T).Name,
string.Join(", ", parameters.Include)
);
}
}
private IQueryable<T> ApplyFiltersAndIncludes<T>(
IQueryable<T> queryable,
QueryParameters parameters,
List<string> mappedIncludes
)
where T : class
{
var (mainFilters, includeFilters) = IncludeFilterParser.SeparateIncludeFilters(
parameters.Filter,
parameters.Include
);
IQueryable<T> filteredQuery = queryable;
if (mainFilters != null)
filteredQuery = filteredQuery.ApplyFilters(mainFilters, Logger);
if (includeFilters.Count > 0)
{
Logger.LogDebug(
"Applying {FilterCount} filtered includes for {EntityType}",
includeFilters.Count,
typeof(T).Name
);
filteredQuery = filteredQuery.ApplyFilteredIncludes(
mappedIncludes,
includeFilters,
Logger
);
}
else if (mappedIncludes.Count > 0)
{
filteredQuery =
parameters.Pagination != null
? filteredQuery.ApplyIncludesSingleQuery(mappedIncludes)
: filteredQuery.ApplyIncludes(mappedIncludes);
Logger.LogDebug(
"Applied {IncludeCount} includes for {EntityType} using {QueryType}",
mappedIncludes.Count,
typeof(T).Name,
parameters.Pagination != null ? "SingleQuery" : "SplitQuery"
);
}
return filteredQuery;
}
private void LogCountResults<T>(QueryParameters parameters, int totalCount)
{
if (totalCount == 0 && parameters.Filter?.Filters?.Count > 0)
{
Logger.LogInformation("Query returned 0 results for {EntityType}", typeof(T).Name);
}
else if (totalCount > 1000 && parameters.Pagination == null)
{
Logger.LogWarning(
"Large result set ({TotalCount}) without pagination. Consider adding pagination to improve performance",
totalCount
);
}
}
private async Task<IActionResult?> TryApplyDatabaseProjection<T>(
IQueryable<T> filteredQuery,
string resourceType,
string baseUrl,
PaginationMeta? paginationMeta,
List<string> mappedIncludes,
QueryParameters parameters
)
where T : class
{
if (!Options.EnableDatabaseProjection || parameters.Fields == null)
return null;
if (mappedIncludes.Count > 0)
{
Logger.LogDebug(
"Database projection skipped for {EntityType}: includes are not compatible with Select() projection",
typeof(T).Name
);
return null;
}
if (
parameters.Fields.TryGetValue(resourceType, out List<string>? requestedFields)
&& requestedFields.Count > 0
)
{
try
{
var projectionProperties = ProjectionPropertySelector.Determine(
typeof(T),
requestedFields
);
var (projectionType, projectionExpression) = ProjectionTypeCache.GetOrCreate(
typeof(T),
projectionProperties
);
IQueryable projectedQuery = DatabaseProjectionApplicator.ApplySelect(
filteredQuery,
projectionType,
projectionExpression
);
List<object> projectedResults = await DatabaseProjectionApplicator
.MaterializeAsync(projectedQuery, projectionType, HttpContext.RequestAborted)
.ConfigureAwait(false);
Logger.LogDebug(
"Database projection applied for {EntityType}: {FieldCount} fields projected",
typeof(T).Name,
requestedFields.Count
);
JsonApiCollectionDocument<ResourceObject> projectedDocument =
JsonApiMapper.ToCollectionDocument(
projectedResults,
resourceType,
baseUrl,
paginationMeta,
mappedIncludes,
Logger,
parameters.Fields
);
return Ok(projectedDocument);
}
catch (Exception ex)
{
Logger.LogWarning(
ex,
"Database projection failed for {EntityType}, falling back to full entity load",
typeof(T).Name
);
return null;
}
}
if (parameters.Fields.Count > 0)
{
Logger.LogDebug(
"Database projection skipped for {EntityType}: fields[] present but no key matches resourceType '{ResourceType}'. Keys: {Keys}",
typeof(T).Name,
resourceType,
string.Join(", ", parameters.Fields.Keys)
);
}
return null;
}
}