77 lines
2.2 KiB
C#
77 lines
2.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using AutoMapper;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using TOOHUCardAPI.Data.Models;
|
|
|
|
namespace TOOHUCardAPI.Data.Repositories
|
|
{
|
|
public class UserRepository
|
|
{
|
|
private readonly AppDbContext _appDbContext;
|
|
private readonly IMapper _mapper;
|
|
|
|
public UserRepository(AppDbContext appDbContext, IMapper mapper)
|
|
{
|
|
_appDbContext = appDbContext;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
private IQueryable<User> GetAllUsersQuery()
|
|
{
|
|
return _appDbContext.Users
|
|
.Include(u => u.EncodedCardGroups)
|
|
.Include(u => u.CardLevels)
|
|
.ThenInclude(cl => cl.Card)
|
|
.AsSingleQuery()
|
|
.AsQueryable();
|
|
}
|
|
|
|
public async Task<User> GetUser(string steamId, bool allowNull = false)
|
|
{
|
|
User user = await GetAllUsersQuery().FirstOrDefaultAsync(user => user.SteamId.Equals(steamId));
|
|
if (user == null && !allowNull)
|
|
{
|
|
throw new InvalidUserException();
|
|
}
|
|
|
|
return user;
|
|
}
|
|
|
|
public async Task<User> CreateUser(string steamId)
|
|
{
|
|
User user = new User()
|
|
{
|
|
SteamId = steamId,
|
|
Vip = true,
|
|
EndTime = DateTime.MaxValue,
|
|
PetLevel = 1,
|
|
EncodedCardGroups = new List<EncodedCardGroup>()
|
|
};
|
|
await _appDbContext.Users.AddAsync(user);
|
|
await _appDbContext.SaveChangesAsync();
|
|
return user;
|
|
}
|
|
|
|
public async Task<User> UpdateUser(User user)
|
|
{
|
|
var trackedUser = GetAllUsersQuery().FirstOrDefault(u => u.SteamId == user.SteamId);
|
|
if (trackedUser == default)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
_appDbContext.Update(user);
|
|
await _appDbContext.SaveChangesAsync();
|
|
return user;
|
|
}
|
|
|
|
public async Task<User> GetOrCreateUser(string steamId)
|
|
{
|
|
User user = await GetUser(steamId, true) ?? await CreateUser(steamId);
|
|
return user;
|
|
}
|
|
}
|
|
} |