This repository has been archived by the owner on Jul 12, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2e788a3
commit ff9fb07
Showing
3 changed files
with
72 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
using FluentValidation; | ||
using RookieShop.Infrastructure.Cache.Redis; | ||
|
||
namespace RookieShop.ApiService.Filters; | ||
|
||
public class IdempotencyFilter(IRedisService redisService) : IEndpointFilter | ||
{ | ||
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) | ||
{ | ||
var request = context.HttpContext.Request; | ||
var requestMethod = request.Method; | ||
var requestPath = request.Path; | ||
var requestId = request.Headers["X-Idempotency-Key"].FirstOrDefault(); | ||
|
||
if (requestMethod is not "POST" and not "PATCH") | ||
return await next(context); | ||
|
||
if (string.IsNullOrEmpty(requestId)) | ||
{ | ||
context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest; | ||
throw new ValidationException("X-Idempotency-Key header is required for POST and PATCH requests."); | ||
} | ||
|
||
var cacheKey = $"{requestMethod}:{requestPath}:{requestId}"; | ||
|
||
var cacheValue = await redisService.GetOrSet(cacheKey, () => request.GetType().Name, TimeSpan.FromMinutes(1)); | ||
|
||
if (string.IsNullOrEmpty(cacheValue)) | ||
return await next(context); | ||
|
||
context.HttpContext.Response.StatusCode = StatusCodes.Status409Conflict; | ||
return TypedResults.Conflict(); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters