1. 程式人生 > >GraphQL教程(二) .net Core api 2.1

GraphQL教程(二) .net Core api 2.1

一、編輯Schema資料夾內容

真正的GraphQL教程才剛剛開始QWQ,怕了吧,Schema的資料夾才是關於Graph的

置於GraphQL是什麼,一種用於 API 的查詢語言

GraphQL 既是一種用於 API 的查詢語言也是一個滿足你資料查詢的執行時。 GraphQL 對你的 API 中的資料提供了一套易於理解的完整描述,使得客戶端能夠準確地獲得它需要的資料,而且沒有任何冗餘,也讓 API 更容易地隨著時間推移而演進,還能用於構建強大的開發者工具。

官網:https://graphql.cn/

據我所知的是GraphQL由facebook所製造,現階段github等一群大佬企業也在用這個
在這裡插入圖片描述

在類庫schema資料夾中新增三個類MovieType,ActorType,MovieRatingEnum
其中MovieRatingEnum是列舉型別,其他的你可以一一對應下
程式碼看不看的懂,看不懂就對了,不然你也不用學了,直接抄吧,抄個一兩遍就有感悟了,到時候再去官網逛逛提升下自己

首先編寫MovieRatingEnum類,直接上程式碼

using GraphQL.Types;
using GraphStudy.Movies.Movies;

namespace GraphStudy.Movies.Schema
{
    public class MovieRatingEnum:EnumerationGraphType<MovieRatingEnum>
    {
        //先定義下建構函式,列表列舉的GraphQL
        public MovieRatingEnum()
        {
            Name = "MovieRating";//型別的名字
            Description = "";//型別的描述

            //將滑鼠置於AddValue上顯示name,description,value,[deprecationReason]  []的含義是可填可不填的意思
            AddValue(MovieRating.Unrated.ToString(), "Unrated",MovieRating.Unrated);
            AddValue(MovieRating.G.ToString(), "G", MovieRating.G);
            AddValue(MovieRating.PG.ToString(), "PG", MovieRating.PG);
            AddValue(MovieRating.PG13.ToString(), "PG13", MovieRating.PG13);
            AddValue(MovieRating.R.ToString(), "R", MovieRating.R);
            AddValue(MovieRating.NC17.ToString(), "NC17", MovieRating.NC17);
        }
    }
}

編寫ActorType類,直接上程式碼

using GraphQL.Types;
using GraphStudy.Movies.Movies;

namespace GraphStudy.Movies.Schema
{
    public class ActorType:ObjectGraphType<Actor>
    {
        public ActorType()
        {
            Field(x => x.Id);
            Field(x => x.Name);
        }
    }
}

編寫MovieType類

using GraphQL.Types;
using GraphStudy.Movies.Movies;
using GraphStudy.Movies.Services;

namespace GraphStudy.Movies.Schema
{
    public class MovieType:ObjectGraphType<Movie>
    {
        //先定義下建構函式
        public MovieType(IActorService actorService)
        {
            Name = "Movie";//型別的名字
            Description = "";//型別的描述

            Field(x => x.Id);
            Field(x => x.Name);
            Field(x => x.Company);
            Field(x => x.ReleaseDate);
            Field(x => x.ActorId);

            //將列舉的Graph也加入其中,這是在查詢Movie中巢狀(學過sql應該懂得巢狀查詢)一個MovieRatingEnum
            //取名movieRating,查詢結果context.Source.MovieRating
            Field<MovieRatingEnum>("movieRating", resolve: context => context.Source.MovieRating);

            Field<ActorType>("Actor", resolve: context => actorService.GetByIdAsync(context.Source.ActorId));

            //做一個小小的測試
            Field<StringGraphType>("customString", resolve: context => "1234");
        }
    }
}

在Schema資料夾中進行新增查詢類MoviesQuery

using GraphQL.Types;
using GraphStudy.Movies.Services;

namespace GraphStudy.Movies.Schema
{
    //查詢
    class MoviesQuery:ObjectGraphType
    {
        public MoviesQuery(IMovieService movieService)
        {
            Name = "Query";

            //查詢所有Movie
            Field<ListGraphType<MovieType>>("movies", resolve: context => movieService.GetAsyncs());
        }
    }
}

在Service資料夾內新增MovieSchema類,以後的增刪改查都在此新增服務

using GraphQL;

namespace GraphStudy.Movies.Schema
{
    class MovieSchema:GraphQL.Types.Schema
    {
        public MovieSchema(IDependencyResolver dependencyResolver, MoviesQuery moviesQuery)
        {
            DependencyResolver = dependencyResolver;
            Query = moviesQuery;
        }
    }
}

在startup新增服務

services.AddSingleton<ActorType>();
            services.AddSingleton<MovieRatingEnum>();
            services.AddSingleton<MovieType>();
            services.AddSingleton<MoviesQuery>();
            services.AddSingleton<MovieSchema>();

            services.AddSingleton<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));

在這裡插入圖片描述

2.呼叫GraphQL 的UI介面

進入GraphQL的github
https://github.com/graphql-dotnet

在這裡插入圖片描述

找到這個在這裡插入圖片描述

GraphStudy.Api在NuGet程式包新增這三個包
GraphQL.Server.Transports.AspNetCore
GraphQL.Server.Transports.WebSockets
GraphQL.Server.Ui.Playground
在這裡插入圖片描述

在這裡插入圖片描述

將途中的複製下來
在這裡插入圖片描述

在這裡插入圖片描述

在這裡插入圖片描述
startup全部程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using GraphQL;
using GraphQL.Server;
using GraphQL.Server.Ui.Playground;
using GraphStudy.Movies.Schema;
using GraphStudy.Movies.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;


namespace GraphStudy.Api
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<IMovieService, MovieService>();
            services.AddSingleton<IActorService, ActorService>();

            services.AddSingleton<ActorType>();
            services.AddSingleton<MovieRatingEnum>();
            services.AddSingleton<MovieType>();
            services.AddSingleton<MoviesQuery>();
            services.AddSingleton<MovieSchema>();

            services.AddSingleton<IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService));


            // Add GraphQL services and configure options
            services.AddGraphQL(options =>
                {
                    options.EnableMetrics = true;
                    options.ExposeExceptions = true;//是否包容異常,改下
                })
                .AddWebSockets() // Add required services for web socket support
                .AddDataLoader(); // Add required services for DataLoader support
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // this is required for websockets support
            app.UseWebSockets();

            // use websocket middleware for ChatSchema at path /graphql
            app.UseGraphQLWebSockets<MovieSchema>("/graphql");

            // use HTTP middleware for ChatSchema at path /graphql
            app.UseGraphQL<MovieSchema>("/graphql");

            //去點另外兩個UI,因為我們剛剛新增的包就是Playground,所以保留這個就行
            // use graphql-playground middleware at default url /ui/playground
            app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());

        }
    }
}

在這裡插入圖片描述
執行成功
query{
movies{
id
name
company
movieRating
releaseDate
actorId
customString
}
}
是類似sql的查詢語句,GraphQL獨有
可參閱官方學習,或者以後教
https://github.com/1045683477/GraphQL-
這是到現在的寫的,程式碼在GitHub上