/
egopen
/
Lab1
Обзор
Документация
Войти
/
egopen
/
Lab1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
Lab4/library/Services/RentService.cs
66 строк
2 KB
Egopen
lab 4
01 ноя 2025, 18:03
01 ноя 2025, 18:03
78d017c
Код
Авторство
О чём код?
using library.DB; using library.DB.Models; using library.Errors; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Caching.Memory; namespace library.Services { public class RentService { private readonly LibraryDBContext _db; private readonly IMemoryCache _memoryCache; public RentService(LibraryDBContext db, IMemoryCache memoryCache) { _db = db; _memoryCache = memoryCache; } public async Task<Rent> RentBook(Guid userId, Guid bookId) { var idempotencyKey = $"rent_book_{userId}_{bookId}"; if (_memoryCache.TryGetValue(idempotencyKey, out Rent cachedRent)) { return cachedRent; } if (!_db.Books.Any(b=>b.Id == bookId)) { throw new NotFoundException("Book not found"); } var existingRent = await _db.Rents .FirstOrDefaultAsync(r => r.BookId == bookId && r.UserId == userId); if (existingRent != null) { throw new NotFoundException("Book in usage"); } Rent rent = new Rent(); rent.UserId = userId; rent.BookId = bookId; rent.Id = Guid.NewGuid(); await _db.Rents.AddAsync(rent); await _db.SaveChangesAsync(); _memoryCache.Set(idempotencyKey, rent, TimeSpan.FromMinutes(10)); return rent; } public async Task<Rent> EndRentBook(Guid rentId) { var rent = await _db.Rents.FirstOrDefaultAsync(r => r.Id == rentId); if (rent == null) { throw new NotFoundException("Rent not found"); } _db.Rents.Remove(rent); await _db.SaveChangesAsync(); return rent; } public async Task<List<Rent>> GetUserRents(Guid userId, int page, int pageSize) { var rents = await _db.Rents.Where(r=>r.UserId==userId).Skip(pageSize * (page-1)).Take(pageSize).ToListAsync(); return rents; } } }