public void Trivial2Test()
        {
            var api = new ApiDescription
            {
                ApiName  = "TestApi1",
                TypeName = "TestApi1",
                Version  = new Version("0.0.0.1"),
            };

            var provider = new MoqProvider {
                Description = api
            };
            var schema = SchemaGenerator.Generate(new List <ApiProvider> {
                provider
            });

            using (var printer = new SchemaPrinter(schema))
            {
                var description = printer.Print();
                this.output.WriteLine(description);
                Assert.False(string.IsNullOrWhiteSpace(description));
            }

            Assert.NotNull(schema.Query);
            Assert.Equal(3, schema.Query.Fields.Count());
            Assert.True(schema.Query.HasField("api"));
        }
Beispiel #2
0
    private static Command ConfigureServerCommand()
    {
        var serverCommand =
            new Command("server")
        {
            new Option <bool>("--print-graphql-schema", () => false, "Print the GraphQL schema and exit")
        };

        serverCommand.Handler = CommandHandler.Create <bool>(printGraphQlSchema =>
        {
            using var webApp = Server.Server.ConfigureWebApplication(builder =>
            {
                Bootstrap.ConfigureFeature(builder.Services);
                Bootstrap.ConfigureFileService(builder.Services);
                Bootstrap.ConfigureLogging(builder.Logging);
            });

            if (printGraphQlSchema)
            {
                var schema  = webApp.Services.GetRequiredService <ISchema>();
                var printer = new SchemaPrinter(schema);
                Console.WriteLine(printer.Print());
                return;
            }

            webApp.Run();
        });

        return(serverCommand);
    }
Beispiel #3
0
 public async Task SchemaPrint()
 {
     var graphQlService = new EfGraphQLService <MappingContext>(sqlInstance.Model, userContext => null !);
     var printer        = new SchemaPrinter(new MappingSchema(graphQlService));
     var print          = printer.Print();
     await Verifier.Verify(print);
 }
Beispiel #4
0
    public async Task SchemaPrint()
    {
        await using var database = await sqlInstance.Build();

        var dbContext = database.Context;
        var services  = new ServiceCollection();

        services.AddSingleton <Query>();
        services.AddSingleton <Mutation>();
        services.AddSingleton(database.Context);
        foreach (var type in GetGraphQlTypes())
        {
            services.AddSingleton(type);
        }

        EfGraphQLConventions.RegisterInContainer(services, _ => dbContext, dbContext.Model);
        EfGraphQLConventions.RegisterConnectionTypesInContainer(services);
        await using var provider = services.BuildServiceProvider();
        using var schema         = new Schema(provider);

        var printer = new SchemaPrinter(schema);
        var print   = printer.Print();

        await Verify(print);
    }
        public void prints_directive_without_arguments()
        {
            var    d      = new DirectiveGraphType("my", DirectiveLocation.Field, DirectiveLocation.Query);
            string result = new SchemaPrinter(null).PrintDirective(d);

            result.ShouldBe("directive @my on FIELD | QUERY");
        }
Beispiel #6
0
        static async Task Main(string[] args)
        {
            var       dataAdapter = new OrderDbDataAdapter(false, false, "test");
            IEdmModel edmModel    = dataAdapter.BuildEdmModel();

            await InitializeAsync(dataAdapter, edmModel);

            var schemaBuilder = new OeSchemaBuilder(dataAdapter, edmModel, new ModelBuilder.OeEdmModelMetadataProvider());

            var schema     = schemaBuilder.Build();
            var printer    = new SchemaPrinter(schema);
            var jsonSchema = printer.Print();

            Object dataContext = dataAdapter.CreateDataContext();

            var result = await new DocumentExecuter().ExecuteAsync(options =>
            {
                options.UserContext = dataContext;
                options.Schema      = schema;
                //options.Query = "query { orders { name customer (address: \"RU\") { name } } }";
                options.Query = "query { orders (id: 1) { items (orderId: 1) { product } } }";
            }).ConfigureAwait(false);

            dataAdapter.CloseDataContext(dataContext);

            var json = new DocumentWriter(indent: true).Write(result);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostEnvironment env, ISchema schema)
        {
            var printedSchema = new SchemaPrinter(schema).Print();

            Console.WriteLine(printedSchema);

            Console.WriteLine(schema.FindType("FooInput"));
            Console.WriteLine(schema.FindType("BarInput"));
            Console.WriteLine(schema.FindType("BazInput"));

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseHsts();
            }

            // add http for Schema at default url /graphql
            app.UseGraphQL <ISchema>("/graphql");
            app.UseWebSockets();
            app.UseGraphQLWebSockets <ISchema>("/graphql");

            // use graphql-playground at default url /ui/playground
            app.UseGraphiQLServer(new GraphiQLOptions {
                Path = "/graphiql", GraphQLEndPoint = "/graphql"
            });
            app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());

            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
Beispiel #8
0
        public async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "graphql")]
            HttpRequest req,
            CancellationToken cancellationToken)
        {
            var startTime = DateTime.Now;

            _contextManager.SetContext(req.Headers);
            _contextManager.SetInternalRequestId(Guid.NewGuid());

            string result;

            if (req.Method.Equals("GET") && req.Query.ContainsKey("schema"))
            {
                result = new SchemaPrinter(_spiSchema).Print();
            }
            else
            {
                var graphRequest = await ExtractGraphRequestAsync(req);

                result = await _spiSchema.ExecuteAsync(graphRequest);
            }

            var endTime = DateTime.Now;

            return(new AuditedOkObjectResult(
                       result,
                       startTime,
                       endTime,
                       _contextManager.SpiExecutionContext.InternalRequestId.Value,
                       _contextManager.SpiExecutionContext.ExternalRequestId));
        }
        public void builds_directives()
        {
            var definitions = @"
                directive @myDirective(
                  if: Boolean!
                ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
            ";

            var schema = Schema.For(definitions);

            schema.Initialize();

            var directive = schema.FindDirective("myDirective");

            directive.ShouldNotBeNull();

            directive.Arguments.Count().ShouldBe(1);
            var argument = directive.Arguments.Find("if");

            SchemaPrinter.ResolveName(argument.ResolvedType).ShouldBe("Boolean!");

            directive.Locations.ShouldBe(new[]
            {
                DirectiveLocation.Field,
                DirectiveLocation.FragmentSpread,
                DirectiveLocation.InlineFragment
            });
        }
Beispiel #10
0
 public string Print(GraphType type)
 {
     if (_schemaPrinter == null)
     {
         _schemaPrinter = new SchemaPrinter(Schema);
     }
     return(_schemaPrinter.ResolveName(type));
 }
Beispiel #11
0
 public string Describe(Func <ISchema, SchemaPrinter> ctor = null)
 {
     BuildSchema(); // Ensure that the schema has been constructed
     if (ctor != null)
     {
         _schemaPrinter = ctor(_schema);
     }
     return(_schemaPrinter.Print());
 }
Beispiel #12
0
 public void PrintsMinimalAst()
 {
     var ast = new ScalarDefinition
     {
         Name = new Name {Value = "foo"},
     };
     var schemaPrinter = new SchemaPrinter();
     schemaPrinter.Visit(ast).Should().Be("scalar foo");
 }
Beispiel #13
0
 public void DoesNotAlterAst()
 {
     var schemaKitchenSink = TestUtils.SchemaKitchenSink.Value;
     var ast = SchemaParser.ParseSchema(schemaKitchenSink);
     var astCopy = SchemaParser.ParseSchema(schemaKitchenSink);
     var schemaPrinter = new SchemaPrinter();
     schemaPrinter.VisitSchemaDocument(ast);
     ast.ShouldBeEquivalentToDeepDynamic(astCopy);
 }
        private string build_schema(string propType)
        {
            var nestedObjType = new ObjectGraphType
            {
                Name = "NestedObjType"
            };

            nestedObjType.AddField(new FieldType
            {
                ResolvedType = new IntGraphType(),
                Name         = "intField"
            });
            var rootType = new ObjectGraphType {
                Name = "root"
            };
            IGraphType resolvedType;

            switch (propType)
            {
            case "none":
            {
                resolvedType = nestedObjType;
                break;
            }

            case "list":
            {
                resolvedType = new ListGraphType(nestedObjType);
                break;
            }

            case "non-null":
            {
                resolvedType = new NonNullGraphType(nestedObjType);
                break;
            }

            default:
            {
                throw new NotSupportedException();
            }
            }

            rootType.AddField(new FieldType
            {
                Name         = "listOfObjField",
                ResolvedType = resolvedType
            });

            var s = new Schema
            {
                Query = rootType
            };
            var schema = new SchemaPrinter(s).Print();

            return(schema);
        }
Beispiel #15
0
        public void DoesNotAlterAst()
        {
            var schemaKitchenSink = TestUtils.SchemaKitchenSink.Value;
            var ast           = SchemaParser.ParseSchema(schemaKitchenSink);
            var astCopy       = SchemaParser.ParseSchema(schemaKitchenSink);
            var schemaPrinter = new SchemaPrinter();

            schemaPrinter.VisitSchemaDocument(ast);
            ast.ShouldBeEquivalentToDeepDynamic(astCopy);
        }
        public void TrivialTest()
        {
            var schema = SchemaGenerator.Generate(new List <ApiProvider>());

            using (var printer = new SchemaPrinter(schema))
            {
                var description = printer.Print();
                this.output.WriteLine(description);
                Assert.False(string.IsNullOrEmpty(description));
            }
        }
        public async Task Can_Construct_And_Describe_Schema_With_Dynamic_Queries()
        {
            var typeAdapter  = new GraphTypeAdapter();
            var typeResolver = new TypeResolver();

            var userRepositoryInterface = GetGraphType(typeAdapter, typeResolver, typeof(IUserRepository).GetTypeInfo());
            var userRepositoryType      = GetGraphType(typeAdapter, typeResolver, typeof(UserRepository).GetTypeInfo());
            var userType = GetGraphType(typeAdapter, typeResolver, typeof(User).GetTypeInfo());

            var schema = new Schema
            {
                Query = new ObjectGraphType {
                    Name = "Query"
                }
            };

            schema.RegisterTypes(userType, userRepositoryInterface, userRepositoryType);

            schema.Query.AddField(new FieldType
            {
                Name         = "users",
                ResolvedType = userRepositoryType,
                Resolver     = new CustomResolver(new UserRepository()),
            });

            var schemaDescription = new SchemaPrinter(schema).Print();

            schemaDescription.ShouldEqualWhenReformatted(@"
            interface IUserRepository {
                getUserById(id: String): User
            }
            type Query {
                users: UserRepository
            }
            type User {
                id: String
                name: String
            }
            type UserRepository implements IUserRepository {
                getUserById(id: String): User
            }
            ");

            var executer = new GraphQL.DocumentExecuter();
            var result   = await executer.ExecuteAsync(new ExecutionOptions
            {
                Schema = schema,
                Query  = "{ users { getUserById(id: \"1\") { id name } } }",
            });

            result.ShouldHaveNoErrors();
            result.Data.ShouldHaveFieldWithValue("users", "getUserById", "id", "1");
            result.Data.ShouldHaveFieldWithValue("users", "getUserById", "name", "User #1");
        }
Beispiel #18
0
 public void Should_Print_Default_Values_Of_Arguments()
 {
     CultureTestHelper.UseCultures(() =>
     {
         var printer = new SchemaPrinter(new Bug2194Schema(), new SchemaPrinterOptions {
             IncludeDeprecationReasons = false, IncludeDescriptions = false
         });
         var printed = printer.Print();
         printed.ShouldBe("Bug2194".ReadSDL());
     });
 }
Beispiel #19
0
        public async Task Invoke(HttpContext context, ISchema schema)
        {
            using (var printer = new SchemaPrinter(schema))
            {
                context.Response.ContentType = "application/text";
                context.Response.StatusCode  = (int)HttpStatusCode.OK;

                await context.Response.WriteAsync(printer.Print());

                return;
            }
        }
Beispiel #20
0
        public void PrintsMinimalAst()
        {
            var ast = new ScalarDefinition
            {
                Name = new Name {
                    Value = "foo"
                },
            };
            var schemaPrinter = new SchemaPrinter();

            schemaPrinter.Visit(ast).Should().Be("scalar foo");
        }
        public async Task EnumApiTest()
        {
            var enumType = new ApiEnumType("EnumType", new[] { "item1", "item2" });

            var api = new ApiDescription(
                "TestApi1",
                "0.0.0.1",
                new ApiType[] { enumType },
                new[] { ApiField.Object("enumField", enumType.TypeName) });

            var provider = new MoqProvider {
                Description = api, Data = "{\"enumField\": \"item2\"}"
            };

            var schema = SchemaGenerator.Generate(new List <ApiProvider> {
                provider
            });

            using (var printer = new SchemaPrinter(schema))
            {
                var description = printer.Print();
                this.output.WriteLine("-------- Schema -----------");
                this.output.WriteLine(description);
                Assert.False(string.IsNullOrWhiteSpace(description));
            }

            Assert.NotNull(schema.Query);
            Assert.Equal(3, schema.Query.Fields.Count());
            Assert.True(schema.Query.HasField("api"));

            var result = await new DocumentExecuter().ExecuteAsync(
                r =>
            {
                r.Schema = schema;
                r.Query  = "query { api { enumField } } ";
            }).ConfigureAwait(true);

            this.output.WriteLine("-------- Response -----------");
            var response = new DocumentWriter(true).Write(result);

            this.output.WriteLine(response);

            var expectedResponse = @"{
                                      ""data"": {
                                        ""api"": {
                                            ""enumField"": ""item2"" 
                                        }
                                     }                                      
                                    }";

            Assert.Equal(CleanResponse(expectedResponse), CleanResponse(response));
        }
Beispiel #22
0
        /// <inheritdoc/>
        public async Task <object> Resolve(IResolveFieldContext context, FieldMiddlewareDelegate next)
        {
            var metadata = new Dictionary <string, object>
            {
                { "typeName", context.ParentType.Name },
                { "fieldName", context.FieldName },
                { "returnTypeName", SchemaPrinter.ResolveName(context.ReturnType) },
                { "path", context.Path },
            };

            using (context.Metrics.Subject("field", context.FieldName, metadata))
                return(await next(context).ConfigureAwait(false));
        }
Beispiel #23
0
 public GraphQLEngine BuildSchema(params System.Type[] types)
 {
     if (_schema == null)
     {
         if (types.Length > 0)
         {
             _schemaTypes.AddRange(types);
         }
         _schema        = _constructor.Build(_schemaTypes.ToArray());
         _schemaPrinter = new SchemaPrinter(_schema, new[] { TypeNames.Url, TypeNames.Uri, TypeNames.TimeSpan, TypeNames.Guid });
     }
     return(this);
 }
    public async Task Print()
    {
        var services = new ServiceCollection();

        services.AddSingleton <ILoggerFactory>(_ => NullLoggerFactory.Instance);
        new Startup().ConfigureServices(services);

        await using var provider = services.BuildServiceProvider();
        var schema   = ServiceProviderServiceExtensions.GetRequiredService <ISchema>(provider);
        var printer  = new SchemaPrinter(schema);
        var print    = printer.Print();
        var settings = new VerifySettings();
        await Verifier.Verify(print, settings);
    }
    public async Task Print()
    {
        var services = new ServiceCollection();

        services.AddSingleton <ILoggerFactory>(x => NullLoggerFactory.Instance);
        new Startup().ConfigureServices(services);

        await using var provider = services.BuildServiceProvider();
        var schema   = new Schema(new FuncDependencyResolver(provider.GetRequiredService));
        var printer  = new SchemaPrinter(schema);
        var print    = printer.Print();
        var settings = new VerifySettings();
        await Verifier.Verify(print, settings);
    }
Beispiel #26
0
        public static StatsReport From(ISchema schema, Operation operation, PerfRecord[] records, DateTime start)
        {
            var operationStat = records.Single(x => string.Equals(x.Category, "operation"));

            var report = new StatsReport
            {
                Start    = start,
                End      = start.AddMilliseconds(operationStat.Duration),
                Duration = operationStat.Duration,
                Types    = TypesFromSchema(schema)
            };

            var perField = new LightweightCache <string, TypeStat>(type => new TypeStat {
                Name = type
            });

            var typeInfo = new TypeInfo(schema);

            var fieldVisitor = new EnterLeaveListener(_ =>
            {
                _.Match <AstField>(f =>
                {
                    var parent     = typeInfo.GetParentType().GetNamedType();
                    var parentType = parent.Name;
                    var fieldName  = f.Name;

                    perField[parentType][fieldName].ReturnType = SchemaPrinter.ResolveName(typeInfo.GetLastType());
                });
            });

            new BasicVisitor(typeInfo, fieldVisitor).Visit(operation);

            var queryResolvers = records.Where(x => string.Equals(x.Category, "field")).ToList();

            queryResolvers.Apply(resolver =>
            {
                var typeName  = resolver.MetaField <string>("typeName");
                var fieldName = resolver.MetaField <string>("fieldName");

                perField[typeName][fieldName].AddLatency(resolver.Duration);
            });

            var operationName = operation.Name ?? "Anonymous";

            report.PerSignature[operationName] = new StatsPerSignature {
                PerType = perField.GetAll()
            };

            return(report);
        }
Beispiel #27
0
        public async Task Invoke(HttpContext httpContext, ApplicationDbContext applicationContext)
        {
            var sent = false;

            if (httpContext.Request.Path.StartsWithSegments("/graph"))
            {
                using (var sr = new StreamReader(httpContext.Request.Body))
                {
                    var query = await sr.ReadToEndAsync();

                    if (!String.IsNullOrWhiteSpace(query))
                    {
                        BooksQuery bq     = new BooksQuery(applicationContext);
                        var        schema = new Schema {
                            Query = bq
                        };


                        if (httpContext.Request.Method == "OPTIONS")
                        {
                            var printedSchema = new SchemaPrinter(schema).Print();

                            await WriteResult(httpContext, printedSchema);

                            sent = true;
                        }
                        else
                        {
                            var result = await new DocumentExecuter()
                                         .ExecuteAsync(options =>
                            {
                                options.Schema = schema;
                                options.Query  = query;
                            }).ConfigureAwait(false);

                            CheckForErrors(result);

                            await WriteResult(httpContext, result);

                            sent = true;
                        }
                    }
                }
            }
            if (!sent)
            {
                await _next(httpContext);
            }
        }
Beispiel #28
0
        public void prints_directive()
        {
            var printer = new SchemaPrinter(null);
            var arg     = DirectiveGraphType.Skip.Arguments.First();

            arg.ResolvedType = arg.Type.BuildNamedType();

            var          result   = printer.PrintDirective(DirectiveGraphType.Skip);
            const string expected = @"# Directs the executor to skip this field or fragment when the 'if' argument is true.
directive @skip(
  if: Boolean!
) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT";

            AssertEqual(result, "directive", expected, excludeScalars: true);
        }
Beispiel #29
0
    public async Task SchemaPrint()
    {
        var graphQlService         = new EfGraphQLService <MappingContext>(sqlInstance.Model, _ => null !);
        ServiceCollection services = new();

        EfGraphQLConventions.RegisterInContainer <MappingContext>(services);
        services.AddSingleton(new MappingChildGraph(graphQlService));
        services.AddSingleton(new MappingParentGraph(graphQlService));
        await using var provider = services.BuildServiceProvider();
        var mappingSchema = new MappingSchema(graphQlService, provider);

        var printer = new SchemaPrinter(mappingSchema);
        var print   = printer.Print();
        await Verifier.Verify(print);
    }
        public void prints_repeatable_directive_with_arguments()
        {
            var d = new DirectiveGraphType("my", DirectiveLocation.Field, DirectiveLocation.Query)
            {
                Repeatable = true,
                Arguments  = new QueryArguments(new QueryArgument(new IntGraphType())
                {
                    Name = "max"
                })
            };
            string result = new SchemaPrinter(null).PrintDirective(d);

            result.ShouldBe(@"directive @my(
  max: Int
) repeatable on FIELD | QUERY");
        }
Beispiel #31
0
    public async Task SchemaPrint()
    {
        var services = new ServiceCollection();

        EfGraphQLConventions.RegisterInContainer <MappingContext>(services, model: sqlInstance.Model);
        services.AddSingleton <MappingChildGraph>();
        services.AddSingleton <MappingParentGraph>();
        services.AddSingleton <MappingSchema>();
        await using var provider = services.BuildServiceProvider();
        var mappingSchema = provider.GetRequiredService <MappingSchema>();

        var printer = new SchemaPrinter(mappingSchema);
        var print   = printer.Print();

        await Verify(print);
    }
Beispiel #32
0
        public void ApiGenerationTest()
        {
            var system = ActorSystem.Create("test");
            var api    = new ApiProvider(system, new TestRepository());

            foreach (var error in api.GenerationErrors)
            {
                this.output.WriteLine($"Error: {error}");
            }

            Assert.Equal(0, api.GenerationErrors.Count);

            var webApiProvider = new DirectProvider(api, this.output.WriteLine)
            {
                UseJsonRepack = true
            };
            var schema = SchemaGenerator.Generate(new List <Web.GraphQL.Publisher.ApiProvider> {
                webApiProvider
            });

            var hasSchemaErrors = false;

            foreach (var error in SchemaGenerator.CheckSchema(schema))
            {
                hasSchemaErrors = true;
                this.output.WriteLine($"Schema error: {error}");
            }

            using (var printer = new SchemaPrinter(schema))
            {
                var description = printer.Print();
                this.output.WriteLine("-------- Schema -----------");
                this.output.WriteLine(description);
                Assert.False(string.IsNullOrWhiteSpace(description));
            }

            Assert.False(hasSchemaErrors);

            hasSchemaErrors = false;
            foreach (var error in SchemaGenerator.CheckSchemaIntrospection(schema))
            {
                hasSchemaErrors = true;
                this.output.WriteLine($"Schema introspection error: {error}");
            }

            Assert.False(hasSchemaErrors);
        }
Beispiel #33
0
        public void PrintsKitchenSink()
        {
            var schemaKitchenSink = TestUtils.SchemaKitchenSink.Value;
            var ast = SchemaParser.ParseSchema(schemaKitchenSink);
            var schemaPrinter = new SchemaPrinter();
            var printed = schemaPrinter.VisitSchemaDocument(ast);
            printed.Should().Be(
            @"type Foo implements Bar {
              one: Type
              two(argument: InputType!): Type
              three(argument: InputType, other: String): Int
              four(argument: String = ""string""): String
              five(argument: [String] = [""string"", ""string""]): String
              six(argument: InputType = {key: ""value""}): Type
            }

            interface Bar {
              one: Type
              four(argument: String = ""string""): String
            }

            union Feed = Story | Article | Advert

            scalar CustomScalar

            enum Site {
              DESKTOP
              MOBILE
            }

            input InputType {
              key: String!
              answer: Int = 42
            }
            ".ToLF());
        }