|
| 1 | +using System.Collections; |
1 | 2 | using System.Collections.Generic;
|
2 | 3 | using System.Linq;
|
3 | 4 | using System.Threading.Tasks;
|
@@ -83,10 +84,10 @@ public async Task<Operation> ProcessAsync(Operation operation)
|
83 | 84 | };
|
84 | 85 |
|
85 | 86 | operationResult.Data = string.IsNullOrWhiteSpace(operation.Ref.Id)
|
86 |
| - ? await GetAllAsync(operation) |
87 |
| - : string.IsNullOrWhiteSpace(operation.Ref.Relationship) |
88 |
| - ? await GetByIdAsync(operation) |
89 |
| - : await GetRelationshipAsync(operation); |
| 87 | + ? await GetAllAsync(operation) |
| 88 | + : string.IsNullOrWhiteSpace(operation.Ref.Relationship) |
| 89 | + ? await GetByIdAsync(operation) |
| 90 | + : await GetRelationshipAsync(operation); |
90 | 91 |
|
91 | 92 | return operationResult;
|
92 | 93 | }
|
@@ -135,11 +136,38 @@ private async Task<object> GetRelationshipAsync(Operation operation)
|
135 | 136 | // when no generic parameter is available
|
136 | 137 | var relationshipType = _contextGraph.GetContextEntity(operation.GetResourceTypeName())
|
137 | 138 | .Relationships.Single(r => r.Is(operation.Ref.Relationship)).Type;
|
| 139 | + |
138 | 140 | var relatedContextEntity = _jsonApiContext.ContextGraph.GetContextEntity(relationshipType);
|
139 | 141 |
|
140 |
| - var doc = _documentBuilder.GetData(relatedContextEntity, result as IIdentifiable); // TODO: if this is safe, then it should be cast in the GetRelationshipAsync call |
| 142 | + if (result == null) |
| 143 | + return null; |
| 144 | + |
| 145 | + if (result is IIdentifiable singleResource) |
| 146 | + return GetData(relatedContextEntity, singleResource); |
141 | 147 |
|
142 |
| - return doc; |
| 148 | + if (result is IEnumerable multipleResults) |
| 149 | + return GetData(relatedContextEntity, multipleResults); |
| 150 | + |
| 151 | + throw new JsonApiException(500, |
| 152 | + $"An unexpected type was returned from '{_getRelationship.GetType()}.{nameof(IGetRelationshipService<T, TId>.GetRelationshipAsync)}'.", |
| 153 | + detail: $"Type '{result.GetType()} does not implement {nameof(IIdentifiable)} nor {nameof(IEnumerable<IIdentifiable>)}'"); |
| 154 | + } |
| 155 | + |
| 156 | + private DocumentData GetData(ContextEntity contextEntity, IIdentifiable singleResource) |
| 157 | + { |
| 158 | + return _documentBuilder.GetData(contextEntity, singleResource); |
| 159 | + } |
| 160 | + |
| 161 | + private List<DocumentData> GetData(ContextEntity contextEntity, IEnumerable multipleResults) |
| 162 | + { |
| 163 | + var resources = new List<DocumentData>(); |
| 164 | + foreach (var singleResult in multipleResults) |
| 165 | + { |
| 166 | + if (singleResult is IIdentifiable resource) |
| 167 | + resources.Add(_documentBuilder.GetData(contextEntity, resource)); |
| 168 | + } |
| 169 | + |
| 170 | + return resources; |
143 | 171 | }
|
144 | 172 |
|
145 | 173 | private TId GetReferenceId(Operation operation) => TypeHelper.ConvertType<TId>(operation.Ref.Id);
|
|
0 commit comments