Skip to content

fix(deserializer): skip foreign key if data not in relationship #194

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 2 commits into from
Nov 15, 2017
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
2 changes: 1 addition & 1 deletion src/JsonApiDotNetCore/JsonApiDotNetCore.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<VersionPrefix>2.1.9</VersionPrefix>
<VersionPrefix>2.1.10</VersionPrefix>
<TargetFrameworks>netstandard1.6</TargetFrameworks>
<AssemblyName>JsonApiDotNetCore</AssemblyName>
<PackageId>JsonApiDotNetCore</PackageId>
Expand Down
11 changes: 6 additions & 5 deletions src/JsonApiDotNetCore/Serialization/JsonApiDeSerializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,11 +164,6 @@ private object SetHasOneRelationship(object entity,
ContextEntity contextEntity,
Dictionary<string, RelationshipData> relationships)
{
var entityProperty = entityProperties.FirstOrDefault(p => p.Name == $"{attr.InternalRelationshipName}Id");

if (entityProperty == null)
throw new JsonApiException(400, $"{contextEntity.EntityType.Name} does not contain an relationsip named {attr.InternalRelationshipName}");

var relationshipName = attr.PublicRelationshipName;

if (relationships.TryGetValue(relationshipName, out RelationshipData relationshipData))
Expand All @@ -181,6 +176,12 @@ private object SetHasOneRelationship(object entity,
if (data == null) return entity;

var newValue = data["id"];

var foreignKey = attr.InternalRelationshipName + "Id";
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}'");

var convertedValue = TypeHelper.ConvertType(newValue, entityProperty.PropertyType);

_jsonApiContext.RelationshipsToUpdate[relationshipAttr] = convertedValue;
Expand Down
107 changes: 106 additions & 1 deletion test/UnitTests/Serialization/JsonApiDeSerializerTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System;
using System.Collections.Generic;
using JsonApiDotNetCore.Builders;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Internal.Generics;
Expand Down Expand Up @@ -196,6 +197,98 @@ public void Immutable_Attrs_Are_Not_Included_In_AttributesToUpdate()
Assert.False(attr.Key.IsImmutable);
}

[Fact]
public void Can_Deserialize_Independent_Side_Of_One_To_One_Relationship()
{
// arrange
var contextGraphBuilder = new ContextGraphBuilder();
contextGraphBuilder.AddResource<Independent>("independents");
contextGraphBuilder.AddResource<Dependent>("dependents");
var contextGraph = contextGraphBuilder.Build();

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

var jsonApiOptions = new JsonApiOptions();
jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

var genericProcessorFactoryMock = new Mock<IGenericProcessorFactory>();

var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object, genericProcessorFactoryMock.Object);

var property = Guid.NewGuid().ToString();
var content = new Document
{
Data = new DocumentData
{
Type = "independents",
Id = "1",
Attributes = new Dictionary<string, object> {
{ "property", property }
}
}
};

var contentString = JsonConvert.SerializeObject(content);

// act
var result = deserializer.Deserialize<Independent>(contentString);

// assert
Assert.NotNull(result);
Assert.Equal(property, result.Property);
}

[Fact]
public void Can_Deserialize_Independent_Side_Of_One_To_One_Relationship_With_Relationship_Body()
{
// arrange
var contextGraphBuilder = new ContextGraphBuilder();
contextGraphBuilder.AddResource<Independent>("independents");
contextGraphBuilder.AddResource<Dependent>("dependents");
var contextGraph = contextGraphBuilder.Build();

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

var jsonApiOptions = new JsonApiOptions();
jsonApiContextMock.Setup(m => m.Options).Returns(jsonApiOptions);

var genericProcessorFactoryMock = new Mock<IGenericProcessorFactory>();

var deserializer = new JsonApiDeSerializer(jsonApiContextMock.Object, genericProcessorFactoryMock.Object);

var property = Guid.NewGuid().ToString();
var content = new Document
{
Data = new DocumentData
{
Type = "independents",
Id = "1",
Attributes = new Dictionary<string, object> {
{ "property", property }
},
// a common case for this is deserialization in unit tests
Relationships = new Dictionary<string, RelationshipData> {
{ "dependent", new RelationshipData { } }
}
}
};

var contentString = JsonConvert.SerializeObject(content);

// act
var result = deserializer.Deserialize<Independent>(contentString);

// assert
Assert.NotNull(result);
Assert.Equal(property, result.Property);
}

private class TestResource : Identifiable
{
[Attr("complex-member")]
Expand All @@ -215,5 +308,17 @@ private class ComplexType
{
public string CompoundName { get; set; }
}

private class Independent : Identifiable
{
[Attr("property")] public string Property { get; set; }
[HasOne("dependent")] public Dependent Dependent { get; set; }
}

private class Dependent : Identifiable
{
[HasOne("independent")] public Independent Independent { get; set; }
public int IndependentId { get; set; }
}
}
}