Example #1
0
        public void TestMutation()
        {
            string query    = @"{ ""query"": ""mutation ($human:HumanInput!){ createHuman(human: $human) { id fullname } }"", ""variables"": { ""human"": { ""fullname"": ""Bobba Fett"",""id"": ""3"" } } }";
            string expected = @"{ ""data"": { ""createHuman"": { ""id"": ""3"",""fullname"": ""Bobba Fett"" } } }";

            StarWarsSchema swss   = this._provider.GetRequiredService <StarWarsSchema>();
            var            result = swss.Execute(_ =>
            {
                //get the input into GraphQL format
                GraphQL.Inputs queryInputs = query.ToInputs();
                foreach (KeyValuePair <string, object> qIn in queryInputs)
                {
                    if (qIn.Key == "variables")
                    {
                        string json = JsonConvert.SerializeObject(qIn.Value, Formatting.Indented);
                        _.Inputs    = json.ToInputs();
                    }
                    if (qIn.Key == "query")
                    {
                        _.Query = qIn.Value.ToString();
                    }
                }
            });

            _output.WriteLine("Query:" + query);
            _output.WriteLine("Result:" + result);
            JToken actualJson   = JToken.Parse(result);
            JToken expectedJson = JToken.Parse(expected);

            Assert.Equal(expectedJson.ToString(), actualJson.ToString());
        }
Example #2
0
        public void does_not_request_instance_more_than_once()
        {
            // configure DI provider
            var services = new SimpleContainer();

            services.Singleton <StarWarsData>();

            // mock it so we can verify behavior
            var mock = new Mock <IServiceProvider>(MockBehavior.Loose);

            mock.Setup(x => x.GetService(It.IsAny <Type>())).Returns <Type>(type => services.Get(type));

            // run test
            var schema = new StarWarsSchema(mock.Object);

            schema.Initialize();

            // verify that GetService was only called once for each schema type
            mock.Verify(x => x.GetService(typeof(StarWarsQuery)), Times.Once);
            mock.Verify(x => x.GetService(typeof(StarWarsMutation)), Times.Once);
            mock.Verify(x => x.GetService(typeof(CharacterInterface)), Times.Once);
            mock.Verify(x => x.GetService(typeof(DroidType)), Times.Once);
            mock.Verify(x => x.GetService(typeof(HumanInputType)), Times.Once);
            mock.Verify(x => x.GetService(typeof(HumanType)), Times.Once);
            mock.Verify(x => x.GetService(typeof(EpisodeEnum)), Times.Once);
            mock.Verify(x => x.GetService(typeof(IEnumerable <IConfigureSchema>)), Times.Once);
            mock.VerifyNoOtherCalls();
        }
Example #3
0
        public static void Main(string[] args)
        {
            using (var db = new StarWarsContext())
            {
                // insert some testing data into database
                if (db.Humans.Count() == 0)
                {
                    InsertData(db);
                }

                var container = new UnityContainer();

                container.RegisterInstance(db);

                container.RegisterType <StarWarsQuery>();
                container.RegisterType <DroidType>();
                container.RegisterType <HumanType>();

                var schema = new StarWarsSchema((t) => container.Resolve(t) as GraphType);

                var query = @"
                    query AllHumansQuery {
                        humans {
                            name
                            friends {
                                id
                                name
                                ...on Droid {
                                    primaryFunction
                                }
                            }
                        }
                    }";

                Console.WriteLine("Run AllHumansQuery");

                var result = Execute(schema, null, query);

                Console.WriteLine(result.Result);
                Console.WriteLine();

                query = @"
                    query AllCharactersQuery {
                        characters {
                            name
                            friends {
                                name
                            }
                        }
                    }";

                Console.WriteLine("Run AllCharactersQuery");

                result = Execute(schema, null, query);

                Console.WriteLine(result.Result);
            }
        }
Example #4
0
 private static async Task RunTest(StarWarsSchema schema, IDocumentExecuter executer)
 {
     await executer.ExecuteAsync(_ =>
     {
         _.Query       = TestQuery;
         _.Schema      = schema;
         _.UserContext = new StarWarsContext();
     });
 }
Example #5
0
 public StarWarsGraphQLController(
     IDocumentExecuter executer,
     IDocumentWriter writer,
     StarWarsSchema schema)
 {
     _executer = executer;
     _writer   = writer;
     _schema   = schema;
 }
Example #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // add execution components
            services.AddSingleton <IDocumentExecuter, DocumentExecuter>();
            services.AddSingleton <IDocumentWriter, DocumentWriter>();
            services.AddSingleton <IErrorInfoProvider>(services =>
            {
                var settings = services.GetRequiredService <IOptions <GraphQLSettings> >();
                return(new ErrorInfoProvider(new ErrorInfoProviderOptions {
                    ExposeExceptionStackTrace = settings.Value.ExposeExceptions
                }));
            });

            // add something like repository
            services.AddSingleton <StarWarsData>();

            // add graph types
            services.AddSingleton <StarWarsQuery>();
            services.AddSingleton <StarWarsMutation>();
            services.AddSingleton <HumanType>();
            services.AddSingleton <HumanInputType>();
            services.AddSingleton <DroidType>();
            services.AddSingleton <CharacterInterface>();
            services.AddSingleton <EpisodeEnum>();

            // add schema
            services.AddSingleton <ISchema, StarWarsSchema>(services =>
            {
                var settings = services.GetRequiredService <IOptions <GraphQLSettings> >();
                var schema   = new StarWarsSchema(services);
                if (settings.Value.EnableMetrics)
                {
                    var middlewares = services.GetRequiredService <IEnumerable <IFieldMiddleware> >();
                    foreach (var middleware in middlewares)
                    {
                        schema.FieldMiddleware.Use(middleware);
                    }
                }
                return(schema);
            });

            // add infrastructure stuff
            services.AddHttpContextAccessor();
            services.AddLogging(builder => builder.AddConsole());

            // add options configuration
            services.Configure <GraphQLSettings>(Configuration);
            services.Configure <GraphQLSettings>(settings => settings.BuildUserContext = ctx => new GraphQLUserContext {
                User = ctx.User
            });

            // add Field Middlewares
            services.AddSingleton <IFieldMiddleware, CountFieldMiddleware>();
            services.AddSingleton <IFieldMiddleware, InstrumentFieldsMiddleware>();
        }
        public string Execute(string query)
        {
            var schema = new StarWarsSchema(type => (GraphType)Services.Get(type));

            IDocumentExecuter documentExecutor = new DocumentExecuter(new AntlrDocumentBuilder(), new DocumentValidator());
            IDocumentWriter   writer           = new DocumentWriter(indent: true);

            var runResult     = documentExecutor.ExecuteAsync(schema, null, query, null);
            var writtenResult = writer.Write(runResult);

            return(writtenResult);
        }
Example #8
0
        public static void RunTests()
        {
            var schema   = new StarWarsSchema();
            var executer = new DocumentExecuter();
            var clock    = Stopwatch.StartNew();
            var i        = 0;

            for (; i < 100000; i++)
            {
                RunTest(schema, executer).Wait();
            }
            clock.Stop();
            Console.WriteLine($"Took {clock.ElapsedMilliseconds}ms to run {i} tests");
        }
Example #9
0
        public GraphQLController(
            IDocumentExecuter executer,
            IDocumentWriter writer,
            StarWarsSchema schema)
        {
            _executer = executer;
            _writer   = writer;
            _schema   = schema;

            _namedQueries = new Dictionary <string, string>
            {
                ["a-query"] = @"query foo { hero { name } }"
            };
        }
Example #10
0
        static void Main(string[] args)
        {
            var query = ResolveQuery(args);

            if (string.IsNullOrWhiteSpace(query))
            {
                Console.WriteLine("No query argument provided, or failed to parse query. Provide either a query or the named of a stored query. Stored queries: \n");
                foreach (var name in NamedQueries.Keys)
                {
                    Console.WriteLine(name);
                }
                return;
            }

            Console.WriteLine(StarWarsSchema.Execute(query));
        }
Example #11
0
        public void ValidSchemaVariables(string query, string expected)
        {
            //
            StarWarsSchema swss   = this._provider.GetRequiredService <StarWarsSchema>();
            var            result = swss.Execute(x =>
            {
                x.Query = query;
            });

            _output.WriteLine("Query:" + query);
            _output.WriteLine("Result:" + result);
            JToken actualJson   = JToken.Parse(result);
            JToken expectedJson = JToken.Parse(expected);

            Assert.Equal(expectedJson.ToString(), actualJson.ToString());
        }
Example #12
0
        public void Schemas_Align()
        {
            var schemaGenerator = new SchemaGenerator(new MockServiceProvider());
            var schema          = schemaGenerator.CreateSchema(typeof(StarWarsAttributeSchema));

            var container = new SimpleContainer();

            container.Singleton(new StarWarsData());
            container.Register <StarWarsQuery>();
            container.Register <HumanType>();
            container.Register <DroidType>();
            container.Register <CharacterInterface>();
            var manualSchema = new StarWarsSchema(type => (GraphType)container.Get(type));

            Assert.Equal(manualSchema.Query.Fields.Count(), schema.Query.Fields.Count());
            Assert.Equal(manualSchema.AllTypes.Count(), schema.AllTypes.Count() + 1); //todo work on enum
        }
Example #13
0
        private ISimpleContainer BuildContainer()
        {
            var container = new SimpleContainer();

            container.Singleton <IDocumentExecuter>(new DocumentExecuter());
            container.Singleton <IDocumentWriter>(new DocumentWriter(true));

            container.Singleton(new StarWarsData());
            container.Register <StarWarsQuery>();
            container.Register <StarWarsMutation>();
            container.Register <HumanType>();
            container.Register <HumanInputType>();
            container.Register <DroidType>();
            container.Register <CharacterInterface>();
            using (var starWarsSchema = new StarWarsSchema(new FuncDependencyResolver(type => container.Get(type))))
            {
                container.Singleton(starWarsSchema);
            }

            return(container);
        }
Example #14
0
 public GraphQLController(StarWarsSchema starWarsSchema)
 {
     _starWarsSchema = starWarsSchema;
 }
 public GraphQLController(StarWarsSchema schema, IDocumentExecuter executer)
 {
     _schema   = schema;
     _executer = executer;
 }
Example #16
0
 public GraphQLController(RequestExecutor executor, Swapi api, StarWarsSchema schema)
 {
     Schema    = schema;
     _api      = api;
     _executor = executor;
 }
 public GraphQLController(StarWarsSchema schema, IDocumentExecuter executer, IDocumentWriter writer)
 {
     _executer = executer;
     _schema   = schema;
     _writer   = writer;
 }