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 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using Luticate2.Auth.Utils.Dbo;
  5. using Luticate2.Auth.Utils.Dbo.Fields;
  6. using Luticate2.Auth.Utils.Dbo.Result;
  7. using Luticate2.Auth.Utils.Interfaces;
  8. namespace Luticate2.Auth.Utils.Business.ObjectConverter
  9. {
  10. public class LuObjectConverterLists : ILuObjectConverter
  11. {
  12. protected IServiceProvider ServiceProvider { get; }
  13. public LuObjectConverterLists(IServiceProvider serviceProvider)
  14. {
  15. ServiceProvider = serviceProvider;
  16. }
  17. public LuResult<object> Convert(object srcObj, object dstObj, LuFieldDbo path, LuPartialFieldsDbo fields, ILuObjectConverterOptions options)
  18. {
  19. if (srcObj is IEnumerable enumerable)
  20. {
  21. foreach (var subSrcObj in enumerable)
  22. {
  23. object convertedObj = null;
  24. if (subSrcObj != null)
  25. {
  26. var typeFrom = subSrcObj.GetType();
  27. var typeTo = options.TypeConverter.ConvertType(typeFrom);
  28. // TODO Handle converter == null
  29. var converter = LuObjectConverterUtils.GetObjectConverter(ServiceProvider, typeFrom, typeTo);
  30. var subDstObj = options.Allocator.GetInstance(typeTo);
  31. var convertResult = converter.Convert(subSrcObj, subDstObj, path, fields, options);
  32. if (!convertResult)
  33. {
  34. return convertResult;
  35. }
  36. convertedObj = convertResult.Data;
  37. }
  38. var methodInfo = dstObj.GetType().GetMethod(nameof(ICollection<object>.Add));
  39. methodInfo.Invoke(dstObj, new []{convertedObj});
  40. }
  41. return LuResult<object>.Ok(dstObj);
  42. }
  43. else
  44. {
  45. return LuResult<object>.Error(LuStatus.InputError.ToInt(), $"Could not convert {nameof(srcObj)} to {nameof(IEnumerable)}");
  46. }
  47. }
  48. }
  49. }