Skip to content

Fix/#218 #284

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 4 commits into from
Jun 5, 2018
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
87 changes: 57 additions & 30 deletions src/JsonApiDotNetCore/Builders/DocumentBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ public class DocumentBuilder : IDocumentBuilder
private readonly IJsonApiContext _jsonApiContext;
private readonly IContextGraph _contextGraph;
private readonly IRequestMeta _requestMeta;
private readonly DocumentBuilderOptions _documentBuilderOptions;
private readonly DocumentBuilderOptions _documentBuilderOptions;

public DocumentBuilder(IJsonApiContext jsonApiContext, IRequestMeta requestMeta=null, IDocumentBuilderOptionsProvider documentBuilderOptionsProvider=null)
public DocumentBuilder(IJsonApiContext jsonApiContext, IRequestMeta requestMeta = null, IDocumentBuilderOptionsProvider documentBuilderOptionsProvider = null)
{
_jsonApiContext = jsonApiContext;
_contextGraph = jsonApiContext.ContextGraph;
Expand Down Expand Up @@ -143,34 +143,42 @@ private bool OmitNullValuedAttribute(AttrAttribute attr, object attributeValue)
private void AddRelationships(DocumentData data, ContextEntity contextEntity, IIdentifiable entity)
{
data.Relationships = new Dictionary<string, RelationshipData>();
contextEntity.Relationships.ForEach(r =>
data.Relationships.Add(
r.PublicRelationshipName,
GetRelationshipData(r, contextEntity, entity)
)
);
}

private RelationshipData GetRelationshipData(RelationshipAttribute attr, ContextEntity contextEntity, IIdentifiable entity)
{
var linkBuilder = new LinkBuilder(_jsonApiContext);

contextEntity.Relationships.ForEach(r =>
var relationshipData = new RelationshipData();

if (attr.DocumentLinks.HasFlag(Link.None) == false)
{
var relationshipData = new RelationshipData();
relationshipData.Links = new Links();
if (attr.DocumentLinks.HasFlag(Link.Self))
relationshipData.Links.Self = linkBuilder.GetSelfRelationLink(contextEntity.EntityName, entity.StringId, attr.PublicRelationshipName);

if (r.DocumentLinks.HasFlag(Link.None) == false)
{
relationshipData.Links = new Links();
if (r.DocumentLinks.HasFlag(Link.Self))
relationshipData.Links.Self = linkBuilder.GetSelfRelationLink(contextEntity.EntityName, entity.StringId, r.PublicRelationshipName);
if (attr.DocumentLinks.HasFlag(Link.Related))
relationshipData.Links.Related = linkBuilder.GetRelatedRelationLink(contextEntity.EntityName, entity.StringId, attr.PublicRelationshipName);
}

if (r.DocumentLinks.HasFlag(Link.Related))
relationshipData.Links.Related = linkBuilder.GetRelatedRelationLink(contextEntity.EntityName, entity.StringId, r.PublicRelationshipName);
}

var navigationEntity = _jsonApiContext.ContextGraph
.GetRelationship(entity, r.InternalRelationshipName);

if (navigationEntity == null)
relationshipData.SingleData = null;
else if (navigationEntity is IEnumerable)
relationshipData.ManyData = GetRelationships((IEnumerable<object>)navigationEntity);
else
relationshipData.SingleData = GetRelationship(navigationEntity);

data.Relationships.Add(r.PublicRelationshipName, relationshipData);
});
// this only includes the navigation property, we need to actually check the navigation property Id
var navigationEntity = _jsonApiContext.ContextGraph.GetRelationship(entity, attr.InternalRelationshipName);
if (navigationEntity == null)
relationshipData.SingleData = attr.IsHasOne
? GetIndependentRelationshipIdentifier((HasOneAttribute)attr, entity)
: null;
else if (navigationEntity is IEnumerable)
relationshipData.ManyData = GetRelationships((IEnumerable<object>)navigationEntity);
else
relationshipData.SingleData = GetRelationship(navigationEntity);

return relationshipData;
}

private List<DocumentData> GetIncludedEntities(List<DocumentData> included, ContextEntity contextEntity, IIdentifiable entity)
Expand Down Expand Up @@ -240,23 +248,42 @@ private List<ResourceIdentifierObject> GetRelationships(IEnumerable<object> enti
var relationships = new List<ResourceIdentifierObject>();
foreach (var entity in entities)
{
relationships.Add(new ResourceIdentifierObject {
relationships.Add(new ResourceIdentifierObject
{
Type = typeName.EntityName,
Id = ((IIdentifiable)entity).StringId
});
}
return relationships;
}

private ResourceIdentifierObject GetRelationship(object entity)
{
var objType = entity.GetType();
var contextEntity = _jsonApiContext.ContextGraph.GetContextEntity(objType);

var typeName = _jsonApiContext.ContextGraph.GetContextEntity(objType);

return new ResourceIdentifierObject {
Type = typeName.EntityName,
return new ResourceIdentifierObject
{
Type = contextEntity.EntityName,
Id = ((IIdentifiable)entity).StringId
};
}

private ResourceIdentifierObject GetIndependentRelationshipIdentifier(HasOneAttribute hasOne, IIdentifiable entity)
{
var independentRelationshipIdentifier = hasOne.GetIdentifiablePropertyValue(entity);
if (independentRelationshipIdentifier == null)
return null;

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

return new ResourceIdentifierObject
{
Type = relatedContextEntity.EntityName,
Id = independentRelationshipIdentifier.ToString()
};
}
}
}
21 changes: 9 additions & 12 deletions src/JsonApiDotNetCore/JsonApiDotNetCore.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>2.2.3</VersionPrefix>
<VersionPrefix>2.2.4</VersionPrefix>
<TargetFrameworks>$(NetStandardVersion)</TargetFrameworks>
<AssemblyName>JsonApiDotNetCore</AssemblyName>
<PackageId>JsonApiDotNetCore</PackageId>
<LangVersion>7.2</LangVersion>
</PropertyGroup>

<PropertyGroup>
Expand All @@ -25,20 +26,16 @@
<PackageReference Include="System.ValueTuple" Version="$(TuplesVersion)" />
</ItemGroup>

<!-- XML documentation -->
<PropertyGroup>
<!--
To generate DocFX documentation on Windows platforms: dotnet build -c Release /p:DocFx=true
-->
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<IsWindows Condition="'$(OS)' == 'Windows_NT'">true</IsWindows>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<GenerateDocumentation Condition="'$(IsWindows)|$(DocFx)' == 'true|true'">true</GenerateDocumentation>
<DocumentationFile>bin\Release\netstandard2.0\JsonApiDotNetCore.xml</DocumentationFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Release|netstandard2.0|AnyCPU'">
<LangVersion>7.2</LangVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(TargetFramework)|$(Platform)'=='Debug|netstandard2.0|AnyCPU'">
<LangVersion>7.2</LangVersion>
</PropertyGroup>
<ItemGroup Condition="$(IsWindows)=='true'">

<ItemGroup Condition="'$(GenerateDocumentation)' == 'true'">
<PackageReference Include="docfx.console" Version="2.33.0" />
</ItemGroup>

Expand Down
65 changes: 58 additions & 7 deletions src/JsonApiDotNetCore/Models/HasOneAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,72 @@ namespace JsonApiDotNetCore.Models
{
public class HasOneAttribute : RelationshipAttribute
{
public HasOneAttribute(string publicName, Link documentLinks = Link.All, bool canInclude = true)
/// <summary>
/// Create a HasOne relational link to another entity
/// </summary>
///
/// <param name="publicName">The relationship name as exposed by the API</param>
/// <param name="documentLinks">Which links are available. Defaults to <see cref="Link.All"/></param>
/// <param name="canInclude">Whether or not this relationship can be included using the <c>?include=public-name</c> query string</param>
/// <param name="withForiegnKey">The foreign key property name. Defaults to <c>"{RelationshipName}Id"</c></param>
///
/// <example>
/// Using an alternative foreign key:
///
/// <code>
/// public class Article : Identifiable
/// {
/// [HasOne("author", withForiegnKey: nameof(AuthorKey)]
/// public Author Author { get; set; }
/// public int AuthorKey { get; set; }
/// }
/// </code>
///
/// </example>
public HasOneAttribute(string publicName, Link documentLinks = Link.All, bool canInclude = true, string withForiegnKey = null)
: base(publicName, documentLinks, canInclude)
{ }
{
_explicitIdentifiablePropertyName = withForiegnKey;
}

private readonly string _explicitIdentifiablePropertyName;

/// <summary>
/// The independent entity identifier.
/// </summary>
public string IdentifiablePropertyName => string.IsNullOrWhiteSpace(_explicitIdentifiablePropertyName)
? $"{InternalRelationshipName}Id"
: _explicitIdentifiablePropertyName;

public override void SetValue(object entity, object newValue)
{
var propertyName = (newValue.GetType() == Type)
? InternalRelationshipName
: $"{InternalRelationshipName}Id";
var propertyName = (newValue.GetType() == Type)
? InternalRelationshipName
: IdentifiablePropertyName;

var propertyInfo = entity
.GetType()
.GetProperty(propertyName);

propertyInfo.SetValue(entity, newValue);
}

// HACK: this will likely require boxing
// we should be able to move some of the reflection into the ContextGraphBuilder
/// <summary>
/// Gets the value of the independent identifier (e.g. Article.AuthorId)
/// </summary>
///
/// <param name="entity">
/// An instance of dependent resource
/// </param>
///
/// <returns>
/// The property value or null if the property does not exist on the model.
/// </returns>
internal object GetIdentifiablePropertyValue(object entity) => entity
.GetType()
.GetProperty(IdentifiablePropertyName)
?.GetValue(entity);
}
}
6 changes: 3 additions & 3 deletions src/JsonApiDotNetCore/Serialization/JsonApiDeSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ private object SetRelationships(
foreach (var attr in contextEntity.Relationships)
{
entity = attr.IsHasOne
? SetHasOneRelationship(entity, entityProperties, attr, contextEntity, relationships)
? SetHasOneRelationship(entity, entityProperties, (HasOneAttribute)attr, contextEntity, relationships)
: SetHasManyRelationship(entity, entityProperties, attr, contextEntity, relationships);
}

Expand All @@ -184,7 +184,7 @@ private object SetRelationships(

private object SetHasOneRelationship(object entity,
PropertyInfo[] entityProperties,
RelationshipAttribute attr,
HasOneAttribute attr,
ContextEntity contextEntity,
Dictionary<string, RelationshipData> relationships)
{
Expand All @@ -204,7 +204,7 @@ private object SetHasOneRelationship(object entity,

var newValue = rio.Id;

var foreignKey = attr.InternalRelationshipName + "Id";
var foreignKey = attr.IdentifiablePropertyName;
var entityProperty = entityProperties.FirstOrDefault(p => p.Name == foreignKey);
if (entityProperty == null)
throw new JsonApiException(400, $"{contextEntity.EntityType.Name} does not contain a foreign key property '{foreignKey}' for has one relationship '{attr.InternalRelationshipName}'");
Expand Down
29 changes: 29 additions & 0 deletions test/UnitTests/Builders/DocumentBuilder_Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,35 @@ public void Related_Data_Included_In_Relationships_By_Default()
// act
var document = documentBuilder.Build(entity);

// assert
var relationshipData = document.Data.Relationships[relationshipName];
Assert.NotNull(relationshipData);
Assert.NotNull(relationshipData.SingleData);
Assert.NotNull(relationshipData.SingleData);
Assert.Equal(relatedId.ToString(), relationshipData.SingleData.Id);
Assert.Equal(relatedTypeName, relationshipData.SingleData.Type);
}

[Fact]
public void IndependentIdentifier__Included_In_HasOne_Relationships_By_Default()
{
// arrange
const string relatedTypeName = "related-models";
const string relationshipName = "related-model";
const int relatedId = 1;
_jsonApiContextMock
.Setup(m => m.ContextGraph)
.Returns(_options.ContextGraph);

var documentBuilder = new DocumentBuilder(_jsonApiContextMock.Object);
var entity = new Model
{
RelatedModelId = relatedId
};

// act
var document = documentBuilder.Build(entity);

// assert
var relationshipData = document.Data.Relationships[relationshipName];
Assert.NotNull(relationshipData);
Expand Down