I have a rep with Media Items Each items can have several bookmarks and comments from different users.
When I come to update the repo I need to get all existing Comments and book marks and append the new comments and book marks, the code works, but i cant think of a clean way to do this generically that will reduce duplication, as more fields like this are planned
public class MapValues
{
private readonly string _userName;
private readonly Media _media;
private readonly IMediaRepository _mediaRepo;
public MapValues(string userName, Media media, IMediaRepository mediaRepo)
{
_userName = userName;
_media = media;
IMediaRepository = mediaRepo;
}
public async Task<Media> AppendExistingUserValues(Media updatedMedia, string userName)
{
var existingMedia = await _mediaRepo.GetByIdAsync(updatedMedia.Id);
var existingBookmarks = GetBookmarksExcludingUser(userName, existingMedia);
var existingComments = GetCommentsExcludingUser(userName, existingMedia);
if (updatedMedia.Bookmarks.Any())
{
existingBookmarks.AddRange(updatedMedia.Bookmarks);
}
if (updatedMedia.Comments.Any())
{
existingComments.AddRange(updatedMedia.Comments);
}
updatedMedia.Bookmarks = existingBookmarks;
updatedMedia.Comments = existingComments;
return updatedMedia;
}
private List<MediaBookmarks> GetBookmarksExcludingUser(string userName, Media media)
{
var exisitingBookmarks = new List<MediaBookmarks>();
if (media?.Bookmarks != null)
{
exisitingBookmarks.AddRange(media.Bookmarks
.Where(x => !string.Equals(x.Name, userName, StringComparison.CurrentCultureIgnoreCase)).ToList());
}
return exisitingBookmarks;
}
private List<MediaComments> GetCommentsExcludingUser(string userName, Media media)
{
var exisitingComments = new List<MediaComments>();
if (media?.Bookmarks != null)
{
exisitingComments.AddRange(media.Comments
.Where(x => !string.Equals(x.Name, userName, StringComparison.CurrentCultureIgnoreCase)).ToList());
}
return exisitingComments;
}
}
public class Media
{
public IEnumerable<MediaBookmarks> Bookmarks { get; set; }
public IEnumerable<MediaComments> Comments { get; set; }
public string Id { get; set; }
}
public class MediaBookmarks
{
public string Name { get; set; }
}
public class MediaComments
{
public string Name { get; set; }
}
Aucun commentaire:
Enregistrer un commentaire