Skip to content

Commit

Permalink
Create SaveStyleSheetCommand.cs
Browse files Browse the repository at this point in the history
  • Loading branch information
EdiWang committed Sep 3, 2023
1 parent d232882 commit 2a95c57
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/Moonglade.Core/SaveStyleSheetCommand.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System.Security.Cryptography;
using Moonglade.Data.Spec;

namespace Moonglade.Core;

public record SaveStyleSheetCommand(string Slug, string CssContent) : IRequest<Guid>;

public class SaveStyleSheetCommandHandler : IRequestHandler<SaveStyleSheetCommand, Guid>
{
private readonly IRepository<StyleSheetEntity> _repo;

public SaveStyleSheetCommandHandler(IRepository<StyleSheetEntity> repo) => _repo = repo;

public async Task<Guid> Handle(SaveStyleSheetCommand request, CancellationToken cancellationToken)
{
var slug = request.Slug.ToLower().Trim();
var css = request.CssContent.Trim();
var hash = CalculateHash($"{slug}_{css}");

var entity = await _repo.GetAsync(new StyleSheetByFriendlyNameSpec(slug), cancellationToken);
if (entity is null)
{
entity = new()
{
Id = Guid.NewGuid(),
FriendlyName = slug,
CssContent = css,
Hash = hash,
LastModifiedTimeUtc = DateTime.UtcNow
};

await _repo.AddAsync(entity, cancellationToken);
}
else
{
entity.CssContent = css;
entity.Hash = hash;
entity.LastModifiedTimeUtc = DateTime.UtcNow;

await _repo.UpdateAsync(entity, cancellationToken);
}

return entity.Id;
}

private string CalculateHash(string content)
{
var sha256 = SHA256.Create();

byte[] inputBytes = Encoding.ASCII.GetBytes(content);
byte[] outputBytes = sha256.ComputeHash(inputBytes);

return Convert.ToBase64String(outputBytes);
}
}

0 comments on commit 2a95c57

Please sign in to comment.