From 81b3fc43a900857443c3c763f52e0a54719c2fae Mon Sep 17 00:00:00 2001 From: transtrike Date: Wed, 3 Feb 2021 02:59:21 +0200 Subject: User-Friends Relation Fixed --- src/DevHive.Services/Services/UserService.cs | 53 +++++++++++++++++----------- 1 file changed, 33 insertions(+), 20 deletions(-) (limited to 'src/DevHive.Services/Services/UserService.cs') diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index c8624ee..09b56c1 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -109,12 +109,15 @@ namespace DevHive.Services.Services User user = await this.PopulateModel(updateUserServiceModel); + await this.CreateRelationToFriends(user, updateUserServiceModel.Friends.ToList()); + bool successful = await this._userRepository.EditAsync(updateUserServiceModel.Id, user); if (!successful) throw new InvalidOperationException("Unable to edit user!"); - return this._userMapper.Map(user); + return this._userMapper.Map( + await this._userRepository.GetByIdAsync(user.Id)); } #endregion @@ -269,25 +272,6 @@ namespace DevHive.Services.Services else user.Roles = (await this._userRepository.GetByIdAsync(updateUserServiceModel.Id)).Roles; - /* Fetch Friends and replace model's*/ - HashSet friends = new(); - int friendsCount = updateUserServiceModel.Friends.Count; - for (int i = 0; i < friendsCount; i++) - { - User friend = await this._userRepository.GetByUsernameAsync(updateUserServiceModel.Friends.ElementAt(i).UserName) ?? - throw new ArgumentException("Invalid friend's username!"); - - UserFriends relation = new() - { - UserId = user.Id, - User = user, - FriendId = friend.Id, - Friend = friend - }; - friends.Add(relation); - } - user.Friends = friends; - /* Fetch Languages and replace model's*/ HashSet languages = new(); int languagesCount = updateUserServiceModel.Languages.Count; @@ -314,6 +298,35 @@ namespace DevHive.Services.Services return user; } + + private async Task CreateRelationToFriends(User user, List friends) + { + foreach (var friend in friends) + { + User amigo = await this._userRepository.GetByUsernameAsync(friend.UserName) ?? + throw new ArgumentException("No amigo, bro!"); + + UserFriend relation = new() + { + UserId = user.Id, + User = user, + FriendId = amigo.Id, + Friend = amigo + }; + + UserFriend theOtherRelation = new() + { + UserId = amigo.Id, + User = amigo, + FriendId = user.Id, + Friend = user + }; + + user.MyFriends.Add(relation); + user.FriendsOf.Add(theOtherRelation); + } + return true; + } #endregion } } -- cgit v1.2.3