fleshout backend
This commit is contained in:
@@ -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;
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
13
backend/Controllers/UserRequests.cs
Normal file
13
backend/Controllers/UserRequests.cs
Normal 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);
|
||||
96
backend/Controllers/UsersController.cs
Normal file
96
backend/Controllers/UsersController.cs
Normal 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();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
58
backend/Data/InMemory/InMemoryUserRepository.cs
Normal file
58
backend/Data/InMemory/InMemoryUserRepository.cs
Normal 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 _));
|
||||
}
|
||||
13
backend/Data/PersistenceOptions.cs
Normal file
13
backend/Data/PersistenceOptions.cs
Normal 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";
|
||||
}
|
||||
37
backend/Data/PersistenceServiceCollectionExtensions.cs
Normal file
37
backend/Data/PersistenceServiceCollectionExtensions.cs
Normal 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
15
backend/Data/User.cs
Normal 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;
|
||||
}
|
||||
8
backend/Gateway/ApiRoutes.cs
Normal file
8
backend/Gateway/ApiRoutes.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace Backend.Gateway;
|
||||
|
||||
public static class ApiRoutes
|
||||
{
|
||||
public const string V1 = "v1";
|
||||
|
||||
public const string Health = "/health";
|
||||
}
|
||||
14
backend/Gateway/GatewayApplicationBuilderExtensions.cs
Normal file
14
backend/Gateway/GatewayApplicationBuilderExtensions.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
19
backend/Gateway/GatewayOptions.cs
Normal file
19
backend/Gateway/GatewayOptions.cs
Normal 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; }
|
||||
}
|
||||
64
backend/Gateway/GatewayServiceCollectionExtensions.cs
Normal file
64
backend/Gateway/GatewayServiceCollectionExtensions.cs
Normal 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,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -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) =>
|
||||
{
|
||||
@@ -51,4 +44,4 @@ app.MapHealthChecks("/health", new HealthCheckOptions
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
app.Run();
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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}}
|
||||
|
||||
###
|
||||
|
||||
Reference in New Issue
Block a user