GraphQL-hotchocolate学习:Query操作查询函数映射

我本来计划使用RestfulAPI建立我自己的API服务框架,意外发现GraphQL更好,更有前途,于是决定使用GraphQL。

为什么呢?

因为虽然RestfulAPI号称是面向资源的,而本质上是面向操作的,比如get/put/post等,并且依赖于资源/函数名称(url),这些东西一旦变化,客户端也要跟着修改,所以面临版本管理和兼容性的问题。而GraphQL是面向数据的,可以按需获取,数据架构(Schema)确定之后,增加字段不会造成版本兼容问题。

这里面的区别比较微妙,可以参考https://graphql.cn/实际体验感受一下。

GraphQL只是一个协议,和具体的语言实现无关,我习惯于使用C#语言,所以找了一个.net的实现。

.Net的实现主要有GraphQL.NEThotchocolate两种,比较了一下,最终选择了后者,感觉比较简单一些。

关于Schema模型和查询对象之间的关系,文档中没有详细描述,做了一下实验,对应关系大概如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyGraphQL
{
    public class GraphQLServices
    {
        public List<GraphQLService> Services { get; set; }
    }

    /// <summary>
    /// 一个GraphQL服务
    /// </summary>
    public class GraphQLService
    {
        /// <summary>
        /// 服务名称
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 服务地址,形如:"http://localhost:8888"
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        /// 服务说明
        /// </summary>
        public string Describe { get; set; }
    }

    public class Query
    {
        public GraphQLServices GetGraphQLServices2
        {
            get
            {
                return this.GetGraphQLServices();
            }
        }
        public GraphQLServices GetGraphQLServices()
        {
            GraphQLServices graphQLServices = new();
            GraphQLService graphQLService = new();
            graphQLService.Name = "GraphQLService";
            graphQLService.Url = @"http://localhost:8888";
            graphQLService.Describe = "提供GraphQL的入口服务";
            graphQLServices.Services = new List<GraphQLService>();
            graphQLServices.Services.Add(graphQLService);
            return graphQLServices;
        }
    }
}
View Code

一个类的公共属性和方法,会被映射为查询的对象,例如上面的代码,GetGraphQLServices()函数映射为graphQLServices对象,如果函数不是Get开头,则直接映射为函数名;GetGraphQLServices2属性映射为getGraphQLServices2对象。如下图所示:

 

posted @ 2021-04-24 17:20  顺其自然,道法自然  阅读(227)  评论(0编辑  收藏  举报