Browse Source

1、Bogus模拟数据
2、处理cosmos查询value为空、数组为空数组

李思淳 5 years ago
parent
commit
30bd9f8d58

+ 47 - 3
TEAMModelOS.SDK/Module/AzureCosmosDBV3/SQLHelperParametric.cs

@@ -71,11 +71,47 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
             return sql;
         }
 
-        public static CosmosDbQuery GetSQL(Dictionary<string, object> dict, StringBuilder sql)
+        public static void DictIsNotNULL(Dictionary<string, object> dict)
         {
+            Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
+            foreach (KeyValuePair<string, object> keyValuePair in dict)
+            {
+                if (keyValuePair.Value is JArray array)
+                {
+                    if (array == null || array.Count == 0) keyValuePairs.Add(keyValuePair.Key, keyValuePair.Value);
+                }
+                else if (keyValuePair.Value is IList enumerable && !(keyValuePair.Value is String))
+                {
+                    if (enumerable == null || enumerable.Count == 0) keyValuePairs.Add(keyValuePair.Key, keyValuePair.Value);
+                }
+                else if (keyValuePair.Value is JsonElement jsonElement && jsonElement.ValueKind is JsonValueKind.Array)
+                {
 
+                    if (jsonElement.EnumerateArray().Count() == 0)
+                    {
+                        keyValuePairs.Add(keyValuePair.Key, keyValuePair.Value);
+                    }
+                }
+                else if (keyValuePair.Value is null)
+                {
+                    keyValuePairs.Add(keyValuePair.Key, keyValuePair.Value);
+                }
+            }
+
+            if (keyValuePairs.Count > 0)
+            {
+                foreach (KeyValuePair<string, object> keyValuePair in keyValuePairs)
+                {
+                    dict.Remove(keyValuePair.Key);
+                }
+            }
+        }
+
+        public static CosmosDbQuery GetSQL(Dictionary<string, object> dict, StringBuilder sql)
+        {
             if (dict != null)
             {
+                DictIsNotNULL(dict);
                 Dictionary<string, object> parmeters = new Dictionary<string, object>();
 
                 int offsetNum = 0;
@@ -245,9 +281,13 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
                     sql.Append(" OFFSET " + " @offsetNum " + " LIMIT " + " @limitNum ");
                 }
 
-
+                //替换关键字
                 ReplaceKeyWords(ref sql);
+
+                //参数化查询拼接 参数dict
                 parmeters = GetParmeter(dict, parmeters, offsetNum, limitNum);
+
+
                 CosmosDbQuery cosmosDbQuery = new CosmosDbQuery
                 {
                     QueryText = sql.ToString(),
@@ -535,7 +575,7 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
                         aa++;
                     }
                 }
-                else if (value is JsonElement jsonElement && jsonElement.ValueKind! is JsonValueKind.Array)
+                else if (value is JsonElement jsonElement && jsonElement.ValueKind is JsonValueKind.Array)
                 {
                     int aa = 0;
                     foreach (JsonElement obja in jsonElement.EnumerateArray().ToArray())
@@ -562,6 +602,10 @@ namespace TEAMModelOS.SDK.Module.AzureCosmosDBV3
                     {
                         sql1 = logicOper + "Contains(  c." + key + " ,  @" + key1 + " ) = " + compareOperBool + " ";
                     }
+                    if (value is JsonElement jsonElement1 && jsonElement1.ValueKind is JsonValueKind.String)
+                    {
+                        sql1 = logicOper + "Contains(  c." + key + " ,  @" + key1 + " ) = " + compareOperBool + " ";
+                    }
                     else
                     {
                         sql1 = logicOper + "Contains(  ToString( c." + key + " ),  \'@" + key1 + "\' ) = " + compareOperBool + " ";

+ 37 - 1
TEAMModelOS/Controllers/Test/TestController.cs

@@ -5,18 +5,54 @@ using System.Threading.Tasks;
 using Microsoft.AspNetCore.Authorization;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
+using TEAMModelOS.Models;
+using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
+using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
+using TEAMModelOS.SDK.Module.AzureCosmosDBV3;
 
 namespace TEAMModelOS.Controllers.Test
 {
-    [Authorize]
+    //[Authorize]
     [Route("[controller]")]
     [ApiController]
     public class TestController : ControllerBase
     {
+        private readonly IAzureCosmosDBV3Repository azureCosmosDBRepository;
+
+        public TestController(IAzureCosmosDBV3Repository azureCosmosDBRepository)
+        {
+            this.azureCosmosDBRepository = azureCosmosDBRepository;
+        }
+
         [HttpGet]
         public IActionResult Get()
         {
             return new JsonResult(new { a="aa", c="bb" });
         }
+
+
+        [HttpPost("SimulatedData")]
+        public async Task<List<Family>> SimulatedDataAsync(string request)
+        {
+            var repository = new SampleCustomerRepository();
+            List<Family> customers = repository.GetCustomers().ToList();
+            List<Family> customers1 = await azureCosmosDBRepository.SaveAll<Family>(customers);
+            return customers;
+        }
+
+
+        [HttpPost("FindKnowledge")]
+        public async Task<BaseJosnRPCResponse> FindSchoolPointByDict(JosnRPCRequest<Dictionary<string, object>> request)
+        {
+          JsonRPCResponseBuilder builder = JsonRPCResponseBuilder.custom();
+            List<string> st = new List<string> { "FamilyOrder", "LastName","Children", "Parents" , "Address" };
+            //List<Family> families = await azureCosmosDBRepository.FindAll<Family>(propertys: st);
+            Dictionary<string,object > keyValuePairs = new Dictionary<string, object>();
+            List<Family> families1 = new List<Family>();
+            keyValuePairs.Add("aaaa", families1);
+            List<Family> families = await azureCosmosDBRepository.FindByDict<Family>(dict: keyValuePairs, propertys: st);
+
+          return builder.Data(families).Extend(new Dictionary<string, object> { {"Count", families.Count } }).build();
+        }
     }
 }

+ 55 - 0
TEAMModelOS/Models/Family.cs

@@ -0,0 +1,55 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+using TEAMModelOS.SDK.Context.Attributes.Azure;
+using TEAMModelOS.SDK.Module.AzureCosmosDBV3;
+
+namespace TEAMModelOS.Controllers.Test
+{
+    [CosmosDB(RU = 400, Name = "Family")]
+    public class Family : ID
+    {
+        // public string Id { get; set; }
+        public int FamilyOrder { get; set; }
+        public string LastName { get; set; }
+        [PartitionKey]
+        public string PartitionKey { get; set; } = "aaaaaaaa";
+        public List<Parent> Parents { get; set; }
+        public List<Child> Children { get; set; }
+        public Address Address { get; set; }
+        public bool IsRegistered { get; set; }
+        public string id { get; set; }
+        // The ToString() method is used to format the output, it's used for demo purpose only. It's not required by Azure Cosmos DB
+
+    }
+
+    public class Parent
+    {
+        public string FamilyName { get; set; }
+        public string FirstName { get; set; }
+    }
+
+    public class Child
+    {
+        public string FamilyName { get; set; }
+        public string FirstName { get; set; }
+        public string Gender { get; set; }
+        public int Grade { get; set; }
+        public double Score { get; set; }
+        public List<Pet> Pets { get; set; }
+    }
+
+    public class Pet
+    {
+        public string GivenName { get; set; }
+        public int Age { get; set; }
+    }
+
+    public class Address
+    {
+        public string State { get; set; }
+        public string County { get; set; }
+        public string City { get; set; }
+    }
+}

+ 55 - 0
TEAMModelOS/Models/SampleCustomerRepository.cs

@@ -0,0 +1,55 @@
+using Bogus;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace TEAMModelOS.Controllers.Test
+{
+    public class SampleCustomerRepository
+    {
+        public enum Gender
+        {
+            Male,
+            Female
+        }
+        public IEnumerable<Family> GetCustomers()
+        {
+       
+
+        //Randomizer.Seed = new Random(123456);
+        var parent = new Faker<Parent>("zh_CN")
+                .RuleFor(o => o.FamilyName, f => f.Name.FirstName())
+                .RuleFor(o => o.FirstName, f => f.Name.LastName());
+
+            var pet = new Faker<Pet>("zh_CN")
+              .RuleFor(o => o.GivenName, f => f.Name.FullName())
+               .RuleFor(o => o.Age, f => f.Random.Number(0,13));
+
+            var child = new Faker<Child>("zh_CN")
+             .RuleFor(o => o.FamilyName, f => f.Name.FirstName())
+             .RuleFor(o => o.FirstName, f => f.Name.FirstName())
+             .RuleFor(o => o.Gender, f => f.PickRandom<Gender>().ToString())
+             .RuleFor(o => o.Grade, f => f.Random.Number(1, 16))
+             .RuleFor(o => o.Score, f => f.Random.Double(30, 100))
+             .RuleFor(o => o.Pets, f => pet.Generate(f.Random.Number(1, 4)).ToList());
+
+            var address = new Faker<Address>("zh_CN")
+           .RuleFor(o => o.State, f => f.Address.State())
+           .RuleFor(o => o.County, f => f.Address.Country())
+           .RuleFor(o => o.City, f => f.Address.City());
+
+            var orderIds = 0;
+            var customerGenerator = new Faker<Family>("zh_CN")
+                .RuleFor(c => c.FamilyOrder, f => orderIds++)
+                .RuleFor(c => c.id, f =>f.Random.Guid().ToString())//Guid.NewGuid().ToString()
+                .RuleFor(c => c.LastName, f => f.Name.LastName())
+                .RuleFor(c => c.IsRegistered, f => f.Random.Bool())
+                .RuleFor(c => c.Parents, f => parent.Generate(f.Random.Number(2,2)).ToList())
+                .RuleFor(c => c.Children, f => child.Generate(f.Random.Number(1,3)).ToList())
+                .RuleFor(c => c.Address, f => address.Generate(1).ToList()[0]);
+
+            return customerGenerator.Generate(350);
+        }
+    }
+}

+ 1 - 0
TEAMModelOS/TEAMModelOS.csproj

@@ -10,6 +10,7 @@
   </PropertyGroup>
 
   <ItemGroup>
+    <PackageReference Include="Bogus" Version="29.0.1" />
     <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.0.0" />
     <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.0.0" />
     <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.0.0" />