using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Timeline.Entities; using Timeline.Models.Validation; namespace Timeline.Services { internal static class DatabaseExtensions { /// /// 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, UsernameValidator validator, string username) { if (username == null) throw new ArgumentNullException(nameof(username)); var (result, messageGenerator) = validator.Validate(username); if (!result) throw new UsernameBadFormatException(username, messageGenerator(null)); var userId = await userDbSet.Where(u => u.Name == username).Select(u => u.Id).SingleOrDefaultAsync(); if (userId == 0) throw new UserNotExistException(username); return userId; } } }