70 lines
2.9 KiB
C#
70 lines
2.9 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using System.Security.Claims;
|
|
|
|
namespace ApiGateway.Controllers;
|
|
|
|
[ApiController]
|
|
[Route("api/patients")]
|
|
public sealed class PatientController(IHttpClientFactory clients) : ControllerBase
|
|
{
|
|
[HttpPost]
|
|
public Task CreatePatient(CancellationToken cancellationToken) =>
|
|
ForwardAsync(HttpMethod.Post, "api/patients", cancellationToken);
|
|
|
|
[HttpGet("me")]
|
|
public Task GetOwnPatient(CancellationToken cancellationToken) =>
|
|
ForwardAsync(HttpMethod.Get, "api/patients/by-account/" + Uri.EscapeDataString(User.FindFirstValue(ClaimTypes.NameIdentifier)!), cancellationToken);
|
|
|
|
[HttpGet("{patientId:guid}")]
|
|
public Task GetPatient(Guid patientId, CancellationToken cancellationToken) =>
|
|
ForwardAsync(HttpMethod.Get, $"api/patients/{patientId}", cancellationToken);
|
|
|
|
[HttpPut("{patientId:guid}")]
|
|
public Task UpdatePatient(Guid patientId, CancellationToken cancellationToken) =>
|
|
ForwardAsync(HttpMethod.Put, $"api/patients/{patientId}", cancellationToken);
|
|
|
|
private async Task ForwardAsync(HttpMethod method, string path, CancellationToken cancellationToken)
|
|
{
|
|
using var request = new HttpRequestMessage(method, path);
|
|
if (method == HttpMethod.Post)
|
|
request.Headers.Add("X-Account-Id", User.FindFirstValue(ClaimTypes.NameIdentifier));
|
|
if (method == HttpMethod.Post || method == HttpMethod.Put)
|
|
{
|
|
request.Content = new StreamContent(Request.Body);
|
|
if (Request.ContentType is not null)
|
|
request.Content.Headers.TryAddWithoutValidation("Content-Type", Request.ContentType);
|
|
}
|
|
|
|
try
|
|
{
|
|
using var upstream = await clients.CreateClient("PatientProfile")
|
|
.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
|
Response.StatusCode = (int)upstream.StatusCode;
|
|
Response.ContentType = upstream.Content.Headers.ContentType?.ToString();
|
|
if (upstream.Headers.Location is { } location)
|
|
Response.Headers.Location = location.IsAbsoluteUri ? location.PathAndQuery : location.ToString();
|
|
await upstream.Content.CopyToAsync(Response.Body, cancellationToken);
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
await WriteFailureAsync(StatusCodes.Status502BadGateway);
|
|
}
|
|
catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
|
|
{
|
|
await WriteFailureAsync(StatusCodes.Status504GatewayTimeout);
|
|
}
|
|
}
|
|
|
|
private Task WriteFailureAsync(int status)
|
|
{
|
|
if (Response.HasStarted)
|
|
{
|
|
HttpContext.Abort();
|
|
return Task.CompletedTask;
|
|
}
|
|
Response.Clear();
|
|
return Results.Problem(statusCode: status, title: "Patient/Profile service is unavailable.")
|
|
.ExecuteAsync(HttpContext);
|
|
}
|
|
}
|