using FoodsharingSiegen.Contracts; using FoodsharingSiegen.Contracts.Entity; using Microsoft.EntityFrameworkCore; namespace FoodsharingSiegen.Server.Data.Service { public class UserService : ServiceBase { public UserService(FsContext context) : base(context) { } public async Task> AddUserAsync(User user) { try { if (await Context.Users.AnyAsync(x => x.Mail.ToLower().Equals(user.Mail.ToLower()))) return new OperationResult(new Exception("Diese E-Mail Adresse wird bereits verwendet")); user.Created = DateTime.UtcNow; if (string.IsNullOrWhiteSpace(user.Password)) user.Password = string.Empty; await Context.Users.AddAsync(user); var saveResult = await Context.SaveChangesAsync(); if (saveResult == 0) return new OperationResult(new Exception("Fehler bei der Registrierung")); return new OperationResult(user); } catch (Exception e) { return new OperationResult(e); } } public async Task Update(User user) { try { var entityUser = await Context.Users.FirstOrDefaultAsync(x => x.Id == user.Id); if (entityUser == null) return new OperationResult(new Exception("User not found")); entityUser.Mail = user.Mail; entityUser.Name = user.Name; entityUser.Type = user.Type; entityUser.Verified = user.Verified; entityUser.Groups = user.Groups; var saveR = await Context.SaveChangesAsync(); if(saveR < 1) return new OperationResult(new Exception("Fehler beim speichern")); return new OperationResult(); } catch (Exception e) { return new OperationResult(e); } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// Gets users asynchronous. /// /// A Beging, 20.10.2021. /// /// An asynchronous result that yields the users. //////////////////////////////////////////////////////////////////////////////////////////////////// public async Task>> GetUsersAsync() { try { var users = await Context.Users.ToListAsync(); return new OperationResult>(users); } catch (Exception e) { return new OperationResult>(e); } } } }