Skip to content

Commit

Permalink
chore: ran cleanup on new code
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Whittington committed Oct 7, 2024
1 parent 316489c commit ef539f8
Show file tree
Hide file tree
Showing 8 changed files with 109 additions and 106 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
using Polly;
using System.Net;
using Polly;
using Polly.Extensions.Http;

namespace Dfe.ContentSupport.Web.Extensions;

public static class CsHttpClientPolicyExtensions
{
public static void AddRetryPolicy(IHttpClientBuilder builder) =>
public static void AddRetryPolicy(IHttpClientBuilder builder)
{
builder
.SetHandlerLifetime(TimeSpan.FromMinutes(5))
.AddPolicyHandler(GetRetryPolicy());
}

public static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy() =>
HttpPolicyExtensions.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == System.Net.HttpStatusCode.NotFound)
public static IAsyncPolicy<HttpResponseMessage> GetRetryPolicy()
{
return HttpPolicyExtensions.HandleTransientHttpError()
.OrResult(msg => msg.StatusCode == HttpStatusCode.NotFound)
.WaitAndRetryAsync(6, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,21 +45,21 @@ public static void SetupContentfulClient(this IServiceCollection services,
sp.GetRequiredService<IOptions<ContentfulOptions>>().Value);

services.AddKeyedScoped<IContentfulClient, ContentfulClient>(ContentAndSupportServiceKey,
implementationFactory: (sp, _) =>
(sp, _) =>
{
var contentfulOptions = sp.GetRequiredKeyedService<Func<IServiceProvider, ContentfulOptions>>(ContentAndSupportServiceKey)(sp);
var contentfulOptions =
sp.GetRequiredKeyedService<Func<IServiceProvider, ContentfulOptions>>(
ContentAndSupportServiceKey)(sp);
var httpClient = sp.GetRequiredService<HttpClient>();
return new ContentfulClient(httpClient, contentfulOptions);
});

if (app.Environment.EnvironmentName.Equals("e2e"))
{
services.AddKeyedScoped<IContentfulService, StubContentfulService>(ContentAndSupportServiceKey);
}
services.AddKeyedScoped<IContentfulService, StubContentfulService>(
ContentAndSupportServiceKey);
else
{
services.AddKeyedScoped<IContentfulService, ContentfulService>(ContentAndSupportServiceKey);
}
services.AddKeyedScoped<IContentfulService, ContentfulService>(
ContentAndSupportServiceKey);

CsHttpClientPolicyExtensions.AddRetryPolicy(services.AddHttpClient<ContentfulClient>());
}
Expand Down
10 changes: 2 additions & 8 deletions src/Dfe.ContentSupport.Web/Services/ContentService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,20 +55,14 @@ public async Task<List<CsPage>> GetContentSupportPages(
if (!isPreview)
{
var fromCache = cache.GetFromCache(key);
if (fromCache is not null)
{
return fromCache;
}
if (fromCache is not null) return fromCache;
}


var result = await contentfulService.GetContentSupportPages(field, value);
var pages = modelMapper.MapToCsPages(result);

if (!isPreview)
{
cache.AddToCache(key, pages);
}
if (!isPreview) cache.AddToCache(key, pages);

return pages;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Dfe.ContentSupport.Web/Services/CsPagesCacheService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void AddToCache(string key, List<CsPage> item)
}

public void ClearCache()
{
{
(cache as MemoryCache)?.Clear();
}
}
2 changes: 1 addition & 1 deletion src/Dfe.ContentSupport.Web/Services/ICacheService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

public interface ICacheService<T>
{
void AddToCache(string key,T item);
void AddToCache(string key, T item);
T? GetFromCache(string key);
void ClearCache();
}
161 changes: 81 additions & 80 deletions src/Dfe.ContentSupport.Web/Services/ModelMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Dfe.ContentSupport.Web.Models.Mapped.Standard;
using Dfe.ContentSupport.Web.Models.Mapped.Types;
using Dfe.ContentSupport.Web.ViewModels;
using Hyperlink = Dfe.ContentSupport.Web.Models.Mapped.Standard.Hyperlink;

namespace Dfe.ContentSupport.Web.Services;

Expand All @@ -17,41 +18,9 @@ public List<CsPage> MapToCsPages(IEnumerable<ContentSupportPage> incoming)
return incoming.Select(MapToCsPage).ToList();
}

public CsPage MapToCsPage(ContentSupportPage incoming)
{
CsPage result = new CsPage
{
Heading = incoming.Heading,
Slug = incoming.Slug,
IsSitemap = incoming.IsSitemap,
HasCitation = incoming.HasCitation,
HasBackToTop = incoming.HasBackToTop,
HasFeedbackBanner = incoming.HasFeedbackBanner,
HasPrint = incoming.HasPrint,
Content = MapEntriesToContent(incoming.Content),
ShowVerticalNavigation = incoming.ShowVerticalNavigation,
CreatedAt = incoming.SystemProperties.CreatedAt,
UpdatedAt = incoming.SystemProperties.UpdatedAt,
Tags = FlattenMetadata(incoming.Metadata)
};
return result;
}

private static List<string> FlattenMetadata(ContentfulMetadata item)
{
if (item is null) return [];

return item.Tags.Select(o => o.Sys.Id).ToList();
}

private List<CsContentItem> MapEntriesToContent(List<Entry> entries)
{
return entries.Select(ConvertEntryToContentItem).ToList();
}

public CsContentItem ConvertEntryToContentItem(Entry entry)
{
CsContentItem item = entry.RichText is not null
var item = entry.RichText is not null
? MapRichTextContent(entry.RichText, entry)!
: new CsContentItem
{
Expand All @@ -61,24 +30,6 @@ public CsContentItem ConvertEntryToContentItem(Entry entry)
return item;
}

public RichTextContentItem? MapRichTextContent(ContentItemBase? richText, Entry entry)
{
if (richText is null) return null;
RichTextContentItem item =
new RichTextContentItem
{
InternalName = entry.InternalName,
Slug = entry.Slug,
Title = entry.Title,
Subtitle = entry.Subtitle,
UseParentHero = entry.UseParentHero,
NodeType = ConvertToRichTextNodeType(richText.NodeType),
Content = MapRichTextNodes(richText.Content),
Tags = FlattenMetadata(entry.Metadata)
};
return item;
}

public List<RichTextContentItem> MapRichTextNodes(List<ContentItem> nodes)
{
return nodes.Select(node => MapContent(node) ?? new RichTextContentItem
Expand All @@ -103,7 +54,7 @@ public List<RichTextContentItem> MapRichTextNodes(List<ContentItem> nodes)
break;
case RichTextNodeType.Hyperlink:
var uri = contentItem.Data.Uri.ToString();
item = new Models.Mapped.Standard.Hyperlink
item = new Hyperlink
{
Uri = uri,
IsVimeo = uri.Contains("vimeo.com")
Expand Down Expand Up @@ -174,6 +125,84 @@ public List<RichTextContentItem> MapRichTextNodes(List<ContentItem> nodes)
};
}

public RichTextNodeType ConvertToRichTextNodeType(string str)
{
return str switch
{
RichTextTags.Document => RichTextNodeType.Document,
RichTextTags.Paragraph => RichTextNodeType.Paragraph,
RichTextTags.Heading2 => RichTextNodeType.Heading2,
RichTextTags.Heading3 => RichTextNodeType.Heading3,
RichTextTags.Heading4 => RichTextNodeType.Heading4,
RichTextTags.Heading5 => RichTextNodeType.Heading5,
RichTextTags.Heading6 => RichTextNodeType.Heading6,
RichTextTags.UnorderedList => RichTextNodeType.UnorderedList,
RichTextTags.OrderedList => RichTextNodeType.OrderedList,
RichTextTags.ListItem => RichTextNodeType.ListItem,
RichTextTags.Hyperlink => RichTextNodeType.Hyperlink,
RichTextTags.Table => RichTextNodeType.Table,
RichTextTags.TableRow => RichTextNodeType.TableRow,
RichTextTags.TableHeaderCell => RichTextNodeType.TableHeaderCell,
RichTextTags.TableCell => RichTextNodeType.TableCell,
RichTextTags.Hr => RichTextNodeType.Hr,
RichTextTags.EmbeddedAsset => RichTextNodeType.EmbeddedAsset,
RichTextTags.Text => RichTextNodeType.Text,
RichTextTags.EmbeddedEntry or RichTextTags.EmbeddedEntryInline => RichTextNodeType
.EmbeddedEntry,
_ => RichTextNodeType.Unknown
};
}

public CsPage MapToCsPage(ContentSupportPage incoming)
{
var result = new CsPage
{
Heading = incoming.Heading,
Slug = incoming.Slug,
IsSitemap = incoming.IsSitemap,
HasCitation = incoming.HasCitation,
HasBackToTop = incoming.HasBackToTop,
HasFeedbackBanner = incoming.HasFeedbackBanner,
HasPrint = incoming.HasPrint,
Content = MapEntriesToContent(incoming.Content),
ShowVerticalNavigation = incoming.ShowVerticalNavigation,
CreatedAt = incoming.SystemProperties.CreatedAt,
UpdatedAt = incoming.SystemProperties.UpdatedAt,
Tags = FlattenMetadata(incoming.Metadata)
};
return result;
}

private static List<string> FlattenMetadata(ContentfulMetadata item)
{
if (item is null) return [];

return item.Tags.Select(o => o.Sys.Id).ToList();
}

private List<CsContentItem> MapEntriesToContent(List<Entry> entries)
{
return entries.Select(ConvertEntryToContentItem).ToList();
}

public RichTextContentItem? MapRichTextContent(ContentItemBase? richText, Entry entry)
{
if (richText is null) return null;
var item =
new RichTextContentItem
{
InternalName = entry.InternalName,
Slug = entry.Slug,
Title = entry.Title,
Subtitle = entry.Subtitle,
UseParentHero = entry.UseParentHero,
NodeType = ConvertToRichTextNodeType(richText.NodeType),
Content = MapRichTextNodes(richText.Content),
Tags = FlattenMetadata(entry.Metadata)
};
return item;
}

private CustomAccordion GenerateCustomAccordion(Target target)
{
return new CustomAccordion
Expand Down Expand Up @@ -223,34 +252,6 @@ private CustomGridContainer GenerateCustomGridContainer(Target target)
};
}

public RichTextNodeType ConvertToRichTextNodeType(string str)
{
return str switch
{
RichTextTags.Document => RichTextNodeType.Document,
RichTextTags.Paragraph => RichTextNodeType.Paragraph,
RichTextTags.Heading2 => RichTextNodeType.Heading2,
RichTextTags.Heading3 => RichTextNodeType.Heading3,
RichTextTags.Heading4 => RichTextNodeType.Heading4,
RichTextTags.Heading5 => RichTextNodeType.Heading5,
RichTextTags.Heading6 => RichTextNodeType.Heading6,
RichTextTags.UnorderedList => RichTextNodeType.UnorderedList,
RichTextTags.OrderedList => RichTextNodeType.OrderedList,
RichTextTags.ListItem => RichTextNodeType.ListItem,
RichTextTags.Hyperlink => RichTextNodeType.Hyperlink,
RichTextTags.Table => RichTextNodeType.Table,
RichTextTags.TableRow => RichTextNodeType.TableRow,
RichTextTags.TableHeaderCell => RichTextNodeType.TableHeaderCell,
RichTextTags.TableCell => RichTextNodeType.TableCell,
RichTextTags.Hr => RichTextNodeType.Hr,
RichTextTags.EmbeddedAsset => RichTextNodeType.EmbeddedAsset,
RichTextTags.Text => RichTextNodeType.Text,
RichTextTags.EmbeddedEntry or RichTextTags.EmbeddedEntryInline => RichTextNodeType
.EmbeddedEntry,
_ => RichTextNodeType.Unknown
};
}


public AssetContentType ConvertToAssetContentType(string str)
{
Expand Down
6 changes: 4 additions & 2 deletions src/Dfe.ContentSupport.Web/Services/StubContentfulService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@
using Dfe.ContentSupport.Web.Extensions;
using Dfe.ContentSupport.Web.ViewModels;
using Newtonsoft.Json;
using File = System.IO.File;

namespace Dfe.ContentSupport.Web.Services;

public class StubContentfulService(
HttpClient httpClient,
[FromKeyedServices(WebApplicationBuilderExtensions.ContentAndSupportServiceKey)] ContentfulOptions options)
[FromKeyedServices(WebApplicationBuilderExtensions.ContentAndSupportServiceKey)]
ContentfulOptions options)
: ContentfulClient(httpClient, options), IContentfulService
{
public async Task<IEnumerable<ContentSupportPage>> GetContentSupportPages(string field,
string value, CancellationToken cancellationToken = default)
{
var json = await System.IO.File.ReadAllTextAsync("StubData/ContentfulCollection.json",
var json = await File.ReadAllTextAsync("StubData/ContentfulCollection.json",
cancellationToken);
var resp = JsonConvert.DeserializeObject<ContentSupportPage>(json);
return resp == null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public void Builder_E2e_Uses_MockClient()
builder.InitCsDependencyInjection();

var service = builder.Services.First(o => o.ServiceType == typeof(IContentfulService));
service.KeyedImplementationType?.Name.Should().BeEquivalentTo(nameof(StubContentfulService));
service.KeyedImplementationType?.Name.Should()
.BeEquivalentTo(nameof(StubContentfulService));
}
}

0 comments on commit ef539f8

Please sign in to comment.