Skip to content

Commit

Permalink
Avoid duplicates
Browse files Browse the repository at this point in the history
  • Loading branch information
JonathanDuvalV committed Mar 23, 2024
1 parent 273f914 commit 45576e6
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
1 change: 1 addition & 0 deletions core/Repositories/Abstractions/IReportRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ namespace api.core.repositories.abstractions;

public interface IReportRepository: IRepository<Report>
{
public IEnumerable<Report> GetRecentReports(int lastSeconds);
}
10 changes: 8 additions & 2 deletions core/Repositories/ReportRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,14 @@ public bool Delete(Report entity)
public IEnumerable<Report> GetAll()
{
return context.Reports
.Include(r => r.Publication)
.ToList();
.Include(r => r.Publication);
}

public IEnumerable<Report> GetRecentReports(int lastSeconds)
{
return context.Reports
.Where(r => r.CreatedAt >= DateTime.UtcNow.AddSeconds(-lastSeconds))
.Include(r => r.Publication);
}

public bool Update(Guid id, Report entity)
Expand Down
12 changes: 12 additions & 0 deletions core/Services/ReportService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using api.core.repositories.abstractions;
using api.core.services.abstractions;


namespace api.core.Services;

public class ReportService(IEventRepository eventRepository, IReportRepository reportRepository) : IReportService
Expand All @@ -17,6 +18,8 @@ public IEnumerable<ReportResponseDTO> GetReports()

public void ReportEvent(Guid eventId, CreateReportRequestDTO request)
{
if (AvoidDuplicates(request)) return;

var evnt = eventRepository.Get(eventId);
NotFoundException<Event>.ThrowIfNull(evnt);

Expand All @@ -30,4 +33,13 @@ public void ReportEvent(Guid eventId, CreateReportRequestDTO request)
};
reportRepository.Add(report);
}

private bool AvoidDuplicates(CreateReportRequestDTO request)
{
// If a request with a duplicated reason is submitted within the time window of the rate limiter,
// we ignore the request
var timeWindow = int.Parse(Environment.GetEnvironmentVariable("RATE_LIMIT_TIME_WINDOW_SECONDS") ?? "10");
var reports = reportRepository.GetRecentReports(timeWindow);
return reports.Any(r => r.Reason == request.Reason);
}
}

0 comments on commit 45576e6

Please sign in to comment.