• GraphQL教程(三) .net core api


    GraphQL笔记来源是杨旭视屏教程

    今天学习用添加
    首先需要创建三个类,MovieInput(数据对应的模板类)、MovieInputType(GraphQL需要的类型)、MovieMutation(添加处理)
    第二步是在MovieSchema类对MovieMution进行添加(第二篇文章说过此类用于对增删查改类处理)
    第三步是在startup类中进行注册
    然后就可以用GraphQL进行添加处理
    第四步介绍下文档

    直接上代码
    MovieInput类,注意其中没有Id属性了,因为添加时自动增加Id属性

    using System;
    
    namespace GraphStudy.Movies.Movies
    {
        //添加类的模板
        public class MovieInput
        {
            public string Name { get; set; }
            public DateTime ReleaseDate { get; set; }//上映时间
            public string Company { get; set; }
            public int ActorId { get; set; }//演员ID
            public MovieRating MovieRating { get; set; }//电影等级枚举
        }
    }
    

    MovieInputType类,(GraphQL需要的类型),这里的类型与MovieInput对应,同样没有,注意枚举有点特殊,

    using GraphQL.Types;
    using GraphStudy.Movies.Movies;
    
    namespace GraphStudy.Movies.Schema
    {
        public class MovieInputType:InputObjectGraphType<MovieInput>
        {
            public MovieInputType()
            {
                Name = "MovieInput";
    
                Field(x => x.Name);
                Field(x => x.ActorId);
                Field(x => x.Company);
                Field(x => x.ReleaseDate);
                Field(x => x.MovieRating,type:typeof(MovieRatingEnum));
            }
        }
    }
    

    MovieMutation(添加处理)

    using GraphQL.Types;
    using GraphStudy.Movies.Movies;
    using GraphStudy.Movies.Services;
    using System.Linq;
    
    namespace GraphStudy.Movies.Schema
    {
        public class MoviesMutation:ObjectGraphType
        {
            public MoviesMutation(IMovieService movieService)
            {
                Name = "Mutation";
    
                //返回类型为MovieType,所以Field<MovieType>
                FieldAsync<MovieType> 
                (
                    "createMovie",
                    arguments: new QueryArguments(new QueryArgument<NonNullGraphType<MovieInputType>>
                    {
                        Name = "movie"//注意此处无需标点符号,不然会出错
                    }),
                    resolve: async context =>
                    {
                        var movieInput = context.GetArgument<MovieInput>("movie");//此处movie的字应该与arguments里面的Name字一样,模板为MovieInput
                        //用异步处理下面Id自增
                        var movies = await movieService.GetAsyncs();
                        var maxId = movies.Select(x => x.Id).Max();
    
                        var movie = new Movie
                        {
                            Id = ++maxId,
                            Name = movieInput.Name,
                            Company = movieInput.Company,
                            ActorId = movieInput.ActorId,
                            MovieRating = movieInput.MovieRating,
                            ReleaseDate = movieInput.ReleaseDate
                        };
                        //检车下MovieService类中CreateAsync方法是否写对,
                        var result = await movieService.CreateAsync(movie);
                        //返回结果,返回类型为MovieType,他里面有Id属性
                        return result;
                    }
                );
            }
        }
    }
    
    

    在MovieSchema类对MovieMution进行添加,所有的增删改查都在其中添加,同意在startup中注册服务

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

    最后在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<MovieInputType>();
                services.AddSingleton<MoviesMutation>();
    		///
                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());
    
            }
        }
    }
    
    

    最后运行
    在这里插入图片描述

    在这里插入图片描述

    在这里插入图片描述


    好了添加成功,那个actor里面的内容与ActorService里面的种子数据一一对应
    接下来查询下,点击中间那个按钮运行,选择Query
    在这里插入图片描述

    可以看到添加成功

    看看query查询语句,mutation添加语句

    # Try to write your query here
    query Query{
      movies{
        id
        name
        company
        movieRating
        releaseDate
        actorId
        customString
        actor{
          id
          name
        }
      }
    }
    
    mutation Create($input:MovieInput!){
      createMovie(movie: $input){
    
        name
        company
        movieRating
        releaseDate
        actorId
        actor{
          id
          name
        }
      }
    }
    

    其中添加里这句话解释下
    mutation Create($input:MovieInput!){
    createMovie(movie: $input){

    Create是添加语句的别名,

    createMovie为MovieMutation类里面的FieldAsync下面那个名字"createMovie",与之对应

    createMovie(movie: $input)中括号内需要添加一个参数变量,movie: input表示参数变量,input表示参数变量,inputinput传递参数变量

    Create(input:MovieInput!)中(input:MovieInput!)中(input:MovieInput!)(input:MovieInput!)表示定义变量,MovieInput表示变量类型,置于为什么是MovieInput这个呢
    可能和这句MovieMutation类var movieInput = context.GetArgument(“movie”);里面的有关,其中的感叹号!表示必填

    五、文档
    相信大家都看到了这个吧
    在这里插入图片描述

    点击schema出现这个这个就是我们的文档,最上面的搜索,QUERIES是关于查询,MUTATIONS关于增加,随着左边的语句增加,右边文档增加,点开查询看看
    在这里插入图片描述

    现在带有感叹号的为必填,我们点开的是枚举类型,可以自行查看相关信息,再打开添加的试试
    在这里插入图片描述
    actor对应ActorType类型,里面由id,name属性

    是不是感觉很方便

    https://github.com/1045683477/GraphQL-
    这是到现在的写的,代码在GitHub上

  • 相关阅读:
    PHP大文件上传断点续传源码
    PHP大文件上传断点续传解决方案
    Flash大文件断点续传解决方案
    Flash大文件断点续传功能
    ASP.NET上传断点续传
    B/S文件上传下载解决方案
    web文件夹上传下载方案
    Codeforces 460E Roland and Rose(暴力)
    iOS_25_彩票骨架搭建+导航栏适配
    配置Redmine的邮件通知功能
  • 原文地址:https://www.cnblogs.com/zuiren/p/10849933.html
Copyright © 2020-2023  润新知