PostResult.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace InABox.Core
  6. {
  7. public interface IPostResult<TPostable>
  8. where TPostable : IPostable
  9. {
  10. /// <summary>
  11. /// All successful or failed <typeparamref name="TPostable"/>s.
  12. /// </summary>
  13. public IEnumerable<TPostable> PostedEntities { get; }
  14. public IEnumerable<TPostable> SuccessfulEntities => PostedEntities.Where(x => x.PostedStatus == PostedStatus.Posted);
  15. public IEnumerable<TPostable> FailedEntities => PostedEntities.Where(x => x.PostedStatus == PostedStatus.PostFailed);
  16. public IEnumerable<KeyValuePair<Type, IEnumerable<IPostableFragment<TPostable>>>> Fragments { get; }
  17. }
  18. public class PostResult<TPostable> : IPostResult<TPostable>
  19. where TPostable : IPostable
  20. {
  21. private List<TPostable> posts = new List<TPostable>();
  22. private Dictionary<Type, List<IPostableFragment<TPostable>>> fragments = new Dictionary<Type, List<IPostableFragment<TPostable>>>();
  23. /// <summary>
  24. /// All successful or failed <typeparamref name="TPostable"/>s.
  25. /// </summary>
  26. public IEnumerable<TPostable> PostedEntities => posts;
  27. public IEnumerable<KeyValuePair<Type, IEnumerable<IPostableFragment<TPostable>>>> Fragments =>
  28. fragments.Select(x => new KeyValuePair<Type, IEnumerable<IPostableFragment<TPostable>>>(x.Key, x.Value));
  29. public void AddSuccess(TPostable post)
  30. {
  31. post.Post();
  32. posts.Add(post);
  33. }
  34. public void AddFailed(TPostable post, string note)
  35. {
  36. post.FailPost(note);
  37. posts.Add(post);
  38. }
  39. public void AddFragment(IPostableFragment<TPostable> fragment)
  40. {
  41. var type = fragment.GetType();
  42. if (!fragments.TryGetValue(type, out var fragmentsList))
  43. {
  44. fragmentsList = new List<IPostableFragment<TPostable>>();
  45. fragments[type] = fragmentsList;
  46. }
  47. fragmentsList.Add(fragment);
  48. }
  49. }
  50. }