ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

GraphQL:打造自己的Directive库

2022-02-01 16:02:09  阅读:175  来源: 互联网

标签:name Directive GraphQL context var new 打造 public Name


  GraphQL 既是一种用于 API 的查询语言也是一个满足你数据查询的运行时。GraphQL 对你的 API 中的数据提供了一套易于理解的完整描述,使得客户端能够准确地获得它需要的数据,而且没有任何冗余,也让 API 更容易地随着时间推移而演进,还能用于构建强大的开发者工具。

                                        ——出自 https://graphql.cn

  HotChocolate可以通过自定义Directive来对字段的值进行转换和处理,下在的例子就是给字符串给字符串类型的值转大写和替换。

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

namespace GraphQLBase003
{
    class Program
    {
        static void Main(string[] args)
{
            DirectiveDemo.Run();
        }
    }
  
    public class DirectiveDemo
    {
        public static void Run()
{
            var schema = SchemaBuilder.New()
                .AddProjections()
                .AddQueryType<Query>()
                .AddDirectiveType<UpperDirectiveType>()
                .AddDirectiveType<ReplaceDirectiveType>()
                .Create();
            var executor = schema.MakeExecutable();
            Console.WriteLine("原name=abcde ");
            Console.WriteLine("--------------转大写-------------------");
            Console.WriteLine(executor.Execute("{ student{id name @upper(name:\"this is test\")  age} }").ToJson());
            Console.WriteLine("--------------a替换成1 -------------------");
            Console.WriteLine(executor.Execute("{ student{id name @replace(old:\"a\",new:\"1\")  age} }").ToJson());
            Console.WriteLine("--------------然后全部转大写-.a替换成1 -------------------");
            Console.WriteLine(executor.Execute("{ student{id name @upper(name:\"this is test\") @replace(old:\"a\",new:\"1\")  age} }").ToJson());
            Console.WriteLine("--------------a替换成1.然后全部转大写-------------------");
            Console.WriteLine(executor.Execute("{ student{id name @replace(old:\"a\",new:\"1\")  @upper(name:\"this is test\") age} }").ToJson());
        }
        public class Query
        {
            [UseProjection]
            public Student GetStudent()
{
                return new Student
                {
                    Id = 1,
                    Name = "abcde",
                    Age = 234
                };
            }
            [UseProjection]
            public List<Student> GetStudents()
            {
                return new List<Student>{
                    new Student
                    {
                        Id = 100,
                        Name = "aBcD",
                        Age=10
                    },
                    new Student
                    {
                        Id = 101,
                        Name = "EFGH",
                        Age=20
                    }
                };
            }
        }
        public class Student
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public int Age { get; set; }
        }

        public class UpperDirectiveType : DirectiveType<UpperDirective>
        {
            protected override void Configure(IDirectiveTypeDescriptor<UpperDirective> descriptor)
{
                descriptor.Name("upper");
                descriptor.Location(DirectiveLocation.Field);
                descriptor.Use(next => context =>
                {
                    foreach (var directive in context.FieldSelection.Directives)
                    {
                        if (directive.Name.Value == "upper")
                        {
                            if (context.Field.Member.MemberType == System.Reflection.MemberTypes.Property)
                            {
                                var pro = context.Field.Member as PropertyInfo;
                                var obj = context.GetType().GetMethod("Parent").MakeGenericMethod(context.ObjectType.RuntimeType).Invoke(context, new object[0]);
                                var value = pro.GetValue(obj);
                                pro.SetValue(obj, value.ToString().ToUpper());                            
                            }
                        }
                    }
                    return next.Invoke(context);
                });
            }
        }

        public class UpperDirective
        {
            public string Name
            {
                get;
                set;
            }
        }

        public class ReplaceDirectiveType : DirectiveType<ReplaceDirective>
        {

            protected override void Configure(IDirectiveTypeDescriptor<ReplaceDirective> descriptor)
{
                descriptor.Name("replace");
                descriptor.Location(DirectiveLocation.Field);
                descriptor.Use(next => context =>
                {
                    foreach (var directive in context.FieldSelection.Directives)
                    {
                        if (directive.Name.Value == "replace")
                        {
                            var dir = new Dictionary<string, object>();
                            foreach (var item in directive.Arguments)
                            {
                                dir.Add(item.Name.Value?.ToLower(), item.Value.Value);
                            }
                            if (context.Field.Member.MemberType == System.Reflection.MemberTypes.Property)
                            {                                
                                var s = context.Parent<Student>();
                                var pro = context.Field.Member as PropertyInfo;
                                var obj = context.GetType().GetMethod("Parent").MakeGenericMethod(context.ObjectType.RuntimeType).Invoke(context, new object[0]);
                                var value = pro.GetValue(obj);
                                pro.SetValue(obj, value.ToString().Replace(dir["old"].ToString(), dir["new"].ToString()));                                
                            }
                        }
                    }
                    return next.Invoke(context);
                });


            }
        }

        public class ReplaceDirective
        {
            public string Old
            {
                get;
                set;
            }
            public string New
            {
                get;
                set;
            }
        }
    }
}

  upper和replace两个Directive处理的还比较粗糙,这里主要说明Directive的定义方式;在调用这些Directive时,按照前后顺序调用,多个Directive可以同时生效,和asp.net core的中间件原理相近,上例的后两个调用 name @upper @replace和name @replace @upper返回的结果是不一样的。

    想要更快更方便的了解相关知识,可以关注微信公众号   

 

 

标签:name,Directive,GraphQL,context,var,new,打造,public,Name
来源: https://www.cnblogs.com/axzxs2001/p/15859135.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有