Skip to content

GetAffected syntax in resource hook helpers #541

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/Examples/GettingStarted/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
},
"GettingStarted": {
"commandName": "Project",
"launchBrowser": true
"launchBrowser": true,
"environmentVariables": {}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
}
},
"NoEntityFrameworkExample": {
"commandName": "Project"
"commandName": "Project",
"environmentVariables": {}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,24 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57181/",
"sslPort": 0
}
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57181/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/v1/students",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "api/v1/students",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"ResourceEntitySeparationExample": {
"commandName": "Project"
}
"ResourceEntitySeparationExample": {
"commandName": "Project",
"environmentVariables": {}
}
}
}
}
23 changes: 12 additions & 11 deletions src/JsonApiDotNetCore/Extensions/IServiceCollectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public static IServiceCollection AddJsonApi(
var config = new JsonApiOptions();
configureOptions(config);

if(autoDiscover != null)
if (autoDiscover != null)
{
var facade = new ServiceDiscoveryFacade(services, config.ResourceGraphBuilder);
autoDiscover(facade);
Expand Down Expand Up @@ -159,7 +159,7 @@ public static void AddJsonApiInternals(
services.AddScoped<IControllerContext, Services.ControllerContext>();
services.AddScoped<IDocumentBuilderOptionsProvider, DocumentBuilderOptionsProvider>();


if (jsonApiOptions.EnableResourceHooks)
{
services.AddSingleton(typeof(IHooksDiscovery<>), typeof(HooksDiscovery<>));
Expand Down Expand Up @@ -204,7 +204,7 @@ public static void SerializeAsJsonApi(this MvcOptions options, JsonApiOptions js
/// Adds all required registrations for the service to the container
/// </summary>
/// <exception cref="JsonApiSetupException"/>
public static IServiceCollection AddResourceService<T>(this IServiceCollection services)
public static IServiceCollection AddResourceService<T>(this IServiceCollection services)
{
var typeImplementsAnExpectedInterface = false;

Expand All @@ -213,28 +213,29 @@ public static IServiceCollection AddResourceService<T>(this IServiceCollection s
// it is _possible_ that a single concrete type could be used for multiple resources...
var resourceDescriptors = GetResourceTypesFromServiceImplementation(serviceImplementationType);

foreach(var resourceDescriptor in resourceDescriptors)
foreach (var resourceDescriptor in resourceDescriptors)
{
foreach(var openGenericType in ServiceDiscoveryFacade.ServiceInterfaces)
foreach (var openGenericType in ServiceDiscoveryFacade.ServiceInterfaces)
{
// A shorthand interface is one where the id type is ommitted
// e.g. IResourceService<T> is the shorthand for IResourceService<T, TId>
var isShorthandInterface = (openGenericType.GetTypeInfo().GenericTypeParameters.Length == 1);
if(isShorthandInterface && resourceDescriptor.IdType != typeof(int))
if (isShorthandInterface && resourceDescriptor.IdType != typeof(int))
continue; // we can't create a shorthand for id types other than int

var concreteGenericType = isShorthandInterface
? openGenericType.MakeGenericType(resourceDescriptor.ResourceType)
: openGenericType.MakeGenericType(resourceDescriptor.ResourceType, resourceDescriptor.IdType);

if(concreteGenericType.IsAssignableFrom(serviceImplementationType)) {
if (concreteGenericType.IsAssignableFrom(serviceImplementationType))
{
services.AddScoped(concreteGenericType, serviceImplementationType);
typeImplementsAnExpectedInterface = true;
}
}
}

if(typeImplementsAnExpectedInterface == false)
if (typeImplementsAnExpectedInterface == false)
throw new JsonApiSetupException($"{serviceImplementationType} does not implement any of the expected JsonApiDotNetCore interfaces.");

return services;
Expand All @@ -244,12 +245,12 @@ private static HashSet<ResourceDescriptor> GetResourceTypesFromServiceImplementa
{
var resourceDecriptors = new HashSet<ResourceDescriptor>();
var interfaces = type.GetInterfaces();
foreach(var i in interfaces)
foreach (var i in interfaces)
{
if(i.IsGenericType)
if (i.IsGenericType)
{
var firstGenericArgument = i.GenericTypeArguments.FirstOrDefault();
if(TypeLocator.TryGetResourceDescriptor(firstGenericArgument, out var resourceDescriptor) == true)
if (TypeLocator.TryGetResourceDescriptor(firstGenericArgument, out var resourceDescriptor) == true)
{
resourceDecriptors.Add(resourceDescriptor);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JsonApiDotNetCore.Extensions;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Models;
using JsonApiDotNetCore.Services;

namespace JsonApiDotNetCore.Hooks
{
Expand All @@ -15,68 +18,79 @@ namespace JsonApiDotNetCore.Hooks
/// Also contains information about updated relationships through
/// implementation of IRelationshipsDictionary<typeparamref name="TResource"/>>
/// </summary>
public interface IEntityDiffs<TResource> : IEnumerable<EntityDiffPair<TResource>> where TResource : class, IIdentifiable
public interface IDiffableEntityHashSet<TResource> : IEntityHashSet<TResource> where TResource : class, IIdentifiable
{
/// <summary>
/// The database values of the resources affected by the request.
/// Iterates over diffs, which is the affected entity from the request
/// with their associated current value from the database.
/// </summary>
HashSet<TResource> DatabaseValues { get; }

/// <summary>
/// The resources that were affected by the request.
/// </summary>
EntityHashSet<TResource> Entities { get; }
IEnumerable<EntityDiffPair<TResource>> GetDiffs();

}

/// <inheritdoc />
public class EntityDiffs<TResource> : IEntityDiffs<TResource> where TResource : class, IIdentifiable
public class DiffableEntityHashSet<TResource> : EntityHashSet<TResource>, IDiffableEntityHashSet<TResource> where TResource : class, IIdentifiable
{
/// <inheritdoc />
public HashSet<TResource> DatabaseValues { get => _databaseValues ?? ThrowNoDbValuesError(); }
/// <inheritdoc />
public EntityHashSet<TResource> Entities { get; private set; }

private readonly HashSet<TResource> _databaseValues;
private readonly bool _databaseValuesLoaded;
private Dictionary<PropertyInfo, HashSet<TResource>> _updatedAttributes;

public EntityDiffs(HashSet<TResource> requestEntities,
public DiffableEntityHashSet(HashSet<TResource> requestEntities,
HashSet<TResource> databaseEntities,
Dictionary<RelationshipAttribute, HashSet<TResource>> relationships)
Dictionary<RelationshipAttribute, HashSet<TResource>> relationships,
Dictionary<PropertyInfo, HashSet<TResource>> updatedAttributes)
: base(requestEntities, relationships)
{
Entities = new EntityHashSet<TResource>(requestEntities, relationships);
_databaseValues = databaseEntities;
_databaseValuesLoaded |= _databaseValues != null;
_updatedAttributes = updatedAttributes;
}

/// <summary>
/// Used internally by the ResourceHookExecutor to make live a bit easier with generics
/// </summary>
internal EntityDiffs(IEnumerable requestEntities,
internal DiffableEntityHashSet(IEnumerable requestEntities,
IEnumerable databaseEntities,
Dictionary<RelationshipAttribute, IEnumerable> relationships)
: this((HashSet<TResource>)requestEntities, (HashSet<TResource>)databaseEntities, TypeHelper.ConvertRelationshipDictionary<TResource>(relationships)) { }
Dictionary<RelationshipAttribute, IEnumerable> relationships,
IJsonApiContext jsonApiContext)
: this((HashSet<TResource>)requestEntities, (HashSet<TResource>)databaseEntities, TypeHelper.ConvertRelationshipDictionary<TResource>(relationships),
TypeHelper.ConvertAttributeDictionary(jsonApiContext.AttributesToUpdate, (HashSet<TResource>)requestEntities))
{ }


/// <inheritdoc />
public IEnumerator<EntityDiffPair<TResource>> GetEnumerator()
public IEnumerable<EntityDiffPair<TResource>> GetDiffs()
{
if (!_databaseValuesLoaded) ThrowNoDbValuesError();

foreach (var entity in Entities)
foreach (var entity in this)
{
TResource currentValueInDatabase = null;
currentValueInDatabase = _databaseValues.Single(e => entity.StringId == e.StringId);
TResource currentValueInDatabase = _databaseValues.Single(e => entity.StringId == e.StringId);
yield return new EntityDiffPair<TResource>(entity, currentValueInDatabase);
}
}

/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public new HashSet<TResource> GetAffected(Expression<Func<TResource, object>> NavigationAction)
{
var propertyInfo = TypeHelper.ParseNavigationExpression(NavigationAction);
var propertyType = propertyInfo.PropertyType;
if (propertyType.Inherits(typeof(IEnumerable))) propertyType = TypeHelper.GetTypeOfList(propertyType);
if (propertyType.Implements<IIdentifiable>())
{
// the navigation action references a relationship. Redirect the call to the relationship dictionary.
return base.GetAffected(NavigationAction);
}
else if (_updatedAttributes.TryGetValue(propertyInfo, out HashSet<TResource> entities))
{
return entities;
}
return new HashSet<TResource>();
}

private HashSet<TResource> ThrowNoDbValuesError()
{
throw new MemberAccessException("Cannot access database entities if the LoadDatabaseValues option is set to false");
throw new MemberAccessException("Cannot iterate over the diffs if the LoadDatabaseValues option is set to false");
}
}

Expand Down
11 changes: 9 additions & 2 deletions src/JsonApiDotNetCore/Hooks/Execution/EntityHashSet.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System;
using System.Collections.ObjectModel;
using System.Collections.Immutable;
using System.Linq.Expressions;

namespace JsonApiDotNetCore.Hooks
{
Expand All @@ -26,7 +27,7 @@ public interface IEntityHashSet<TResource> : IByAffectedRelationships<TResource>
/// </summary>
public class EntityHashSet<TResource> : HashSet<TResource>, IEntityHashSet<TResource> where TResource : class, IIdentifiable
{


/// <inheritdoc />
public Dictionary<RelationshipAttribute, HashSet<TResource>> AffectedRelationships { get => _relationships; }
Expand All @@ -53,9 +54,15 @@ public Dictionary<RelationshipAttribute, HashSet<TResource>> GetByRelationship(T
}

/// <inheritdoc />
public Dictionary<RelationshipAttribute, HashSet<TResource>> GetByRelationship<TRelatedResource>() where TRelatedResource : class, IIdentifiable
public Dictionary<RelationshipAttribute, HashSet<TResource>> GetByRelationship<TRelatedResource>() where TRelatedResource : class, IIdentifiable
{
return GetByRelationship(typeof(TRelatedResource));
}

/// <inheritdoc />
public HashSet<TResource> GetAffected(Expression<Func<TResource, object>> NavigationAction)
{
return _relationships.GetAffected(NavigationAction);
}
}
}
36 changes: 25 additions & 11 deletions src/JsonApiDotNetCore/Hooks/Execution/RelationshipsDictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using JsonApiDotNetCore.Internal;
using JsonApiDotNetCore.Models;

Expand All @@ -15,13 +17,9 @@ public interface IRelationshipsDictionary { }
/// <summary>
/// An interface that is implemented to expose a relationship dictionary on another class.
/// </summary>
public interface IByAffectedRelationships<TDependentResource> :
public interface IByAffectedRelationships<TDependentResource> :
IRelationshipGetters<TDependentResource> where TDependentResource : class, IIdentifiable
{
/// todo: expose getters that behave something like this:
/// relationshipDictionary.GetAffected( entity => entity.NavigationProperty ).
/// see https://stackoverflow.com/a/17116267/4441216

/// <summary>
/// Gets a dictionary of affected resources grouped by affected relationships.
/// </summary>
Expand All @@ -31,10 +29,11 @@ public interface IByAffectedRelationships<TDependentResource> :
/// <summary>
/// A helper class that provides insights in which relationships have been updated for which entities.
/// </summary>
public interface IRelationshipsDictionary<TDependentResource> :
IRelationshipGetters<TDependentResource>,
IReadOnlyDictionary<RelationshipAttribute, HashSet<TDependentResource>>,
IRelationshipsDictionary where TDependentResource : class, IIdentifiable { }
public interface IRelationshipsDictionary<TDependentResource> :
IRelationshipGetters<TDependentResource>,
IReadOnlyDictionary<RelationshipAttribute, HashSet<TDependentResource>>,
IRelationshipsDictionary where TDependentResource : class, IIdentifiable
{ }

/// <summary>
/// A helper class that provides insights in which relationships have been updated for which entities.
Expand All @@ -49,16 +48,24 @@ public interface IRelationshipGetters<TResource> where TResource : class, IIdent
/// Gets a dictionary of all entities that have an affected relationship to type <paramref name="principalType"/>
/// </summary>
Dictionary<RelationshipAttribute, HashSet<TResource>> GetByRelationship(Type relatedResourceType);

/// <summary>
/// Gets a collection of all the entities for the property within <paramref name="NavigationAction"/>
/// has been affected by the request
/// </summary>
/// <param name="NavigationAction"></param>
HashSet<TResource> GetAffected(Expression<Func<TResource, object>> NavigationAction);
}


/// <summary>
/// Implementation of IAffectedRelationships{TDependentResource}
///
/// It is practically a ReadOnlyDictionary{RelationshipAttribute, HashSet{TDependentResource}} dictionary
/// with the two helper methods defined on IAffectedRelationships{TDependentResource}.
/// </summary>
public class RelationshipsDictionary<TResource> :
Dictionary<RelationshipAttribute, HashSet<TResource>>,
Dictionary<RelationshipAttribute, HashSet<TResource>>,
IRelationshipsDictionary<TResource> where TResource : class, IIdentifiable
{
/// <summary>
Expand All @@ -70,7 +77,7 @@ public RelationshipsDictionary(Dictionary<RelationshipAttribute, HashSet<TResour
/// <summary>
/// Used internally by the ResourceHookExecutor to make live a bit easier with generics
/// </summary>
internal RelationshipsDictionary(Dictionary<RelationshipAttribute, IEnumerable> relationships)
internal RelationshipsDictionary(Dictionary<RelationshipAttribute, IEnumerable> relationships)
: this(TypeHelper.ConvertRelationshipDictionary<TResource>(relationships)) { }

/// <inheritdoc />
Expand All @@ -84,5 +91,12 @@ public Dictionary<RelationshipAttribute, HashSet<TResource>> GetByRelationship(T
{
return this.Where(p => p.Key.DependentType == relatedType).ToDictionary(p => p.Key, p => p.Value);
}

/// <inheritdoc />
public HashSet<TResource> GetAffected(Expression<Func<TResource, object>> NavigationAction)
{
var property = TypeHelper.ParseNavigationExpression(NavigationAction);
return this.Where(p => p.Key.InternalRelationshipName == property.Name).Select(p => p.Value).SingleOrDefault();
}
}
}
Loading