2757869176
Add contract validation, SMTP delivery results, terminal failure context, neutral development seeding, and local Docker setup. Ref: IT-1033
37 lines
1.3 KiB
C#
37 lines
1.3 KiB
C#
namespace HrynCo.NotificationService.Worker.Services.EmailProcessing;
|
|
|
|
using System.Text;
|
|
using HrynCo.NotificationService.Contracts.Messages;
|
|
using HrynCo.NotificationService.DAL.Abstract.Templates;
|
|
|
|
internal sealed class EmailTemplateRenderingService : IEmailTemplateRenderingService
|
|
{
|
|
public RenderedEmail Render(EmailTemplate template, SendEmailMessageData data)
|
|
{
|
|
string[] missingVariables = template.Variables
|
|
.Where(variable => variable.Required)
|
|
.Select(variable => variable.Name)
|
|
.Where(name => !data.Variables.TryGetValue(name, out string? value) || string.IsNullOrWhiteSpace(value))
|
|
.ToArray();
|
|
|
|
if (missingVariables.Length > 0)
|
|
{
|
|
throw new InvalidDataException(
|
|
$"Required template variables are missing: {string.Join(", ", missingVariables)}.");
|
|
}
|
|
|
|
return new RenderedEmail(
|
|
Interpolate(template.Subject, data.Variables),
|
|
Interpolate(template.HtmlBody, data.Variables),
|
|
Interpolate(template.TextBody, data.Variables));
|
|
}
|
|
|
|
private static string Interpolate(string text, IReadOnlyDictionary<string, string> variables)
|
|
{
|
|
var sb = new StringBuilder(text);
|
|
foreach (var (key, value) in variables)
|
|
sb.Replace($"{{{{{key}}}}}", value);
|
|
return sb.ToString();
|
|
}
|
|
}
|