12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- using System.Collections.Generic;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- using Luticate2.Utils.Dbo.Result;
- using Microsoft.AspNetCore.Mvc.ModelBinding;
-
- namespace Luticate2.Utils.Dbo.Filter
- {
- public class LuFilterBinder : IModelBinder
- {
- private const string RegExp = "^([\\w\\-]+) *: *([^ \"\']+|\"[^\"]*\"|\'[^\']*\') *";
-
- public static LuResult<LuFilterDbo> FromString(string data)
- {
- if (data == null)
- {
- data = "";
- }
- var filters = new Dictionary<string, string>();
-
- Match match;
- do
- {
- match = Regex.Match(data, RegExp);
- if (match.Success)
- {
- var key = match.Groups[1].Value;
- var value = match.Groups[2].Value;
- if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
- (value.StartsWith("\'") && value.EndsWith("\'")))
- {
- value = value.Remove(value.Length - 1, 1).Remove(0, 1).Trim();
- }
- if (!filters.ContainsKey(key))
- {
- filters.Add(key, value);
- }
- else
- {
- filters[key] = value;
- }
- data = data.Remove(match.Index, match.Length);
- }
- } while (match.Success);
-
-
- var dbo = new LuFilterDbo
- {
- Query = data.Trim(),
- Filters = filters
- };
- return LuResult<LuFilterDbo>.Ok(dbo);
- }
-
- public Task BindModelAsync(ModelBindingContext bindingContext)
- {
- var messageTypeResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
- var res = FromString(messageTypeResult.FirstValue);
- if (res)
- {
- bindingContext.Result = ModelBindingResult.Success(res.Data);
- }
- else
- {
- bindingContext.Result = ModelBindingResult.Failed();
- }
- return Task.FromResult(0);
- }
- }
-
- public class LuFilterBinderProvider : IModelBinderProvider
- {
- public IModelBinder GetBinder(ModelBinderProviderContext context)
- {
- if (context.Metadata.ModelType == typeof(LuFilterDbo))
- {
- return new LuFilterBinder();
- }
- return null;
- }
- }
- }
|