Skip to content

Commit

Permalink
Add json converter for layoutgroups
Browse files Browse the repository at this point in the history
  • Loading branch information
Roblinde committed Jun 26, 2023
1 parent 410f9cd commit ffa8e05
Show file tree
Hide file tree
Showing 8 changed files with 263 additions and 57 deletions.
10 changes: 5 additions & 5 deletions Contentful.AspNetCore/Contentful.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<Description>Official .NET SDK for the Contentful Content Delivery and Management API for ASP.NET core.</Description>
<PackageId>contentful.aspnetcore</PackageId>
<NeutralLanguage>en-US</NeutralLanguage>
<VersionPrefix>7.2.9</VersionPrefix>
<VersionPrefix>7.2.10</VersionPrefix>
<TargetFramework>netstandard2.0</TargetFramework>
<Authors>Contentful</Authors>
<Copyright>Contentful GmbH.</Copyright>
Expand All @@ -13,10 +13,10 @@
<PackageProjectUrl>https://github.com/contentful/contentful.net</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RepositoryType>git</RepositoryType>
<Version>7.2.9</Version>
<AssemblyVersion>7.2.9.0</AssemblyVersion>
<Version>7.2.10</Version>
<AssemblyVersion>7.2.10.0</AssemblyVersion>
<RepositoryUrl>https://github.com/contentful/contentful.net</RepositoryUrl>
<FileVersion>7.2.9.0</FileVersion>
<FileVersion>7.2.10.0</FileVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DocumentationFile>bin\Release\netstandard1.5\Contentful.AspNetCore.xml</DocumentationFile>
Expand All @@ -25,7 +25,7 @@
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="contentful.csharp" Version="7.2.9" />
<PackageReference Include="contentful.csharp" Version="7.2.10" />
<PackageReference Include="gitlink" Version="3.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
Expand Down
2 changes: 2 additions & 0 deletions Contentful.Core.Tests/Contentful.Core.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<ItemGroup>
<None Remove="JsonFiles\ApiKey.json" />
<None Remove="JsonFiles\ApiUsage.json" />
<None Remove="JsonFiles\EditorInterfaceWithMetadata.json" />
<None Remove="JsonFiles\EntriesCollectionWithCrossReference.json" />
<None Remove="JsonFiles\EntriesCollectionWithRichTextField.json" />
<None Remove="JsonFiles\EntriesCollectionWithRichTextFieldCalledFields.json" />
Expand All @@ -23,6 +24,7 @@
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="JsonFiles\ApiKey.json" />
<EmbeddedResource Include="JsonFiles\EditorInterfaceWithMetadata.json" />
<EmbeddedResource Include="JsonFiles\EntriesCollectionWithCrossReference.json" />
<EmbeddedResource Include="JsonFiles\EntriesCollectionWithRichTextFieldTable.json" />
<EmbeddedResource Include="JsonFiles\EntriesCollectionWithRichTextFieldCalledFields.json" />
Expand Down
16 changes: 16 additions & 0 deletions Contentful.Core.Tests/ContentfulManagementClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,22 @@ public async Task EditorInterfaceShouldDeserializeCorrectly()
Assert.IsType<BooleanEditorInterfaceControlSettings>(res.Controls[4].Settings);
}

[Fact]
public async Task EditorInterfaceShouldDeserializeCorrectlyWithMetadata()
{
//Arrange
_handler.Response = GetResponseFromFile(@"EditorInterfaceWithMetadata.json");

//Act
var res = await _client.GetEditorInterface("someid");

//Assert
Assert.Equal(7, res.Controls.Count);
Assert.Equal(2, res.EditorLayout.Count);
Assert.Equal(2, res.GroupControls.Count);
Assert.IsType<BooleanEditorInterfaceControlSettings>(res.Controls[4].Settings);
}

[Fact]
public async Task CreateSpaceShouldCreateCorrectObject()
{
Expand Down
114 changes: 114 additions & 0 deletions Contentful.Core.Tests/JsonFiles/EditorInterfaceWithMetadata.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
{
"controls": [
{
"fieldId": "field1",
"widgetId": "singleLine"
},
{
"fieldId": "field2",
"widgetId": "locationEditor"
},
{
"fieldId": "field3",
"widgetId": "markdown"
},
{
"fieldId": "field4",
"widgetId": "assetLinkEditor"
},
{
"fieldId": "field5",
"widgetId": "boolean",
"settings": {
"helpText": "Should the post be featured on the homepage?",
"trueLabel": "absolutely",
"falseLabel": "rather not"
}
},
{
"fieldId": "field6",
"widgetId": "rating",
"settings": {
"helpText": "How many do you likez?",
"stars": "7"
}
},
{
"fieldId": "field7",
"widgetId": "datePicker",
"settings": {
"helpText": "When do we should getz?",
"format": "time",
"ampm": "12"
}
}
],
"editorLayout": [
{
"groupId": "content",
"name": "Content",
"items": [
{ "fieldId": "title" },
{ "fieldId": "body" }
]
},
{
"groupId": "settings",
"name": "Settings",
"items": [
{
"groupId": "seo",
"name": "Seo",
"items": [ { "fieldId": "slug" } ]
}
]
}
],
"groupControls": [
{
"groupId": "content",
"widgetId": "topLevelTab",
"widgetNamespace": "builtin"
},
{
"groupId": "settings",
"widgetId": "topLevelTab",
"widgetNamespace": "builtin"
}
],
"sys": {
"id": "default",
"type": "EditorInterface",
"version": 1,
"createdAt": "2016-11-23T07:37:45.356Z",
"createdBy": {
"sys": {
"type": "Link",
"linkType": "User",
"id": "0w7AzFDgzUA8MWo79R1Qf7"
}
},
"space": {
"sys": {
"type": "Link",
"linkType": "Space",
"id": "gw484zixu8ng"
}
},
"contentType": {
"sys": {
"type": "Link",
"linkType": "ContentType",
"id": "testagain"
}
},
"updatedAt": "2016-11-23T07:37:45.357Z",
"updatedBy": {
"sys": {
"type": "Link",
"linkType": "User",
"id": "0w7AzFDgzUA8MWo79R1Qf7"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@
namespace Contentful.Core.Configuration
{
/// <summary>
/// JsonConverter for converting <see cref="Contentful.Core.Models.Management.EditorInterface"/>.
/// JsonConverter for converting <see cref="Contentful.Core.Models.Management.EditorLayoutGroup"/>.
/// </summary>
public class EditorInterfaceControlJsonConverter : JsonConverter
public class EditorLayoutGroupJsonConverter : JsonConverter
{
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">The type to convert to.</param>
public override bool CanConvert(Type objectType) => objectType == typeof(EditorInterfaceControl);
public override bool CanConvert(Type objectType) => objectType == typeof(EditorLayoutGroup);

/// <summary>
/// Gets a value indicating whether this JsonConverter can write JSON.
Expand All @@ -38,60 +38,24 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
return null;

var jsonObject = JObject.Load(reader);
var settings = new EditorInterfaceControlSettings();

var editorInterfaceControl = new EditorInterfaceControl()
{
FieldId = jsonObject["fieldId"]?.ToString(),
WidgetId = jsonObject["widgetId"]?.ToString()
};

if (jsonObject["settings"] == null)
{
return editorInterfaceControl;
}

if (jsonObject["widgetId"]?.ToString() == "boolean")
{
var boolSettings = new BooleanEditorInterfaceControlSettings()
{
FalseLabel = jsonObject["settings"]?["falseLabel"]?.ToString(),
TrueLabel = jsonObject["settings"]?["trueLabel"]?.ToString()
};
settings = boolSettings;
}

if (jsonObject["widgetId"]?.ToString() == "rating")
var group = new EditorLayoutGroup();
group.GroupId = jsonObject["groupId"].Value<string>();
group.Name = jsonObject["name"].Value<string>();
group.Items = new List<IEditorLayoutGroupItem>();
foreach (var item in jsonObject["items"])
{
var ratingSettings = new RatingEditorInterfaceControlSettings();

var stars = 0;

if (!int.TryParse(jsonObject["settings"]?["stars"]?.ToString(), out stars))
if(item["fieldId"] != null)
{
stars = 5;
group.Items.Add(item.ToObject<EditorLayoutFieldItem>());
}

ratingSettings.NumberOfStars = stars;

settings = ratingSettings;
}

if (jsonObject["widgetId"]?.ToString() == "datePicker")
{
var dateSettings = new DatePickerEditorInterfaceControlSettings()
else
{
ClockFormat = jsonObject["settings"]?["ampm"]?.ToString(),
DateFormat = (EditorInterfaceDateFormat)Enum.Parse(typeof(EditorInterfaceDateFormat), jsonObject["settings"]?["format"]?.ToString(), true)
};
settings = dateSettings;
group.Items.Add(item.ToObject<EditorLayoutGroup>());
}
}


settings.HelpText = jsonObject["settings"]?["helpText"]?.ToString();

editorInterfaceControl.Settings = settings;

return editorInterfaceControl;
return group;
}

/// <summary>
Expand Down
109 changes: 109 additions & 0 deletions Contentful.Core/Configuration/EditorLayoutGroupJsonConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
using Contentful.Core.Models;
using Contentful.Core.Models.Management;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;

namespace Contentful.Core.Configuration
{
/// <summary>
/// JsonConverter for converting <see cref="Contentful.Core.Models.Management.EditorInterface"/>.
/// </summary>
public class EditorInterfaceControlJsonConverter : JsonConverter
{
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">The type to convert to.</param>
public override bool CanConvert(Type objectType) => objectType == typeof(EditorInterfaceControl);

/// <summary>
/// Gets a value indicating whether this JsonConverter can write JSON.
/// </summary>
public override bool CanWrite => false;

/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The reader to use.</param>
/// <param name="objectType">The object type to serialize into.</param>
/// <param name="existingValue">The current value of the property.</param>
/// <param name="serializer">The serializer to use.</param>
/// <returns>The deserialized <see cref="Asset"/>.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;

var jsonObject = JObject.Load(reader);
var settings = new EditorInterfaceControlSettings();

var editorInterfaceControl = new EditorInterfaceControl()
{
FieldId = jsonObject["fieldId"]?.ToString(),
WidgetId = jsonObject["widgetId"]?.ToString()
};

if (jsonObject["settings"] == null)
{
return editorInterfaceControl;
}

if (jsonObject["widgetId"]?.ToString() == "boolean")
{
var boolSettings = new BooleanEditorInterfaceControlSettings()
{
FalseLabel = jsonObject["settings"]?["falseLabel"]?.ToString(),
TrueLabel = jsonObject["settings"]?["trueLabel"]?.ToString()
};
settings = boolSettings;
}

if (jsonObject["widgetId"]?.ToString() == "rating")
{
var ratingSettings = new RatingEditorInterfaceControlSettings();

var stars = 0;

if (!int.TryParse(jsonObject["settings"]?["stars"]?.ToString(), out stars))
{
stars = 5;
}

ratingSettings.NumberOfStars = stars;

settings = ratingSettings;
}

if (jsonObject["widgetId"]?.ToString() == "datePicker")
{
var dateSettings = new DatePickerEditorInterfaceControlSettings()
{
ClockFormat = jsonObject["settings"]?["ampm"]?.ToString(),
DateFormat = (EditorInterfaceDateFormat)Enum.Parse(typeof(EditorInterfaceDateFormat), jsonObject["settings"]?["format"]?.ToString(), true)
};
settings = dateSettings;
}

settings.HelpText = jsonObject["settings"]?["helpText"]?.ToString();

editorInterfaceControl.Settings = settings;

return editorInterfaceControl;
}

/// <summary>
/// Writes the JSON representation of the object.
/// **NOTE: This method is not implemented and will throw an exception.**
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="serializer"></param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
}
2 changes: 1 addition & 1 deletion Contentful.Core/Contentful.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<PackageId>contentful.csharp</PackageId>
<AssemblyTitle>contentful.net</AssemblyTitle>
<NeutralLanguage>en-US</NeutralLanguage>
<VersionPrefix>7.2.9</VersionPrefix>
<VersionPrefix>7.2.10</VersionPrefix>
<TargetFramework>netstandard2.0</TargetFramework>
<Authors>Contentful</Authors>
<Copyright>Contentful GmbH.</Copyright>
Expand Down
Loading

0 comments on commit ffa8e05

Please sign in to comment.