using System.Net.Http.Json; using System.Text.Json; using System.Text.Json.Nodes; namespace HrynCo.NotificationService.Web.IntegrationTests; public sealed class DefinitionApiTestContext : IAsyncDisposable { public required TemplateWebApplicationFactory App { get; init; } public required HttpClient Client { get; init; } public required Guid ServiceId { get; init; } public string ServiceRoot => $"/api/v1/services/{ServiceId}"; public static async Task CreateAsync(TemplateDatabaseFixture fixture) { var app = new TemplateWebApplicationFactory(await fixture.CreateDatabaseAsync()); var client = app.CreateClient(); var response = await client.GetFromJsonAsync("/api/v1/services?name=TestService"); return new DefinitionApiTestContext { App = app, Client = client, ServiceId = response.GetProperty("data").GetProperty("id").GetGuid() }; } public string DefinitionUrl(string key = "Welcome", bool upsert = false) => ServiceRoot + "/email-template-definitions" + (upsert ? "/upsert" : "") + "?key=" + Uri.EscapeDataString(key); public Task UpsertAsync(JsonNode body, string key = "Welcome") => Client.PostAsJsonAsync(DefinitionUrl(key, upsert: true), body); public async Task ReadAsync(string key = "Welcome") => (await Client.GetFromJsonAsync(DefinitionUrl(key))).GetProperty("data"); public static JsonObject Body(Guid? revision, params string[] codes) => new() { ["revision"] = revision?.ToString(), ["variables"] = new JsonArray(new JsonObject { ["name"] = "Name", ["required"] = true }), ["translations"] = new JsonArray(codes.Select(code => (JsonNode)new JsonObject { ["languageCode"] = code, ["subject"] = "Subject " + code, ["htmlBody"] = "

Hello {{Name}}

", ["textBody"] = "Hello {{Name}}" }).ToArray()) }; public async ValueTask DisposeAsync() { Client.Dispose(); await App.DisposeAsync(); } }