Skip to content

Commit

Permalink
refactor: moved checksum calculation to middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaxelr committed Jan 25, 2023
1 parent 4aed067 commit 03f2293
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 16 deletions.
19 changes: 17 additions & 2 deletions src/Carter.Cache/CarterCachingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System.IO;
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

Expand Down Expand Up @@ -48,7 +51,7 @@ private async Task SetCache(HttpContext ctx, RequestDelegate next, CachingOption

if (options.ValidResponse(ctx))
{
string checksum = ctx.CalculateChecksum(bytes);
string checksum = CalculateChecksum(bytes);
ctx.AddEtagToContext(checksum);

if (memoryStream.Length > 0)
Expand All @@ -68,4 +71,16 @@ private async Task SetCache(HttpContext ctx, RequestDelegate next, CachingOption
}

private async Task<bool> CheckCache(HttpContext ctx, CachingOption options) => await service.CheckCache(ctx, options);

internal static string CalculateChecksum(byte[] content)
{
if (content.Length == 0) //Dont process an empty byte array
{
return string.Empty;
}

using var sha1 = SHA1.Create();

return Convert.ToBase64String(sha1.ComputeHash(content.ToArray()));
}
}
13 changes: 0 additions & 13 deletions src/Carter.Cache/Extensions/HttpContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Linq;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;

Expand Down Expand Up @@ -44,15 +42,4 @@ internal static void AddEtagToContext(this HttpContext ctx, string checksum)

ctx.Response.Headers[HeaderNames.ETag] = $"\"{checksum}\"";
}

internal static string CalculateChecksum(this HttpContext ctx, byte[] content)
{
if (content.Length == 0) //Dont process an empty byte array
{
return string.Empty;
}

using var sha1 = SHA1.Create();
return Convert.ToBase64String(sha1.ComputeHash(content.ToArray()));
}
}
2 changes: 1 addition & 1 deletion tests/Carter.Cache.Tests/Unit/CachingServiceFxtures.cs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public async Task Service_set_cache_default_with_request_body()
A.CallTo(() => response.StatusCode).Returns(StatusCodes.Status200OK);

A.CallTo(() => response.Headers.ContainsKey(HeaderNames.ETag)).Returns(true);
A.CallTo(() => response.Headers[HeaderNames.ETag]).Returns(ctx.CalculateChecksum(body));
A.CallTo(() => response.Headers[HeaderNames.ETag]).Returns(CarterCachingMiddleware.CalculateChecksum(body));

var cachedResponse = new CachedResponse(ctx, body);

Expand Down

0 comments on commit 03f2293

Please sign in to comment.