Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add worker service for handling overdue borrow request #191

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/Api/ConfigureServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public static IServiceCollection AddApiServices(this IServiceCollection services
{
// Register services
services.AddServices();

services.AddBackgroundServices();
services.AddControllers(opt =>
opt.Conventions.Add(new RouteTokenTransformerConvention(new SlugifyParameterTransformer())));

Expand Down Expand Up @@ -59,4 +59,11 @@ private static IServiceCollection AddServices(this IServiceCollection services)

return services;
}

private static IServiceCollection AddBackgroundServices(this IServiceCollection services)
{
services.AddHostedService<BorrowRequestService>();

return services;
}
}
43 changes: 43 additions & 0 deletions src/Api/Services/BorrowRequestService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Application.Common.Interfaces;
using Domain.Statuses;
using Infrastructure.Persistence;
using NodaTime;

namespace Api.Services;

public class BorrowRequestService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;

public BorrowRequestService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{

while (!stoppingToken.IsCancellationRequested)
{
using (var scope = _serviceProvider.CreateScope())
{
var localDateTimeNow = LocalDateTime.FromDateTime(DateTime.Now);
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var overdueRequests = context.Borrows
.Where(x => x.Status != BorrowRequestStatus.Overdue
&& x.Status == BorrowRequestStatus.CheckedOut
&& x.DueTime < localDateTimeNow)
.ToList();

foreach (var request in overdueRequests)
{
request.Status = BorrowRequestStatus.Overdue;
}
context.UpdateRange(overdueRequests);

await context.SaveChangesAsync(stoppingToken);
await Task.Delay(TimeSpan.FromMinutes(2), stoppingToken);
}
}
}
}