Skip to content

Commit

Permalink
Use C# 12 features
Browse files Browse the repository at this point in the history
- Use primary constructors where relevant.
- Use collection literals where relevant.
- Simplify JSON serialization with `HttpClient`.
- Fix some typos.
- Fix indentation.
  • Loading branch information
martincostello committed Nov 9, 2023
1 parent ab6d2ac commit a18cd4e
Show file tree
Hide file tree
Showing 7 changed files with 30 additions and 82 deletions.
22 changes: 4 additions & 18 deletions src/ApplePayJS/Clients/ApplePayClient.cs
Original file line number Diff line number Diff line change
@@ -1,38 +1,24 @@
// Copyright (c) Just Eat, 2016. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

using System.Net.Mime;
using System.Text;
using System.Text.Json;

namespace JustEat.ApplePayJS.Clients;

public class ApplePayClient
public class ApplePayClient(HttpClient httpClient)
{
private readonly HttpClient _httpClient;

public ApplePayClient(HttpClient httpClient)
{
_httpClient = httpClient;
}

public async Task<JsonDocument> GetMerchantSessionAsync(
Uri requestUri,
MerchantSessionRequest request,
CancellationToken cancellationToken = default)
{
// POST the data to create a valid Apple Pay merchant session.
string json = JsonSerializer.Serialize(request);

using var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);

using var response = await _httpClient.PostAsync(requestUri, content, cancellationToken);
using var response = await httpClient.PostAsJsonAsync(requestUri, request, cancellationToken);

response.EnsureSuccessStatusCode();

// Read the opaque merchant session JSON from the response body.
using var stream = await response.Content.ReadAsStreamAsync();

return await JsonDocument.ParseAsync(stream, cancellationToken: cancellationToken);
var merchantSession = await response.Content.ReadFromJsonAsync<JsonDocument>(cancellationToken);
return merchantSession!;
}
}
9 changes: 2 additions & 7 deletions src/ApplePayJS/Clients/MerchantCertificate.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,9 @@

namespace JustEat.ApplePayJS.Clients;

public class MerchantCertificate
public class MerchantCertificate(IOptions<ApplePayOptions> options)
{
private readonly ApplePayOptions _options;

public MerchantCertificate(IOptions<ApplePayOptions> options)
{
_options = options.Value;
}
private readonly ApplePayOptions _options = options.Value;

public X509Certificate2 GetCertificate()
{
Expand Down
29 changes: 9 additions & 20 deletions src/ApplePayJS/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,29 +10,18 @@ namespace JustEat.ApplePayJS.Controllers;
using Microsoft.Extensions.Options;
using Models;

public class HomeController : Controller
public class HomeController(
ApplePayClient client,
MerchantCertificate certificate,
IOptions<ApplePayOptions> options) : Controller
{
private readonly ApplePayClient _client;
private readonly MerchantCertificate _certificate;
private readonly ApplePayOptions _options;

public HomeController(
ApplePayClient client,
MerchantCertificate certificate,
IOptions<ApplePayOptions> options)
{
_client = client;
_certificate = certificate;
_options = options.Value;
}

public IActionResult Index()
{
// Get the merchant identifier and store name for use in the JavaScript by ApplePaySession.
var model = new HomeModel()
{
MerchantId = _certificate.GetMerchantIdentifier(),
StoreName = _options.StoreName,
MerchantId = certificate.GetMerchantIdentifier(),
StoreName = options.Value.StoreName,
};

return View(model);
Expand All @@ -56,13 +45,13 @@ public async Task<IActionResult> Validate([FromBody] ValidateMerchantSessionMode
// Create the JSON payload to POST to the Apple Pay merchant validation URL.
var request = new MerchantSessionRequest()
{
DisplayName = _options.StoreName,
DisplayName = options.Value.StoreName,
Initiative = "web",
InitiativeContext = Request.GetTypedHeaders().Host.Value,
MerchantIdentifier = _certificate.GetMerchantIdentifier(),
MerchantIdentifier = certificate.GetMerchantIdentifier(),
};

JsonDocument merchantSession = await _client.GetMerchantSessionAsync(requestUri, request, cancellationToken);
JsonDocument merchantSession = await client.GetMerchantSessionAsync(requestUri, request, cancellationToken);

// Return the merchant session as-is to the JavaScript as JSON.
return Json(merchantSession.RootElement);
Expand Down
2 changes: 1 addition & 1 deletion src/ApplePayJS/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);

// Apple Pay JS requires the use of at least TLS 1.2 to generate a merchange session:
// Apple Pay JS requires the use of at least TLS 1.2 to generate a merchant session:
// https://developer.apple.com/documentation/applepayjs/setting_up_server_requirements
// If you run an older operating system that does not negotiate this by default, uncomment the line below.
// handler.SslProtocols = SslProtocols.Tls12;
Expand Down
21 changes: 7 additions & 14 deletions tests/ApplePayJS.Tests/BrowserFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,10 @@

namespace ApplePayJS.Tests;

internal sealed class BrowserFixture
internal sealed class BrowserFixture(ITestOutputHelper? outputHelper)
{
public BrowserFixture(ITestOutputHelper? outputHelper)
{
OutputHelper = outputHelper;
}

private static bool IsRunningInGitHubActions { get; } = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("GITHUB_ACTIONS"));

private ITestOutputHelper? OutputHelper { get; }

public async Task WithPageAsync(
Func<IPage, Task> action,
string browserType = "chromium",
Expand All @@ -32,8 +25,8 @@ public async Task WithPageAsync(

IPage page = await browser.NewPageAsync(options);

page.Console += (_, e) => OutputHelper?.WriteLine(e.Text);
page.PageError += (_, e) => OutputHelper?.WriteLine(e);
page.Console += (_, e) => outputHelper?.WriteLine(e.Text);
page.PageError += (_, e) => outputHelper?.WriteLine(e);

try
{
Expand Down Expand Up @@ -119,11 +112,11 @@ await page.ScreenshotAsync(new PageScreenshotOptions()
Path = path,
});

OutputHelper?.WriteLine($"Screenshot saved to {path}.");
outputHelper?.WriteLine($"Screenshot saved to {path}.");
}
catch (Exception ex)
{
OutputHelper?.WriteLine("Failed to capture screenshot: " + ex);
outputHelper?.WriteLine("Failed to capture screenshot: " + ex);
}
}

Expand Down Expand Up @@ -152,11 +145,11 @@ private async Task TryCaptureVideoAsync(

File.Move(videoSource, videoDestination);

OutputHelper?.WriteLine($"Video saved to {videoDestination}.");
outputHelper?.WriteLine($"Video saved to {videoDestination}.");
}
catch (Exception ex)
{
OutputHelper?.WriteLine("Failed to capture video: " + ex);
outputHelper?.WriteLine("Failed to capture video: " + ex);
}
}
}
18 changes: 5 additions & 13 deletions tests/ApplePayJS.Tests/IntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,9 @@

namespace ApplePayJS.Tests;

public class IntegrationTests : IAsyncLifetime
public class IntegrationTests(ITestOutputHelper outputHelper) : IAsyncLifetime
{
public IntegrationTests(ITestOutputHelper outputHelper)
{
Fixture = new TestFixture()
{
OutputHelper = outputHelper,
};
}

private TestFixture Fixture { get; }
private TestFixture Fixture { get; } = new() { OutputHelper = outputHelper };

public Task InitializeAsync()
{
Expand Down Expand Up @@ -64,7 +56,7 @@ await fixture.WithPageAsync(async (page) =>
await page.WaitForSelectorAsync(Selectors.CardName);
await page.InnerTextAsync(Selectors.CardName).ShouldBe("American Express");

foreach (string selector in new[] { Selectors.BillingContact, Selectors.ShipingContact })
foreach (string selector in new[] { Selectors.BillingContact, Selectors.ShippingContact })
{
var contact = await page.QuerySelectorAsync(selector);
contact.ShouldNotBeNull();
Expand All @@ -79,7 +71,7 @@ await fixture.WithPageAsync(async (page) =>

private static void InstallPlaywright()
{
int exitCode = Program.Main(new[] { "install" });
int exitCode = Program.Main(["install"]);

if (exitCode != 0)
{
Expand All @@ -94,6 +86,6 @@ private static class Selectors
internal const string CardName = ".card-name";
internal const string ContactName = ".contact-name";
internal const string Pay = "id=apple-pay-button";
internal const string ShipingContact = "id=shipping-contact";
internal const string ShippingContact = "id=shipping-contact";
}
}
11 changes: 2 additions & 9 deletions tests/ApplePayJS.Tests/TestFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,21 +125,14 @@ private void EnsureServer()
}
}

private sealed class HttpRequestInterceptionFilter : IHttpMessageHandlerBuilderFilter
private sealed class HttpRequestInterceptionFilter(HttpClientInterceptorOptions options) : IHttpMessageHandlerBuilderFilter
{
internal HttpRequestInterceptionFilter(HttpClientInterceptorOptions options)
{
Options = options;
}

private HttpClientInterceptorOptions Options { get; }

public Action<HttpMessageHandlerBuilder> Configure(Action<HttpMessageHandlerBuilder> next)
{
return (builder) =>
{
next(builder);
builder.AdditionalHandlers.Add(Options.CreateHttpMessageHandler());
builder.AdditionalHandlers.Add(options.CreateHttpMessageHandler());
};
}
}
Expand Down

0 comments on commit a18cd4e

Please sign in to comment.