GraphQL:Descriptor Attributes

GraphQL 既是一種用於 API 的查詢語言也是一個知足你數據查詢的運行時。GraphQL 對你的 API 中的數據提供了一套易於理解的完整描述,使得客戶端可以準確地得到它須要的數據,並且沒有任何冗餘,也讓 API 更容易地隨着時間推移而演進,還能用於構建強大的開發者工具。ide

——出自 https://graphql.cn

HotChocolate中能夠經過定義Attribute來增長通用性處理功能,以前博文中用過UsePaging分頁,UseFiltering過濾,UseSorting排序,咱們也能夠自定義特性類來達處處理統一數據的做用,下面的例子就是一個脫敏的特性類,能夠在使用特性類時告訴系統那些數據是不顯示出來的,此類就會把數據變成等長的*號字符串來替換。工具

using HotChocolate;
using HotChocolate.Data;
using HotChocolate.Execution;
using HotChocolate.Types;
using HotChocolate.Types.Descriptors;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace GraphQLBase004
{
    class Program
    {
        static void Main(string[] args)
        {
            DescriptorAttributeDemo.Run();
        }
    }
    public class DescriptorAttributeDemo
    {
        public static void Run()
        {
            var schema = SchemaBuilder.New()
                .AddProjections()
                .AddQueryType<Query>()
                .Create();
            var executor = schema.MakeExecutable();
            Console.WriteLine(executor.Execute("{ user{id userName password tel} }").ToJson());
            Console.WriteLine("===============");
            Console.WriteLine(executor.Execute("{ users{id userName password tel} }").ToJson());
        }
        /// <summary>
        /// 查詢類
        /// </summary>
        public class Query
        {
            [UseProjection]
            [UseDesensitization(SensitiveFields = new string[] { "password", "tel" })]
            public User GetUser()
            {
                return new User
                {
                    Id = 1,
                    UserName = "gsw",
                    Tel = "13453467114",
                    Password = "111111"
                };
            }
            [UseProjection]
            [UseDesensitization(SensitiveFields = new string[] { "password", "tel" })]
            public List<User> GetUsers()
            {
                return new List<User>(){
                    new User
                    {
                        Id = 1,
                        UserName = "gsw",
                        Tel = "13453467114",
                        Password = "111111"
                    },
                    new User
                    {
                        Id = 1,
                        UserName = "gsw",
                        Tel = "13453467114",
                        Password = "111111"
                    }
                };
            }
        }
        /// <summary>
        /// 用戶
        /// </summary>
        public class User
        {
            public int Id { get; set; }
            public string UserName { get; set; }
            public string Tel { get; set; }
            public string Password { get; set; }
        }
        /// <summary>
        /// 脫敏特性類
        /// </summary>
        public class UseDesensitizationAttribute : ObjectFieldDescriptorAttribute
        {
            public string[] SensitiveFields
            {
                get; set;
            }
            public override void OnConfigure(IDescriptorContext context, IObjectFieldDescriptor descriptor, MemberInfo member)
            {
                descriptor.Use(next => context =>
                {
                    var obj = context.GetType().GetMethod("Parent").MakeGenericMethod(context.ObjectType.RuntimeType).Invoke(context, new object[0]);
                    var resultObj = (member as MethodInfo).Invoke(obj, new object[0]);
                    foreach (var proName in SensitiveFields)
                    {
                        var resulttType = resultObj.GetType();
                        //處理泛型集合
                        if (resulttType.IsGenericType)
                        {
                            foreach (var resultItem in (resultObj as IList))
                            {

                                SetValue(proName, resultItem.GetType(), resultItem);
                            }
                        }
                        else
                        {
                            SetValue(proName, resulttType, resultObj);
                        }
                        void SetValue(string proName, Type type, object resultObj)
                        {
                            var pro = type.GetProperty(proName, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public);
                            if (pro != null && pro.PropertyType.IsAssignableFrom(typeof(string)))
                            {
                                var len = pro.GetValue(resultObj).ToString()?.Length;
                                pro.SetValue(resultObj, "".PadLeft(len.Value, '*'));
                            }
                        }
                    }
                    context.Result = resultObj;
                    return next.Invoke(context);
                });
            }
        }
    }
}

執行結果:
GraphQL:Descriptor Attributesui

相關文章
相關標籤/搜索