Skip to content

Commit

Permalink
Merge pull request #428 from json-api-dotnet/rename-context-graph
Browse files Browse the repository at this point in the history
rename contextGraph to resourceGraph
  • Loading branch information
jaredcnance authored Oct 15, 2018
2 parents cbc37d1 + 2547678 commit 8570b21
Show file tree
Hide file tree
Showing 41 changed files with 466 additions and 451 deletions.
8 changes: 4 additions & 4 deletions benchmarks/Serialization/JsonApiDeserializer_Benchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ public class JsonApiDeserializer_Benchmarks {
private readonly JsonApiDeSerializer _jsonApiDeSerializer;

public JsonApiDeserializer_Benchmarks() {
var contextGraphBuilder = new ContextGraphBuilder();
contextGraphBuilder.AddResource<SimpleType>(TYPE_NAME);
var contextGraph = contextGraphBuilder.Build();
var resourceGraphBuilder = new ResourceGraphBuilder();
resourceGraphBuilder.AddResource<SimpleType>(TYPE_NAME);
var resourceGraph = resourceGraphBuilder.Build();

var jsonApiContextMock = new Mock<IJsonApiContext>();
jsonApiContextMock.SetupAllProperties();
jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
jsonApiContextMock.Setup(m => m.ResourceGraph).Returns(resourceGraph);
jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary<AttrAttribute, object>());

var jsonApiOptions = new JsonApiOptions();
Expand Down
8 changes: 4 additions & 4 deletions benchmarks/Serialization/JsonApiSerializer_Benchmarks.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ public class JsonApiSerializer_Benchmarks {
private readonly JsonApiSerializer _jsonApiSerializer;

public JsonApiSerializer_Benchmarks() {
var contextGraphBuilder = new ContextGraphBuilder();
contextGraphBuilder.AddResource<SimpleType>(TYPE_NAME);
var contextGraph = contextGraphBuilder.Build();
var resourceGraphBuilder = new ResourceGraphBuilder();
resourceGraphBuilder.AddResource<SimpleType>(TYPE_NAME);
var resourceGraph = resourceGraphBuilder.Build();

var jsonApiContextMock = new Mock<IJsonApiContext>();
jsonApiContextMock.SetupAllProperties();
jsonApiContextMock.Setup(m => m.ContextGraph).Returns(contextGraph);
jsonApiContextMock.Setup(m => m.ResourceGraph).Returns(resourceGraph);
jsonApiContextMock.Setup(m => m.AttributesToUpdate).Returns(new Dictionary<AttrAttribute, object>());

var jsonApiOptions = new JsonApiOptions();
Expand Down
2 changes: 1 addition & 1 deletion src/Examples/NoEntityFrameworkExample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ public virtual IServiceProvider ConfigureServices(IServiceCollection services)

services.AddJsonApi(options => {
options.Namespace = "api/v1";
options.BuildContextGraph((builder) => {
options.BuildResourceGraph((builder) => {
builder.AddResource<TodoItem>("custom-todo-items");
});
}, mvcBuilder);
Expand Down
2 changes: 1 addition & 1 deletion src/Examples/ResourceEntitySeparationExample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public virtual IServiceProvider ConfigureServices(IServiceCollection services)
options.Namespace = "api/v1";
options.DefaultPageSize = 10;
options.IncludeTotalRecordCount = true;
options.BuildContextGraph((builder) => {
options.BuildResourceGraph((builder) => {
builder.AddResource<CourseResource>("courses");
builder.AddResource<DepartmentResource>("departments");
builder.AddResource<StudentResource>("students");
Expand Down
32 changes: 16 additions & 16 deletions src/JsonApiDotNetCore/Builders/ContextGraphBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@

namespace JsonApiDotNetCore.Builders
{
public interface IContextGraphBuilder
public interface IResourceGraphBuilder
{
/// <summary>
/// Construct the <see cref="ContextGraph"/>
/// Construct the <see cref="ResourceGraph"/>
/// </summary>
IContextGraph Build();
IResourceGraph Build();

/// <summary>
/// Add a json:api resource
Expand All @@ -29,7 +29,7 @@ public interface IContextGraphBuilder
/// If nothing is specified, the configured name formatter will be used.
/// See <see cref="JsonApiOptions.ResourceNameFormatter" />.
/// </param>
IContextGraphBuilder AddResource<TResource>(string pluralizedTypeName = null) where TResource : class, IIdentifiable<int>;
IResourceGraphBuilder AddResource<TResource>(string pluralizedTypeName = null) where TResource : class, IIdentifiable<int>;

/// <summary>
/// Add a json:api resource
Expand All @@ -41,7 +41,7 @@ public interface IContextGraphBuilder
/// If nothing is specified, the configured name formatter will be used.
/// See <see cref="JsonApiOptions.ResourceNameFormatter" />.
/// </param>
IContextGraphBuilder AddResource<TResource, TId>(string pluralizedTypeName = null) where TResource : class, IIdentifiable<TId>;
IResourceGraphBuilder AddResource<TResource, TId>(string pluralizedTypeName = null) where TResource : class, IIdentifiable<TId>;

/// <summary>
/// Add a json:api resource
Expand All @@ -53,28 +53,28 @@ public interface IContextGraphBuilder
/// If nothing is specified, the configured name formatter will be used.
/// See <see cref="JsonApiOptions.ResourceNameFormatter" />.
/// </param>
IContextGraphBuilder AddResource(Type entityType, Type idType, string pluralizedTypeName = null);
IResourceGraphBuilder AddResource(Type entityType, Type idType, string pluralizedTypeName = null);

/// <summary>
/// Add all the models that are part of the provided <see cref="DbContext" />
/// that also implement <see cref="IIdentifiable"/>
/// </summary>
/// <typeparam name="T">The <see cref="DbContext"/> implementation type.</typeparam>
IContextGraphBuilder AddDbContext<T>() where T : DbContext;
IResourceGraphBuilder AddDbContext<T>() where T : DbContext;

/// <summary>
/// Specify the <see cref="IResourceNameFormatter"/> used to format resource names.
/// </summary>
/// <param name="resourceNameFormatter">Formatter used to define exposed resource names by convention.</param>
IContextGraphBuilder UseNameFormatter(IResourceNameFormatter resourceNameFormatter);
IResourceGraphBuilder UseNameFormatter(IResourceNameFormatter resourceNameFormatter);

/// <summary>
/// Which links to include. Defaults to <see cref="Link.All"/>.
/// </summary>
Link DocumentLinks { get; set; }
}

public class ContextGraphBuilder : IContextGraphBuilder
public class ResourceGraphBuilder : IResourceGraphBuilder
{
private List<ContextEntity> _entities = new List<ContextEntity>();
private List<ValidationResult> _validationResults = new List<ValidationResult>();
Expand All @@ -83,25 +83,25 @@ public class ContextGraphBuilder : IContextGraphBuilder

public Link DocumentLinks { get; set; } = Link.All;

public IContextGraph Build()
public IResourceGraph Build()
{
// this must be done at build so that call order doesn't matter
_entities.ForEach(e => e.Links = GetLinkFlags(e.EntityType));

var graph = new ContextGraph(_entities, _usesDbContext, _validationResults);
var graph = new ResourceGraph(_entities, _usesDbContext, _validationResults);
return graph;
}

/// <inheritdoc />
public IContextGraphBuilder AddResource<TResource>(string pluralizedTypeName = null) where TResource : class, IIdentifiable<int>
public IResourceGraphBuilder AddResource<TResource>(string pluralizedTypeName = null) where TResource : class, IIdentifiable<int>
=> AddResource<TResource, int>(pluralizedTypeName);

/// <inheritdoc />
public IContextGraphBuilder AddResource<TResource, TId>(string pluralizedTypeName = null) where TResource : class, IIdentifiable<TId>
public IResourceGraphBuilder AddResource<TResource, TId>(string pluralizedTypeName = null) where TResource : class, IIdentifiable<TId>
=> AddResource(typeof(TResource), typeof(TId), pluralizedTypeName);

/// <inheritdoc />
public IContextGraphBuilder AddResource(Type entityType, Type idType, string pluralizedTypeName = null)
public IResourceGraphBuilder AddResource(Type entityType, Type idType, string pluralizedTypeName = null)
{
AssertEntityIsNotAlreadyDefined(entityType);

Expand Down Expand Up @@ -222,7 +222,7 @@ protected virtual Type GetRelationshipType(RelationshipAttribute relation, Prope
private Type GetResourceDefinitionType(Type entityType) => typeof(ResourceDefinition<>).MakeGenericType(entityType);

/// <inheritdoc />
public IContextGraphBuilder AddDbContext<T>() where T : DbContext
public IResourceGraphBuilder AddDbContext<T>() where T : DbContext
{
_usesDbContext = true;

Expand Down Expand Up @@ -290,7 +290,7 @@ private void AssertEntityIsNotAlreadyDefined(Type entityType)
}

/// <inheritdoc />
public IContextGraphBuilder UseNameFormatter(IResourceNameFormatter resourceNameFormatter)
public IResourceGraphBuilder UseNameFormatter(IResourceNameFormatter resourceNameFormatter)
{
_resourceNameFormatter = resourceNameFormatter;
return this;
Expand Down
22 changes: 11 additions & 11 deletions src/JsonApiDotNetCore/Builders/DocumentBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace JsonApiDotNetCore.Builders
public class DocumentBuilder : IDocumentBuilder
{
private readonly IJsonApiContext _jsonApiContext;
private readonly IContextGraph _contextGraph;
private readonly IResourceGraph _resourceGraph;
private readonly IRequestMeta _requestMeta;
private readonly DocumentBuilderOptions _documentBuilderOptions;
private readonly IScopedServiceProvider _scopedServiceProvider;
Expand All @@ -24,15 +24,15 @@ public DocumentBuilder(
IScopedServiceProvider scopedServiceProvider = null)
{
_jsonApiContext = jsonApiContext;
_contextGraph = jsonApiContext.ContextGraph;
_resourceGraph = jsonApiContext.ResourceGraph;
_requestMeta = requestMeta;
_documentBuilderOptions = documentBuilderOptionsProvider?.GetDocumentBuilderOptions() ?? new DocumentBuilderOptions();
_scopedServiceProvider = scopedServiceProvider;
}

public Document Build(IIdentifiable entity)
{
var contextEntity = _contextGraph.GetContextEntity(entity.GetType());
var contextEntity = _resourceGraph.GetContextEntity(entity.GetType());

var resourceDefinition = _scopedServiceProvider?.GetService(contextEntity.ResourceType) as IResourceDefinition;
var document = new Document
Expand All @@ -52,7 +52,7 @@ public Document Build(IIdentifiable entity)
public Documents Build(IEnumerable<IIdentifiable> entities)
{
var entityType = entities.GetElementType();
var contextEntity = _contextGraph.GetContextEntity(entityType);
var contextEntity = _resourceGraph.GetContextEntity(entityType);
var resourceDefinition = _scopedServiceProvider?.GetService(contextEntity.ResourceType) as IResourceDefinition;

var enumeratedEntities = entities as IList<IIdentifiable> ?? entities.ToList();
Expand Down Expand Up @@ -179,7 +179,7 @@ private RelationshipData GetRelationshipData(RelationshipAttribute attr, Context
}

// this only includes the navigation property, we need to actually check the navigation property Id
var navigationEntity = _jsonApiContext.ContextGraph.GetRelationshipValue(entity, attr);
var navigationEntity = _jsonApiContext.ResourceGraph.GetRelationshipValue(entity, attr);
if (navigationEntity == null)
relationshipData.SingleData = attr.IsHasOne
? GetIndependentRelationshipIdentifier((HasOneAttribute)attr, entity)
Expand Down Expand Up @@ -217,7 +217,7 @@ private List<ResourceObject> IncludeRelationshipChain(
if(relationship == null)
throw new JsonApiException(400, $"{parentEntity.EntityName} does not contain relationship {requestedRelationship}");

var navigationEntity = _jsonApiContext.ContextGraph.GetRelationshipValue(parentResource, relationship);
var navigationEntity = _jsonApiContext.ResourceGraph.GetRelationshipValue(parentResource, relationship);
if (navigationEntity is IEnumerable hasManyNavigationEntity)
{
foreach (IIdentifiable includedEntity in hasManyNavigationEntity)
Expand All @@ -240,7 +240,7 @@ private List<ResourceObject> IncludeSingleResourceRelationships(
{
if (relationshipChainIndex < relationshipChain.Length)
{
var nextContextEntity = _jsonApiContext.ContextGraph.GetContextEntity(relationship.Type);
var nextContextEntity = _jsonApiContext.ResourceGraph.GetContextEntity(relationship.Type);
var resource = (IIdentifiable)navigationEntity;
// recursive call
if (relationshipChainIndex < relationshipChain.Length - 1)
Expand Down Expand Up @@ -271,7 +271,7 @@ private ResourceObject GetIncludedEntity(IIdentifiable entity)
{
if (entity == null) return null;

var contextEntity = _jsonApiContext.ContextGraph.GetContextEntity(entity.GetType());
var contextEntity = _jsonApiContext.ResourceGraph.GetContextEntity(entity.GetType());
var resourceDefinition = _scopedServiceProvider.GetService(contextEntity.ResourceType) as IResourceDefinition;

var data = GetData(contextEntity, entity, resourceDefinition);
Expand All @@ -296,7 +296,7 @@ private List<ResourceIdentifierObject> GetRelationships(IEnumerable<object> enti
// so, we just lookup the type of the first entity on the graph
// this is better than trying to get it from the generic parameter since it could
// be less specific than what is registered on the graph (e.g. IEnumerable<object>)
typeName = typeName ?? _jsonApiContext.ContextGraph.GetContextEntity(entity.GetType()).EntityName;
typeName = typeName ?? _jsonApiContext.ResourceGraph.GetContextEntity(entity.GetType()).EntityName;
relationships.Add(new ResourceIdentifierObject
{
Type = typeName,
Expand All @@ -309,7 +309,7 @@ private List<ResourceIdentifierObject> GetRelationships(IEnumerable<object> enti
private ResourceIdentifierObject GetRelationship(object entity)
{
var objType = entity.GetType();
var contextEntity = _jsonApiContext.ContextGraph.GetContextEntity(objType);
var contextEntity = _jsonApiContext.ResourceGraph.GetContextEntity(objType);

if (entity is IIdentifiable identifiableEntity)
return new ResourceIdentifierObject
Expand All @@ -327,7 +327,7 @@ private ResourceIdentifierObject GetIndependentRelationshipIdentifier(HasOneAttr
if (independentRelationshipIdentifier == null)
return null;

var relatedContextEntity = _jsonApiContext.ContextGraph.GetContextEntity(hasOne.Type);
var relatedContextEntity = _jsonApiContext.ResourceGraph.GetContextEntity(hasOne.Type);
if (relatedContextEntity == null) // TODO: this should probably be a debug log at minimum
return null;

Expand Down
18 changes: 9 additions & 9 deletions src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public class JsonApiOptions
/// <summary>
/// The graph of all resources exposed by this application.
/// </summary>
public IContextGraph ContextGraph { get; set; }
public IResourceGraph ResourceGraph { get; set; }

/// <summary>
/// Use relative links for all resources.
Expand Down Expand Up @@ -158,28 +158,28 @@ public IContractResolver JsonContractResolver
ContractResolver = new DasherizedResolver()
};

public void BuildContextGraph<TContext>(Action<IContextGraphBuilder> builder) where TContext : DbContext
public void BuildResourceGraph<TContext>(Action<IResourceGraphBuilder> builder) where TContext : DbContext
{
BuildContextGraph(builder);
BuildResourceGraph(builder);

ContextGraphBuilder.AddDbContext<TContext>();
ResourceGraphBuilder.AddDbContext<TContext>();

ContextGraph = ContextGraphBuilder.Build();
ResourceGraph = ResourceGraphBuilder.Build();
}

public void BuildContextGraph(Action<IContextGraphBuilder> builder)
public void BuildResourceGraph(Action<IResourceGraphBuilder> builder)
{
if (builder == null) return;

builder(ContextGraphBuilder);
builder(ResourceGraphBuilder);

ContextGraph = ContextGraphBuilder.Build();
ResourceGraph = ResourceGraphBuilder.Build();
}

public void EnableExtension(JsonApiExtension extension)
=> EnabledExtensions.Add(extension);

internal IContextGraphBuilder ContextGraphBuilder { get; } = new ContextGraphBuilder();
internal IResourceGraphBuilder ResourceGraphBuilder { get; } = new ResourceGraphBuilder();
internal List<JsonApiExtension> EnabledExtensions { get; set; } = new List<JsonApiExtension>();
}
}
4 changes: 2 additions & 2 deletions src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ public virtual async Task<IActionResult> PostAsync([FromBody] T entity)
return Forbidden();

if (_jsonApiContext.Options.ValidateModelState && !ModelState.IsValid)
return UnprocessableEntity(ModelState.ConvertToErrorCollection<T>(_jsonApiContext.ContextGraph));
return UnprocessableEntity(ModelState.ConvertToErrorCollection<T>(_jsonApiContext.ResourceGraph));

entity = await _create.CreateAsync(entity);

Expand All @@ -171,7 +171,7 @@ public virtual async Task<IActionResult> PatchAsync(TId id, [FromBody] T entity)
return UnprocessableEntity();

if (_jsonApiContext.Options.ValidateModelState && !ModelState.IsValid)
return UnprocessableEntity(ModelState.ConvertToErrorCollection<T>(_jsonApiContext.ContextGraph));
return UnprocessableEntity(ModelState.ConvertToErrorCollection<T>(_jsonApiContext.ResourceGraph));

var updatedEntity = await _update.UpdateAsync(id, entity);

Expand Down
2 changes: 1 addition & 1 deletion src/JsonApiDotNetCore/Data/DefaultEntityRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ public virtual IQueryable<TEntity> Include(IQueryable<TEntity> entities, string
: $"{internalRelationshipPath}.{relationship.RelationshipPath}";

if(i < relationshipChain.Length)
entity = _jsonApiContext.ContextGraph.GetContextEntity(relationship.Type);
entity = _jsonApiContext.ResourceGraph.GetContextEntity(relationship.Type);
}

return entities.Include(internalRelationshipPath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static class IApplicationBuilderExtensions
public static IApplicationBuilder UseJsonApi(this IApplicationBuilder app, bool useMvc = true)
{
DisableDetailedErrorsIfProduction(app);
LogContextGraphValidations(app);
LogResourceGraphValidations(app);

app.UseMiddleware<RequestMiddleware>();

Expand All @@ -35,14 +35,14 @@ private static void DisableDetailedErrorsIfProduction(IApplicationBuilder app)
}
}

private static void LogContextGraphValidations(IApplicationBuilder app)
private static void LogResourceGraphValidations(IApplicationBuilder app)
{
var logger = app.ApplicationServices.GetService(typeof(ILogger<ContextGraphBuilder>)) as ILogger;
var contextGraph = app.ApplicationServices.GetService(typeof(IContextGraph)) as ContextGraph;
var logger = app.ApplicationServices.GetService(typeof(ILogger<ResourceGraphBuilder>)) as ILogger;
var resourceGraph = app.ApplicationServices.GetService(typeof(IResourceGraph)) as ResourceGraph;

if (logger != null && contextGraph != null)
if (logger != null && resourceGraph != null)
{
contextGraph.ValidationResults.ForEach((v) =>
resourceGraph.ValidationResults.ForEach((v) =>
logger.Log(
v.LogLevel,
new EventId(),
Expand Down
Loading

0 comments on commit 8570b21

Please sign in to comment.