FEAT-buildout-endpoints #2

Merged
kjannette merged 2 commits from FEAT-buildout-endpoints into master 2026-08-03 08:24:33 +00:00
19 changed files with 500 additions and 52 deletions
Showing only changes of commit 092ef17439 - Show all commits

74
AGENTS.md Normal file
View File

@@ -0,0 +1,74 @@
# AGENTS.md
Skeleton monorepo for React + .NET projects. Clone it, then replace the placeholder
`User` domain with the real one.
## Layout
```
backend/ ASP.NET Core Web API (net10.0)
frontend/ Vite + React + TypeScript SPA
```
## Running
| Stack | Command | URL |
| --- | --- | --- |
| Backend | `cd backend && dotnet run` | `http://localhost:5231` |
| Frontend | `cd frontend && npm install && npm run dev` | `http://localhost:3000` |
Start them in separate terminals. Allowed CORS origins live in `backend/appsettings.json`
under `Cors:AllowedOrigins`.
## Verifying changes
Run these before considering a change done:
```bash
cd backend && dotnet build
cd frontend && npm run build && npm run lint
```
## Backend conventions
- `ImplicitUsings` is enabled. Do not re-import `Microsoft.AspNetCore.*`,
`Microsoft.Extensions.DependencyInjection`, `System.Linq`, and friends.
- Use file-scoped namespaces (`namespace Backend.Data;`).
- Repository methods are async, suffixed `Async`, and take a `CancellationToken`.
- Read configuration through the options pattern (`IOptions<T>` + `Configure<T>`),
not `Configuration["Some:Key"]`.
- Controllers stay thin: validate, delegate to a repository or service, map the result
to an `IActionResult`. No data access in controllers.
- Route templates use `ApiRoutes.V1` rather than a hardcoded `"v1"` string.
- Cross-cutting pipeline concerns (CORS, rate limiting) belong in `backend/Gateway/`
and are wired through `AddApiGateway` / `UseApiGateway`, not inline in `Program.cs`.
- Persistence implementations register through `AddPersistence`, selected by the
`Persistence:Provider` setting. Swapping in EF Core or another store should not
require touching controllers.
## Frontend conventions
- All HTTP goes through `src/api/`. Components never call `fetch` directly.
- Configuration comes from `VITE_*` environment variables; `VITE_API_BASE_URL` points
at the backend. Add new variables to `.env.example` and to the `ImportMetaEnv`
interface in `src/vite-env.d.ts`.
- TypeScript is strict and unused locals are errors. The build runs `tsc -b` before Vite.
## Endpoints
| Method | Path | Purpose |
| --- | --- | --- |
| GET | `/health` | Liveness check, unversioned for infrastructure |
| GET | `/v1/info` | App name, version, environment, server timestamp |
| GET | `/v1/users` | List users |
| GET | `/v1/users/{id}` | Fetch one user |
| POST | `/v1/users` | Create a user |
| PUT | `/v1/users/{id}` | Replace a user |
| DELETE | `/v1/users/{id}` | Delete a user |
Sample requests live in `backend/backend.http`.
## Not included on purpose
Authentication, a real database provider, tests, Docker, and structured logging are all
left out. Add them when the project has requirements that justify a specific choice.

View File

@@ -23,8 +23,16 @@ The API runs at `http://localhost:5231`. Swagger UI is available in Development
Skeleton endpoints:
- `GET /health` — liveness check
- `GET /health` — liveness check, exempt from rate limiting
- `GET /v1/info` — app name, version, environment, and server timestamp
- `GET|POST /v1/users`, `GET|PUT|DELETE /v1/users/{id}` — placeholder CRUD over the
in-memory repository
Requests are rate limited per client IP using the `RateLimiting` section of
`appsettings.json`, and allowed CORS origins come from the `Cors` section. Storage is
selected by `Persistence:Provider`, which currently supports `InMemory` only; data is
lost on restart until a real provider is registered in
`backend/Data/PersistenceServiceCollectionExtensions.cs`.
## Frontend
@@ -46,7 +54,7 @@ VITE_API_BASE_URL=http://localhost:5231
## Running both
Start the backend and frontend in separate terminals. The backend CORS policy allows requests from `http://localhost:3000`.
Start the backend and frontend in separate terminals. The backend CORS policy allows requests from `http://localhost:3000` by default; change `Cors:AllowedOrigins` in `backend/appsettings.json` to add more.
## Project structure

View File

@@ -1,10 +1,11 @@
using Backend.Gateway;
using Microsoft.AspNetCore.Mvc;
namespace Backend.Controllers;
[Route("v1/[controller]")]
[ApiController]
public class InfoController : ControllerBase
[Route(ApiRoutes.V1 + "/[controller]")]
public sealed class InfoController : ControllerBase
{
private readonly IWebHostEnvironment _environment;

View File

@@ -1,17 +0,0 @@
using Microsoft.AspNetCore.Mvc;
using Backend.Data;
namespace Backend.Controllers
{
[Route("v1/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserRepository _userRepository;
public UserController(IUserRepository userRepository)
{
_userRepository = userRepository;
}
}
}

View File

@@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace Backend.Controllers;
// Validation attributes must target the primary constructor parameters, not the
// generated properties; MVC rejects record types with property-level metadata.
public sealed record CreateUserRequest(
[Required][EmailAddress] string Email,
[Required][StringLength(100, MinimumLength = 1)] string DisplayName);
public sealed record UpdateUserRequest(
[Required][EmailAddress] string Email,
[Required][StringLength(100, MinimumLength = 1)] string DisplayName);

View File

@@ -0,0 +1,96 @@
using Backend.Data;
using Backend.Gateway;
using Microsoft.AspNetCore.Mvc;
namespace Backend.Controllers;
[ApiController]
[Route(ApiRoutes.V1 + "/[controller]")]
public sealed class UsersController : ControllerBase
{
private readonly IUserRepository _userRepository;
public UsersController(IUserRepository userRepository)
{
_userRepository = userRepository;
}
[HttpGet]
[ProducesResponseType<IReadOnlyList<User>>(StatusCodes.Status200OK)]
public async Task<IActionResult> GetAll(CancellationToken cancellationToken)
=> Ok(await _userRepository.GetAllAsync(cancellationToken));
[HttpGet("{id:guid}")]
[ProducesResponseType<User>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id, CancellationToken cancellationToken)
{
var user = await _userRepository.GetByIdAsync(id, cancellationToken);
return user is null ? NotFound() : Ok(user);
}
[HttpPost]
[ProducesResponseType<User>(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Create(
CreateUserRequest request,
CancellationToken cancellationToken)
{
if (await _userRepository.GetByEmailAsync(request.Email, cancellationToken) is not null)
{
return Conflict(new ProblemDetails
{
Title = "Email already in use",
Status = StatusCodes.Status409Conflict,
});
}
var user = await _userRepository.AddAsync(
new User { Email = request.Email, DisplayName = request.DisplayName },
cancellationToken);
return CreatedAtAction(nameof(GetById), new { id = user.Id }, user);
}
[HttpPut("{id:guid}")]
[ProducesResponseType<User>(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType(StatusCodes.Status409Conflict)]
public async Task<IActionResult> Update(
Guid id,
UpdateUserRequest request,
CancellationToken cancellationToken)
{
var existing = await _userRepository.GetByIdAsync(id, cancellationToken);
if (existing is null)
{
return NotFound();
}
var emailOwner = await _userRepository.GetByEmailAsync(request.Email, cancellationToken);
if (emailOwner is not null && emailOwner.Id != id)
{
return Conflict(new ProblemDetails
{
Title = "Email already in use",
Status = StatusCodes.Status409Conflict,
});
}
existing.Email = request.Email;
existing.DisplayName = request.DisplayName;
var updated = await _userRepository.UpdateAsync(existing, cancellationToken);
return updated is null ? NotFound() : Ok(updated);
}
[HttpDelete("{id:guid}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> Delete(Guid id, CancellationToken cancellationToken)
=> await _userRepository.DeleteAsync(id, cancellationToken) ? NoContent() : NotFound();
}

View File

@@ -1,5 +1,22 @@
namespace Backend.Data;
/// <summary>
/// Storage-agnostic access to <see cref="User"/>. Implementations are selected by the
/// <c>Persistence:Provider</c> setting; see <see cref="PersistenceServiceCollectionExtensions"/>.
/// </summary>
public interface IUserRepository
{
Task<IReadOnlyList<User>> GetAllAsync(CancellationToken cancellationToken = default);
Task<User?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
Task<User?> GetByEmailAsync(string email, CancellationToken cancellationToken = default);
Task<User> AddAsync(User user, CancellationToken cancellationToken = default);
/// <returns>The updated user, or <c>null</c> when no user has the given id.</returns>
Task<User?> UpdateAsync(User user, CancellationToken cancellationToken = default);
/// <returns><c>true</c> when a user was removed.</returns>
Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default);
}

View File

@@ -0,0 +1,58 @@
using System.Collections.Concurrent;
namespace Backend.Data.InMemory;
/// <summary>
/// Default implementation so the skeleton runs with no database. State is per-process
/// and lost on restart.
/// </summary>
public sealed class InMemoryUserRepository : IUserRepository
{
private readonly ConcurrentDictionary<Guid, User> _users = new();
public Task<IReadOnlyList<User>> GetAllAsync(CancellationToken cancellationToken = default)
{
IReadOnlyList<User> users = _users.Values
.OrderBy(user => user.CreatedAt)
.ToList();
return Task.FromResult(users);
}
public Task<User?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default)
{
_users.TryGetValue(id, out var user);
return Task.FromResult(user);
}
public Task<User?> GetByEmailAsync(string email, CancellationToken cancellationToken = default)
{
var user = _users.Values
.FirstOrDefault(candidate => string.Equals(candidate.Email, email, StringComparison.OrdinalIgnoreCase));
return Task.FromResult(user);
}
public Task<User> AddAsync(User user, CancellationToken cancellationToken = default)
{
_users[user.Id] = user;
return Task.FromResult(user);
}
public Task<User?> UpdateAsync(User user, CancellationToken cancellationToken = default)
{
if (!_users.ContainsKey(user.Id))
{
return Task.FromResult<User?>(null);
}
_users[user.Id] = user;
return Task.FromResult<User?>(user);
}
public Task<bool> DeleteAsync(Guid id, CancellationToken cancellationToken = default)
=> Task.FromResult(_users.TryRemove(id, out _));
}

View File

@@ -0,0 +1,13 @@
namespace Backend.Data;
public sealed class PersistenceOptions
{
public const string SectionName = "Persistence";
public string Provider { get; set; } = PersistenceProviders.InMemory;
}
public static class PersistenceProviders
{
public const string InMemory = "InMemory";
}

View File

@@ -0,0 +1,37 @@
using Backend.Data.InMemory;
namespace Backend.Data;
/// <summary>
/// Single place where a storage backend is chosen. To add a real database, implement
/// <see cref="IUserRepository"/> and register it under a new provider name here;
/// controllers stay untouched.
/// </summary>
public static class PersistenceServiceCollectionExtensions
{
public static IServiceCollection AddPersistence(
this IServiceCollection services,
IConfiguration configuration)
{
services.Configure<PersistenceOptions>(configuration.GetSection(PersistenceOptions.SectionName));
var provider = configuration.GetSection(PersistenceOptions.SectionName).Get<PersistenceOptions>()?.Provider
?? PersistenceProviders.InMemory;
switch (provider)
{
case PersistenceProviders.InMemory:
// Singleton because the store itself holds the data.
services.AddSingleton<IUserRepository, InMemoryUserRepository>();
break;
default:
throw new InvalidOperationException(
$"Unknown persistence provider '{provider}'. Supported providers: " +
$"'{PersistenceProviders.InMemory}'. Register additional providers in " +
$"{nameof(PersistenceServiceCollectionExtensions)}.");
}
return services;
}
}

15
backend/Data/User.cs Normal file
View File

@@ -0,0 +1,15 @@
namespace Backend.Data;
/// <summary>
/// Placeholder domain entity. Replace with the real model once the project has one.
/// </summary>
public sealed class User
{
public Guid Id { get; init; } = Guid.NewGuid();
public required string Email { get; set; }
public required string DisplayName { get; set; }
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
}

View File

@@ -0,0 +1,8 @@
namespace Backend.Gateway;
public static class ApiRoutes
{
public const string V1 = "v1";
public const string Health = "/health";
}

View File

@@ -0,0 +1,14 @@
namespace Backend.Gateway;
public static class GatewayApplicationBuilderExtensions
{
// CORS must run before the rate limiter so that rejected requests still carry
// the headers the browser needs to surface a 429 to the client.
public static IApplicationBuilder UseApiGateway(this IApplicationBuilder app)
{
app.UseCors(GatewayServiceCollectionExtensions.CorsPolicyName);
app.UseRateLimiter();
return app;
}
}

View File

@@ -0,0 +1,19 @@
namespace Backend.Gateway;
public sealed class CorsOptions
{
public const string SectionName = "Cors";
public string[] AllowedOrigins { get; set; } = [];
}
public sealed class RateLimitOptions
{
public const string SectionName = "RateLimiting";
public int PermitLimit { get; set; } = 100;
public int WindowSeconds { get; set; } = 60;
public int QueueLimit { get; set; }
}

View File

@@ -0,0 +1,64 @@
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
namespace Backend.Gateway;
public static class GatewayServiceCollectionExtensions
{
public const string CorsPolicyName = "DefaultCorsPolicy";
public static IServiceCollection AddApiGateway(
this IServiceCollection services,
IConfiguration configuration)
{
services.Configure<CorsOptions>(configuration.GetSection(CorsOptions.SectionName));
services.Configure<RateLimitOptions>(configuration.GetSection(RateLimitOptions.SectionName));
var corsSettings = configuration.GetSection(CorsOptions.SectionName).Get<CorsOptions>()
?? new CorsOptions();
var rateLimitSettings = configuration.GetSection(RateLimitOptions.SectionName).Get<RateLimitOptions>()
?? new RateLimitOptions();
services.AddCors(options => options.AddPolicy(CorsPolicyName, policy =>
{
if (corsSettings.AllowedOrigins.Length == 0)
{
return;
}
policy.WithOrigins(corsSettings.AllowedOrigins)
.AllowAnyHeader()
.AllowAnyMethod();
}));
services.AddRateLimiter(options =>
{
options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
options.GlobalLimiter = CreateGlobalLimiter(rateLimitSettings);
});
services.Configure<RouteOptions>(options => options.LowercaseUrls = true);
return services;
}
// Health checks are exempt so that infrastructure probes are never throttled.
private static PartitionedRateLimiter<HttpContext> CreateGlobalLimiter(RateLimitOptions settings) =>
PartitionedRateLimiter.Create<HttpContext, string>(context =>
{
if (context.Request.Path.StartsWithSegments(ApiRoutes.Health))
{
return RateLimitPartition.GetNoLimiter("health");
}
var partitionKey = context.Connection.RemoteIpAddress?.ToString() ?? "unknown";
return RateLimitPartition.GetFixedWindowLimiter(partitionKey, _ => new FixedWindowRateLimiterOptions
{
PermitLimit = settings.PermitLimit,
Window = TimeSpan.FromSeconds(settings.WindowSeconds),
QueueLimit = settings.QueueLimit,
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
});
});
}

View File

@@ -1,42 +1,35 @@
using System.Text.Json;
using Backend.Data;
using Backend.Gateway;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
// using Backend.Data
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHealthChecks();
builder.Services.AddProblemDetails();
builder.Services.AddCors();
//builder.Services.AddDbContext<UserContext>(options =>
// options.UseSqlite(builder.Configuration["ConnectionStrings:UserConnection"])
//);
//builder.Services.AddScoped<IBowlingLeagueRepository, EFBowlingLeagueRepository>();
builder.Services.AddApiGateway(builder.Configuration);
builder.Services.AddPersistence(builder.Configuration);
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseExceptionHandler();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(p => p.WithOrigins("http://localhost:3000"));
app.UseHttpsRedirection();
app.UseAuthorization();
app.UseApiGateway();
app.MapHealthChecks("/health", new HealthCheckOptions
app.MapHealthChecks(ApiRoutes.Health, new HealthCheckOptions
{
ResponseWriter = async (context, report) =>
{

View File

@@ -6,7 +6,17 @@
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"BowlingLeagueConnection": "Data Source=BowlingLeague.sqlite"
"Cors": {
"AllowedOrigins": [
"http://localhost:3000"
]
},
"RateLimiting": {
"PermitLimit": 100,
"WindowSeconds": 60,
"QueueLimit": 0
},
"Persistence": {
"Provider": "InMemory"
}
}

View File

@@ -7,16 +7,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="8.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
</ItemGroup>

View File

@@ -1,4 +1,5 @@
@Backend_HostAddress = http://localhost:5231
@UserId = 00000000-0000-0000-0000-000000000000
GET {{Backend_HostAddress}}/health
Accept: application/json
@@ -9,3 +10,37 @@ GET {{Backend_HostAddress}}/v1/info
Accept: application/json
###
GET {{Backend_HostAddress}}/v1/users
Accept: application/json
###
POST {{Backend_HostAddress}}/v1/users
Content-Type: application/json
{
"email": "ada@example.com",
"displayName": "Ada Lovelace"
}
###
GET {{Backend_HostAddress}}/v1/users/{{UserId}}
Accept: application/json
###
PUT {{Backend_HostAddress}}/v1/users/{{UserId}}
Content-Type: application/json
{
"email": "ada@example.com",
"displayName": "Ada King"
}
###
DELETE {{Backend_HostAddress}}/v1/users/{{UserId}}
###