-
Notifications
You must be signed in to change notification settings - Fork 137
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |