Implement US-03 patient profile updates

This commit is contained in:
Steffen committed 2026-10-01 11:29:54 +02:00
1 parent eb2cf2e54a
commit a9633e49e1
8 files changed
+123 -5

No files matched your search

@@ -14,10 +14,14 @@ public sealed class PatientController(IHttpClientFactory clients) : ControllerBa
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)
if (method == HttpMethod.Post || method == HttpMethod.Put)
{
request.Content = new StreamContent(Request.Body);
if (Request.ContentType is not null)
@@ -26,4 +26,13 @@ public sealed class PatientApplicationService(PatientRepository repository)
public Task<Patient?> GetPatientAsync(Guid patientId, CancellationToken cancellationToken) =>
repository.FindByIdAsync(patientId, cancellationToken);
public async Task<Patient?> UpdatePatientAsync(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken)
{
ArgumentException.ThrowIfNullOrWhiteSpace(request.Name);
if (!await repository.UpdateProfileAsync(patientId, request.Name, request.ContactInfo, cancellationToken))
return null;
return await repository.FindByIdAsync(patientId, cancellationToken);
}
}
@@ -6,4 +6,5 @@ public interface PatientRepository
{
Task<Patient> SaveAsync(Patient patient, CancellationToken cancellationToken);
Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken);
Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken);
}
@@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;
namespace PatientProfileService.Contracts;
public sealed record UpdatePatientRequest
{
[Required]
public string? Name { get; init; }
public string? ContactInfo { get; init; }
}
@@ -23,6 +23,13 @@ public sealed class PatientController(PatientApplicationService service) : Contr
return patient is null ? NotFound() : Ok(ToDto(patient));
}
[HttpPut("{patientId:guid}")]
public async Task<ActionResult<PatientDto>> UpdatePatient(Guid patientId, UpdatePatientRequest request, CancellationToken cancellationToken)
{
var patient = await service.UpdatePatientAsync(patientId, request, cancellationToken);
return patient is null ? NotFound() : Ok(ToDto(patient));
}
private static PatientDto ToDto(Patient patient) =>
new(patient.PatientId, patient.Name, patient.DateOfBirth, patient.ContactInfo);
}
@@ -15,4 +15,15 @@ public sealed class SqlPatientRepository(PatientDbContext db) : PatientRepositor
public Task<Patient?> FindByIdAsync(Guid patientId, CancellationToken cancellationToken) =>
db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == patientId, cancellationToken);
public async Task<bool> UpdateProfileAsync(Guid patientId, string name, string? contactInfo, CancellationToken cancellationToken)
{
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
var affected = await db.Patients.Where(p => p.PatientId == patientId)
.ExecuteUpdateAsync(update => update
.SetProperty(p => p.Name, name)
.SetProperty(p => p.ContactInfo, contactInfo)
.SetProperty(p => p.UpdatedAt, now), cancellationToken);
return affected != 0;
}
}
+8 -4
View File
@@ -1,8 +1,8 @@
# US-01: Create a patient profile
# US-01–US-03: Create, view and update a patient profile
Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway and Patient/Profile service are separate executables and can run on separate machines. Only the services needed for US-01 are implemented.
Implemented with .NET 10 LTS (see the [official download page](https://dotnet.microsoft.com/en-us/download/dotnet/10.0)), ASP.NET Core controllers, and PostgreSQL/EF Core. The API gateway and Patient/Profile service are separate executables and can run on separate machines. Only the services needed for US-01–US-03 are implemented.
The controller calls `PatientApplicationService`, which uses `PatientRepository`, implemented by `SqlPatientRepository`. The service owns the `patient` table from the ER diagram, including creation/update timestamps stored as UTC in PostgreSQL `timestamp` columns. Update-profile functionality belongs to a later story.
The controller calls `PatientApplicationService`, which uses `PatientRepository`, implemented by `SqlPatientRepository`. The service owns the `patient` table from the ER diagram, including creation/update timestamps stored as UTC in PostgreSQL `timestamp` columns.
## Build and run
@@ -37,7 +37,9 @@ curl -i http://127.0.0.1:5080/api/patients \
`GET /api/patients/{patientId}` retrieves the persisted profile, or returns `404` when absent. Retrieval is included because US-01 explicitly requires it. The gateway returns `502` for connection failures and `504` for upstream timeouts.
Authentication and authorization policy is unspecified; the gap is recorded in `suggestions/api-gateway-authentication.md`. No access policy has been invented for US-01.
`PUT /api/patients/{patientId}` updates the name and contact information and returns `200` with the updated profile. It preserves the patient identifier, date of birth and creation timestamp, and updates the modification timestamp. Names must be nonblank, consistent with profile creation; omitted or null contact information clears that optional value. A missing patient returns `404` without creating a profile. Invalid requests return `400` without changing stored information.
Authentication and access control are defined in US-13, US-14 and `Docs/Design/authentication-and-access-control-design.md`, and remain to be implemented as separate stories. These endpoints currently have no access restrictions.
## Automated acceptance tests
@@ -50,6 +52,8 @@ TEST_POSTGRES_CONNECTION='Host=127.0.0.1;Database=postgres;Username=postgres;Pas
The xUnit tests send HTTP requests to the gateway; the gateway reaches a real Kestrel Patient/Profile service over HTTP. They cover every US-01 acceptance scenario, retrieval after host restart, distinct identifiers, optional contact information, invalid JSON/dates, and rejection without database writes. Test assertions use an independent HTTP response contract. Production projects have no references to each other's implementation.
US-02 retrieval scenarios are covered by the creation tests. US-03 tests cover persisted updates after restart, preservation of identity and date of birth, missing-patient rejection without insertion, and invalid-name rejection without changing the profile.
Dependencies: Npgsql's EF Core PostgreSQL provider supplies persistence; EF Core Relational is pinned to the same patch as EF Core Design to keep runtime/tooling versions aligned; EF Core Design supports migration maintenance. xUnit, its Visual Studio runner, Microsoft.NET.Test.Sdk, and ASP.NET Core MVC Testing are used only for automated tests. The gateway uses the platform's HttpClient and has no extra package dependency.
## Linux deployment
@@ -0,0 +1,71 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.EntityFrameworkCore;
using Xunit;
namespace PatientProfile.AcceptanceTests;
public sealed class UpdatePatientTests(PatientApiFixture fixture) : IClassFixture<PatientApiFixture>
{
private sealed record Profile(Guid PatientId, string Name, DateOnly DateOfBirth, string? ContactInfo);
[Fact]
public async Task Updated_profile_preserves_identity_and_date_of_birth_and_survives_restart()
{
using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test"
});
Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode);
var created = (await createdResponse.Content.ReadFromJsonAsync<Profile>())!;
var path = $"/api/patients/{created.PatientId}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name = "Steffen Updated", contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var expected = created with { Name = "Steffen Updated", ContactInfo = "new@example.test" };
Assert.Equal(expected, await response.Content.ReadFromJsonAsync<Profile>());
await fixture.RestartHostsAsync();
Assert.Equal(expected, await fixture.Client.GetFromJsonAsync<Profile>(path));
}
[Fact]
public async Task Updating_a_missing_patient_is_rejected_without_creating_a_profile()
{
await using var db = fixture.CreateDbContext();
var countBefore = await db.Patients.CountAsync();
var path = $"/api/patients/{Guid.NewGuid()}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name = "Steffen Example", contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
Assert.Equal(countBefore, await db.Patients.CountAsync());
using var retrieval = await fixture.Client.GetAsync(path);
Assert.Equal(HttpStatusCode.NotFound, retrieval.StatusCode);
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public async Task Invalid_name_is_rejected_without_changing_the_profile(string? name)
{
using var createdResponse = await fixture.Client.PostAsJsonAsync("/api/patients", new
{
name = "Steffen Example", dateOfBirth = "1980-01-01", contactInfo = "old@example.test"
});
Assert.Equal(HttpStatusCode.Created, createdResponse.StatusCode);
var created = (await createdResponse.Content.ReadFromJsonAsync<Profile>())!;
var path = $"/api/patients/{created.PatientId}";
using var response = await fixture.Client.PutAsJsonAsync(path, new
{
name, contactInfo = "new@example.test"
});
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Equal(created, await fixture.Client.GetFromJsonAsync<Profile>(path));
}
}