|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Net; |
| 5 | +using System.Threading; |
| 6 | +using System.Threading.Tasks; |
| 7 | +using JetBrains.Annotations; |
| 8 | +using JsonApiDotNetCore; |
| 9 | +using JsonApiDotNetCore.Configuration; |
| 10 | +using JsonApiDotNetCore.Errors; |
| 11 | +using JsonApiDotNetCore.Middleware; |
| 12 | +using JsonApiDotNetCore.Queries; |
| 13 | +using JsonApiDotNetCore.Queries.Expressions; |
| 14 | +using JsonApiDotNetCore.Resources; |
| 15 | +using JsonApiDotNetCore.Resources.Annotations; |
| 16 | +using JsonApiDotNetCore.Serialization.Objects; |
| 17 | +using Microsoft.EntityFrameworkCore; |
| 18 | + |
| 19 | +namespace JsonApiDotNetCoreExampleTests.IntegrationTests.Archiving |
| 20 | +{ |
| 21 | + [UsedImplicitly(ImplicitUseKindFlags.InstantiatedNoFixedConstructorSignature)] |
| 22 | + public sealed class TelevisionBroadcastDefinition : JsonApiResourceDefinition<TelevisionBroadcast> |
| 23 | + { |
| 24 | + private readonly TelevisionDbContext _dbContext; |
| 25 | + private readonly IJsonApiRequest _request; |
| 26 | + private readonly IEnumerable<IQueryConstraintProvider> _constraintProviders; |
| 27 | + private readonly ResourceContext _broadcastContext; |
| 28 | + |
| 29 | + private DateTimeOffset? _storedArchivedAt; |
| 30 | + |
| 31 | + public TelevisionBroadcastDefinition(IResourceGraph resourceGraph, TelevisionDbContext dbContext, IJsonApiRequest request, |
| 32 | + IEnumerable<IQueryConstraintProvider> constraintProviders) |
| 33 | + : base(resourceGraph) |
| 34 | + { |
| 35 | + _dbContext = dbContext; |
| 36 | + _request = request; |
| 37 | + _constraintProviders = constraintProviders; |
| 38 | + _broadcastContext = resourceGraph.GetResourceContext<TelevisionBroadcast>(); |
| 39 | + } |
| 40 | + |
| 41 | + public override FilterExpression OnApplyFilter(FilterExpression existingFilter) |
| 42 | + { |
| 43 | + if (_request.IsReadOnly) |
| 44 | + { |
| 45 | + // Rule: hide archived broadcasts in collections, unless a filter is specified. |
| 46 | + |
| 47 | + if (IsReturningCollectionOfTelevisionBroadcasts() && !HasFilterOnArchivedAt(existingFilter)) |
| 48 | + { |
| 49 | + AttrAttribute archivedAtAttribute = |
| 50 | + _broadcastContext.Attributes.Single(attr => attr.Property.Name == nameof(TelevisionBroadcast.ArchivedAt)); |
| 51 | + |
| 52 | + var archivedAtChain = new ResourceFieldChainExpression(archivedAtAttribute); |
| 53 | + |
| 54 | + FilterExpression isUnarchived = new ComparisonExpression(ComparisonOperator.Equals, archivedAtChain, new NullConstantExpression()); |
| 55 | + |
| 56 | + return existingFilter == null |
| 57 | + ? isUnarchived |
| 58 | + : new LogicalExpression(LogicalOperator.And, ArrayFactory.Create(existingFilter, isUnarchived)); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + return base.OnApplyFilter(existingFilter); |
| 63 | + } |
| 64 | + |
| 65 | + private bool IsReturningCollectionOfTelevisionBroadcasts() |
| 66 | + { |
| 67 | + return IsRequestingCollectionOfTelevisionBroadcasts() || IsIncludingCollectionOfTelevisionBroadcasts(); |
| 68 | + } |
| 69 | + |
| 70 | + private bool IsRequestingCollectionOfTelevisionBroadcasts() |
| 71 | + { |
| 72 | + if (_request.IsCollection) |
| 73 | + { |
| 74 | + if (_request.PrimaryResource == _broadcastContext || _request.SecondaryResource == _broadcastContext) |
| 75 | + { |
| 76 | + return true; |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + return false; |
| 81 | + } |
| 82 | + |
| 83 | + private bool IsIncludingCollectionOfTelevisionBroadcasts() |
| 84 | + { |
| 85 | + // @formatter:wrap_chained_method_calls chop_always |
| 86 | + // @formatter:keep_existing_linebreaks true |
| 87 | + |
| 88 | + IncludeElementExpression[] includeElements = _constraintProviders |
| 89 | + .SelectMany(provider => provider.GetConstraints()) |
| 90 | + .Select(expressionInScope => expressionInScope.Expression) |
| 91 | + .OfType<IncludeExpression>() |
| 92 | + .SelectMany(include => include.Elements) |
| 93 | + .ToArray(); |
| 94 | + |
| 95 | + // @formatter:keep_existing_linebreaks restore |
| 96 | + // @formatter:wrap_chained_method_calls restore |
| 97 | + |
| 98 | + foreach (IncludeElementExpression includeElement in includeElements) |
| 99 | + { |
| 100 | + if (includeElement.Relationship is HasManyAttribute && includeElement.Relationship.RightType == _broadcastContext.ResourceType) |
| 101 | + { |
| 102 | + return true; |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + return false; |
| 107 | + } |
| 108 | + |
| 109 | + private bool HasFilterOnArchivedAt(FilterExpression existingFilter) |
| 110 | + { |
| 111 | + if (existingFilter == null) |
| 112 | + { |
| 113 | + return false; |
| 114 | + } |
| 115 | + |
| 116 | + var walker = new FilterWalker(); |
| 117 | + walker.Visit(existingFilter, null); |
| 118 | + |
| 119 | + return walker.HasFilterOnArchivedAt; |
| 120 | + } |
| 121 | + |
| 122 | + public override Task OnBeforeCreateResourceAsync(TelevisionBroadcast broadcast, CancellationToken cancellationToken) |
| 123 | + { |
| 124 | + AssertIsNotArchived(broadcast); |
| 125 | + |
| 126 | + return base.OnBeforeCreateResourceAsync(broadcast, cancellationToken); |
| 127 | + } |
| 128 | + |
| 129 | + [AssertionMethod] |
| 130 | + private static void AssertIsNotArchived(TelevisionBroadcast broadcast) |
| 131 | + { |
| 132 | + if (broadcast.ArchivedAt != null) |
| 133 | + { |
| 134 | + throw new JsonApiException(new Error(HttpStatusCode.Forbidden) |
| 135 | + { |
| 136 | + Title = "Television broadcasts cannot be created in archived state." |
| 137 | + }); |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + public override Task OnAfterGetForUpdateResourceAsync(TelevisionBroadcast resource, CancellationToken cancellationToken) |
| 142 | + { |
| 143 | + _storedArchivedAt = resource.ArchivedAt; |
| 144 | + |
| 145 | + return base.OnAfterGetForUpdateResourceAsync(resource, cancellationToken); |
| 146 | + } |
| 147 | + |
| 148 | + public override Task OnBeforeUpdateResourceAsync(TelevisionBroadcast resource, CancellationToken cancellationToken) |
| 149 | + { |
| 150 | + AssertIsNotShiftingArchiveDate(resource); |
| 151 | + |
| 152 | + return base.OnBeforeUpdateResourceAsync(resource, cancellationToken); |
| 153 | + } |
| 154 | + |
| 155 | + [AssertionMethod] |
| 156 | + private void AssertIsNotShiftingArchiveDate(TelevisionBroadcast resource) |
| 157 | + { |
| 158 | + if (_storedArchivedAt != null && resource.ArchivedAt != null && _storedArchivedAt != resource.ArchivedAt) |
| 159 | + { |
| 160 | + throw new JsonApiException(new Error(HttpStatusCode.Forbidden) |
| 161 | + { |
| 162 | + Title = "Archive date of television broadcasts cannot be shifted. Unarchive it first." |
| 163 | + }); |
| 164 | + } |
| 165 | + } |
| 166 | + |
| 167 | + public override async Task OnBeforeDeleteResourceAsync(int broadcastId, CancellationToken cancellationToken) |
| 168 | + { |
| 169 | + TelevisionBroadcast televisionBroadcast = |
| 170 | + await _dbContext.Broadcasts.FirstOrDefaultAsync(broadcast => broadcast.Id == broadcastId, cancellationToken); |
| 171 | + |
| 172 | + if (televisionBroadcast != null) |
| 173 | + { |
| 174 | + AssertIsArchived(televisionBroadcast); |
| 175 | + } |
| 176 | + |
| 177 | + await base.OnBeforeDeleteResourceAsync(broadcastId, cancellationToken); |
| 178 | + } |
| 179 | + |
| 180 | + [AssertionMethod] |
| 181 | + private static void AssertIsArchived(TelevisionBroadcast televisionBroadcast) |
| 182 | + { |
| 183 | + if (televisionBroadcast.ArchivedAt == null) |
| 184 | + { |
| 185 | + throw new JsonApiException(new Error(HttpStatusCode.Forbidden) |
| 186 | + { |
| 187 | + Title = "Television broadcasts must first be archived before they can be deleted." |
| 188 | + }); |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + private sealed class FilterWalker : QueryExpressionRewriter<object> |
| 193 | + { |
| 194 | + public bool HasFilterOnArchivedAt { get; private set; } |
| 195 | + |
| 196 | + public override QueryExpression VisitResourceFieldChain(ResourceFieldChainExpression expression, object argument) |
| 197 | + { |
| 198 | + if (expression.Fields.First().Property.Name == nameof(TelevisionBroadcast.ArchivedAt)) |
| 199 | + { |
| 200 | + HasFilterOnArchivedAt = true; |
| 201 | + } |
| 202 | + |
| 203 | + return base.VisitResourceFieldChain(expression, argument); |
| 204 | + } |
| 205 | + } |
| 206 | + } |
| 207 | +} |
0 commit comments