You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuObjectConverterLists.cs 3.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using Luticate2.Auth.Utils.Dbo;
  6. using Luticate2.Auth.Utils.Dbo.Fields;
  7. using Luticate2.Auth.Utils.Dbo.Result;
  8. using Luticate2.Auth.Utils.Interfaces;
  9. namespace Luticate2.Auth.Utils.Business.ObjectConverter
  10. {
  11. public abstract class LuObjectConverterLists : ILuObjectConverter
  12. {
  13. protected IServiceProvider ServiceProvider { get; }
  14. public LuObjectConverterLists(IServiceProvider serviceProvider)
  15. {
  16. ServiceProvider = serviceProvider;
  17. }
  18. protected abstract Type GetListType();
  19. public LuResult<object> Convert(object srcObj, LuFieldDbo path, LuPartialFieldsDbo fields, ILuObjectConverterOptions options)
  20. {
  21. if (srcObj is IEnumerable enumerable)
  22. {
  23. var listType = GetListType();
  24. var listTypeTo = options.TypeConverter.ConvertType(srcObj.GetType().GetGenericArguments()[0]);
  25. var glistType = listType.MakeGenericType(listTypeTo);
  26. var collection = options.Allocator.GetInstance(glistType);
  27. foreach (var obj in enumerable)
  28. {
  29. object convertedObj = null;
  30. if (obj != null)
  31. {
  32. var typeFrom = obj.GetType();
  33. var typeTo = options.TypeConverter.ConvertType(typeFrom);
  34. // TODO Handle converter == null
  35. var converter = LuObjectConverterUtils.GetObjectConverter(ServiceProvider, typeFrom, typeTo);
  36. var convertResult = converter.Convert(obj, path, fields, options);
  37. if (!convertResult)
  38. {
  39. return convertResult;
  40. }
  41. convertedObj = convertResult.Data;
  42. }
  43. var methodInfo = collection.GetType().GetMethod(nameof(ICollection<object>.Add));
  44. methodInfo.Invoke(collection, new []{convertedObj});
  45. }
  46. return LuResult<object>.Ok(collection);
  47. }
  48. else
  49. {
  50. return LuResult<object>.Error(LuStatus.InputError.ToInt(), $"Could not convert {nameof(srcObj)} to {nameof(IEnumerable)}");
  51. }
  52. }
  53. }
  54. public class LuObjectConverterList : LuObjectConverterLists
  55. {
  56. public LuObjectConverterList(IServiceProvider serviceProvider) : base(serviceProvider)
  57. {
  58. }
  59. protected override Type GetListType()
  60. {
  61. return typeof(List<>);
  62. }
  63. }
  64. public class LuObjectConverterCollection : LuObjectConverterLists
  65. {
  66. public LuObjectConverterCollection(IServiceProvider serviceProvider) : base(serviceProvider)
  67. {
  68. }
  69. protected override Type GetListType()
  70. {
  71. return typeof(Collection<>);
  72. }
  73. }
  74. }