LANCommander/LANCommander.Server.Services/LibraryService.cs
Pat Hartl 62ceffc976 Merge branch 'user-libraries' of https://github.com/LANCommander/LANCommander into user-libraries
# Conflicts:
#	LANCommander.Server.Services/LibraryService.cs
2024-11-12 21:02:28 -06:00

72 lines
2.1 KiB
C#

using LANCommander.Server.Data;
using LANCommander.Server.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZiggyCreatures.Caching.Fusion;
namespace LANCommander.Server.Services
{
public class LibraryService : BaseDatabaseService<Library>
{
private readonly UserService UserService;
private readonly GameService GameService;
public LibraryService(
ILogger<LibraryService> logger,
IFusionCache cache,
Repository<Library> repository,
UserService userService,
GameService gameService) : base(logger, cache, repository)
{
UserService = userService;
GameService = gameService;
}
public async Task<Library> GetByUserIdAsync(Guid userId)
{
var library = await FirstOrDefaultAsync(l => l.User.Id == userId);
if (library == null)
{
var user = await UserService.GetAsync(userId);
if (user == null)
throw new Exception("User not found with ID " + userId.ToString());
library = await AddAsync(new Library { UserId = userId });
}
return library;
}
public async Task AddToLibraryAsync(Guid userId, Guid gameId)
{
var game = await GameService.GetAsync(gameId);
var library = await GetByUserIdAsync(userId);
library.Games.Add(game);
await UpdateAsync(library);
await Cache.ExpireAsync($"LibraryGames:{userId}");
}
public async Task RemoveFromLibraryAsync(Guid userId, Guid gameId)
{
var library = await GetByUserIdAsync(userId);
var game = library.Games.FirstOrDefault(g => g.Id == gameId);
library.Games.Remove(game);
await UpdateAsync(library);
await Cache.ExpireAsync($"LibraryGames:{userId}");
}
}
}