using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;
using Timeline.Entities;
using Timeline.Models.Validation;
namespace Timeline.Services
{
internal static class DatabaseExtensions
{
private static readonly UsernameValidator usernameValidator = new UsernameValidator();
///
/// Check the existence and get the id of the user.
///
/// The username of the user.
/// The user id.
/// Thrown if is null.
/// Thrown if is of bad format.
/// Thrown if user does not exist.
internal static async Task CheckAndGetUser(DbSet userDbSet, string? username)
{
if (username == null)
throw new ArgumentNullException(nameof(username));
var (result, message) = usernameValidator.Validate(username);
if (!result)
throw new UsernameBadFormatException(username, message);
var userId = await userDbSet.Where(u => u.Name == username).Select(u => u.Id).SingleOrDefaultAsync();
if (userId == 0)
throw new UserNotExistException(username);
return userId;
}
}
}