public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                _logger.LogError("Argument null exception for query - CHECK {0}", nameof(query));
                throw new ArgumentNullException(nameof(query));
            }
            var inputs = query.Variables.ToInputs();

            try
            {
                var files            = this.Request.HasFormContentType ? this.Request.Form.Files : null;
                var executionOptions = new ExecutionOptions
                {
                    Schema          = _schema,
                    Query           = query.Query,
                    Inputs          = inputs,
                    Root            = files,
                    ValidationRules = _validationRule
                };

                var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);

                if (result.Errors?.Count > 0)
                {
                    return(StatusCode(400, result));
                }
                return(Ok(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Something really went wrong - CHECK: {0}", ex.Message);
                return(StatusCode(500, "Internal server error"));
            }
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var executionOptions = new ExecutionOptions {
                Schema = _schema, Query = query.Query
            };

            try
            {
                var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);

                if (result.Errors?.Count > 0)
                {
                    return(BadRequest(result));
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var executionOptions = new ExecutionOptions {
                Schema = _schema, Query = query.Query
            };

            try
            {
                var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);

                if (result.Errors?.Count > 0)
                {
                    _logger.LogError("GraphQL errors: {0}", result.Errors);
                    return(BadRequest(result));
                }

                _logger.LogDebug("GraphQL execution result: {result}", JsonConvert.SerializeObject(result.Data));
                return(Ok(result));
            }
            catch (Exception ex)
            {
                _logger.LogError("Document exexuter exception", ex);
                return(BadRequest(ex));
            }
        }
        public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var inputs           = query.Variables.ToInputs();
            var executionOptions = new ExecutionOptions
            {
                Schema = _schema,
                Query  = query.Query,
                Inputs = inputs
            };

            var result = await _documentExecuter
                         .ExecuteAsync(executionOptions);

            if (result.Errors?.Count > 0)
            {
                return(BadRequest(result));
            }

            return(Ok(result));
        }
        public async System.Threading.Tasks.Task <object> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            var executionOptions = new ExecutionOptions()
            {
                Schema = _schema,
                Query  = query.Query,
                Inputs = query.Variables.ToInputs()
            };

            try
            {
                var result = await _documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false);

                return(Ok(result));
            }
            catch (Exception ex)
            {
            }

            return(null);
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }

            try
            {
                var result = await _executer.ExecuteAsync(_ =>
                {
                    _.Schema        = _schema;
                    _.Query         = query.Query;
                    _.OperationName = query.OperationName;

                    _.ComplexityConfiguration = new ComplexityConfiguration {
                        MaxDepth = 15
                    };
                    _.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
                }).ConfigureAwait(false);

                if (result.Errors?.Count > 0)
                {
                    return(BadRequest(result));
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex));
            }
        }
Exemplo n.º 7
0
        public async Task GetUserByIdTest()
        {
            User user = new User()
            {
                Email      = "*****@*****.**",
                GivvenName = "Peter",
                FamilyName = "Johnson"
            };

            //Setup db data
            await _context.DbContext.Users.AddAsync(user);

            await _context.DbContext.SaveChangesAsync();

            //Api call
            var query = new GraphQLQuery()
            {
                Query = $"{{user(id: \"{user.Id}\") {{id,givvenName,familyName,email,created}} }}"
            };
            string postData = JsonConvert.SerializeObject(query);
            var    response = await _context.Client.PostAsync("/graphql", new StringContent(postData, Encoding.UTF8, "application/json"));

            //Check status code
            response.StatusCode.Should().Be(HttpStatusCode.OK);

            //Parse response
            string responseStr = await response.Content.ReadAsStringAsync();

            GraphUserResponse graphQlResponse = JsonConvert.DeserializeObject <GraphUserResponse>(responseStr);

            //Compare response data and original data
            user.Should().Equals(graphQlResponse.Data.user);
        }
Exemplo n.º 8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        public void GraphqlPost(GraphQLQuery body)
        {
            var path = "/graphql";

            path = path.Replace("{format}", "json");

            var    queryParams  = new Dictionary <String, String>();
            var    headerParams = new Dictionary <String, String>();
            var    formParams   = new Dictionary <String, String>();
            var    fileParams   = new Dictionary <String, FileParameter>();
            String postBody     = null;

            postBody = ApiClient.Serialize(body);                                     // http body (model) parameter

            // authentication setting, if any
            String[] authSettings = new String[] {  };

            // make the HTTP request
            IRestResponse response = (IRestResponse)ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if (((int)response.StatusCode) >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling GraphqlPost: " + response.Content, response.Content);
            }
            else if (((int)response.StatusCode) == 0)
            {
                throw new ApiException((int)response.StatusCode, "Error calling GraphqlPost: " + response.ErrorMessage, response.ErrorMessage);
            }

            return;
        }
Exemplo n.º 9
0
        public async Task <IActionResult> GraphQLApi([FromBody] GraphQLQuery query)
        {
            // Create inputs. Convert Variables thành kiểu Inputs
            var inputs = query.Variables.ToInputs();

            // Create schema
            var schema = new Schema
            {
                Query = new RetailerQuery(_retailerRepo)
            };

            // Truyền tham số vào hàm ExecuteAsync để thực hiện GraphQL request
            var result = await _documentExecuter.ExecuteAsync(x =>
            {
                x.Schema        = schema;
                x.Query         = query.Query;
                x.OperationName = query.OperationName;
                x.Inputs        = inputs;
            });

            if (result.Errors?.Count > 0)
            {
                return(BadRequest());
            }

            return(Ok(result));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }
            var inputs           = query.Variables.ToInputs();
            var executionOptions = new ExecutionOptions
            {
                Schema = schema,
                Query  = query.Query,
                Inputs = inputs
            };

            var result = await documentExecuter
                         .ExecuteAsync(executionOptions)
                         .ConfigureAwait(false);

            if (result.Errors != null &&
                result.Errors.Count > 0)
            {
                return(NotFound());
            }

            return(Ok(result));
        }
Exemplo n.º 11
0
 public GraphQLProcessor(GraphQLQuery graphQlQuery, ISchema schema, IDocumentExecuter executer, IDocumentWriter writer)
 {
     _graphQLQuery = graphQlQuery;
     _schema       = schema;
     _executer     = executer;
     _writer       = writer;
 }
Exemplo n.º 12
0
        public async Task IntrospectionTest()
        {
            using (var resolver = new TestResolver(Setup))
            {
                var schema = resolver.Resolve <ISchema>();
                var query  = new GraphQLQuery
                {
                    Query =
                        "\n  query IntrospectionQuery {\n    __schema {\n      queryType { name }\n      mutationType { name }\n      subscriptionType { name }\n      types {\n        ...FullType\n      }\n      directives {\n        name\n        description\n        locations\n        args {\n          ...InputValue\n        }\n      }\n    }\n  }\n\n  fragment FullType on __Type {\n    kind\n    name\n    description\n    fields(includeDeprecated: true) {\n      name\n      description\n      args {\n        ...InputValue\n      }\n      type {\n        ...TypeRef\n      }\n      isDeprecated\n      deprecationReason\n    }\n    inputFields {\n      ...InputValue\n    }\n    interfaces {\n      ...TypeRef\n    }\n    enumValues(includeDeprecated: true) {\n      name\n      description\n      isDeprecated\n      deprecationReason\n    }\n    possibleTypes {\n      ...TypeRef\n    }\n  }\n\n  fragment InputValue on __InputValue {\n    name\n    description\n    type { ...TypeRef }\n    defaultValue\n  }\n\n  fragment TypeRef on __Type {\n    kind\n    name\n    ofType {\n      kind\n      name\n      ofType {\n        kind\n        name\n        ofType {\n          kind\n          name\n          ofType {\n            kind\n            name\n            ofType {\n              kind\n              name\n              ofType {\n                kind\n                name\n                ofType {\n                  kind\n                  name\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n"
                };
                var documentExecuter = resolver.Resolve <IDocumentExecuter>();
                var executionOptions = new ExecutionOptions
                {
                    Schema = schema,
                    Query  = query.Query
                };
                var result = await
                             documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(true);

                Assert.IsNotNull(result);
                Assert.IsTrue(result.Errors == null,
                              string.Concat(result.Errors != null && result.Errors.Any()
                        ? result.Errors
                        : new ExecutionErrors()));
            }
        }
Exemplo n.º 13
0
 private void ValidateQuery(GraphQLQuery query)
 {
     if (query == null)
     {
         throw new ArgumentNullException(nameof(query));
     }
 }
Exemplo n.º 14
0
        //[HttpPost]
        public async Task <IActionResult> Post([FromBody] GraphQLQuery query)
        {
            var _result = await new DocumentExecuter().ExecuteAsync(options =>
            {
                options.Schema = new Schema
                {
                    Query    = new Query(),
                    Mutation = new Mutation()
                };
                options.Query         = query.Query;
                options.OperationName = query.OperationName;
                options.Inputs        = query.Variables.ToInputs();
                options.UserContext   = new GraphQLUserContext()
                {
                    //{"AccessToken",ControllerHelper.GetAccessToken(Request) },
                    //{"Username",ControllerHelper.GetUsername(Request) },
                    //{"UserPassword",ControllerHelper.GetUserPassword(Request) },
                    //{"CurrentPassword",ControllerHelper.GetCurrentPassword(Request) },
                    //{"NewPassword",ControllerHelper.GetNewPassword(Request) },
                    //{"ActivateAccountId",ControllerHelper.GetActivateAccountId(Request) },
                    { "IWebHostEnvironment", _webHostEnvironment }
                };
                //options.ComplexityConfiguration = new ComplexityConfiguration { MaxDepth = 15 };
            });

            if (_result.Errors?.Count > 0)
            {
                return(BadRequest(new ApiErrorResp(_result.Errors)));
            }

            HttpContext.Response.ContentType = "application/json";
            await new DocumentWriter().WriteAsync(HttpContext.Response.Body, _result);

            return(Ok());
        }
Exemplo n.º 15
0
        public async Task should_handle_start_subscriptions()
        {
            /* Given */
            var query = new GraphQLQuery
            {
                OperationName = "test",
                Query         = "subscription",
                Variables     = JObject.FromObject(new { test = "variable" })
            };

            var messageContext = CreateMessage(
                MessageTypes.GQL_START, query);

            _subscriptionExecuter.SubscribeAsync(Arg.Any <ExecutionOptions>())
            .Returns(CreateStreamResult);

            _determinator.IsSubscription(Arg.Any <ExecutionOptions>()).Returns(true);

            /* When */
            await _sut.HandleMessageAsync(messageContext).ConfigureAwait(false);

            /* Then */
            await _subscriptionExecuter.Received()
            .SubscribeAsync(Arg.Is <ExecutionOptions>(
                                context => context.Schema == _schema &&
                                context.Query == query.Query &&
                                context.Inputs.ContainsKey("test")))
            .ConfigureAwait(false);

            var connectionSubscriptions = _sut.Subscriptions[messageContext.ConnectionId];

            Assert.True(connectionSubscriptions.ContainsKey(messageContext.Op.Id));
        }
Exemplo n.º 16
0
 public GraphQLController(GraphQLQuery graphQLQuery, ISchema schema, IDocumentExecuter documentExecuter, IUtilityService utilityService, IServiceProvider serviceProvider)
 {
     _graphQLQuery     = graphQLQuery;
     _schema           = schema;
     _documentExecuter = documentExecuter;
     _utilityService   = utilityService;
     _serviceProvider  = serviceProvider;
 }
        public void Serialize_OfType_OverridesAttributeTypeName()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .OfType("overriden_type")
                        .ToString();

            Assert.Contains("overriden_type {", query);
        }
        public void Serialize_EnumArgument_AddsNameNotValue()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .WithArgument("category", Category.News)
                        .ToString();

            Assert.Contains("blog_post(category: News", query);
        }
        public void Serialize_ArgumentWithoutProperty_AddsProperArgumentSyntax()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .WithArgument("id", 1)
                        .ToString();

            Assert.Contains("blog_post(id: 1)", query);
        }
        public void Serialize_OperationName_AddsSyntax()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .AsOperation("GetBlogPosts")
                        .ToString();

            Assert.Contains("query GetBlogPosts", query);
        }
        public void Serialize_ArgumentWithProperty_AddsProperArgumentSyntax()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .WithArgument(x => x.Title, "length", 5)
                        .ToString();

            Assert.Contains("title(length: 5)", query);
        }
        public void Serialize_WithIgnore_DoesNotContainField()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .ShouldIgnore(x => x.Title)
                        .ToString();

            Assert.DoesNotContain("full_name", query);
        }
        public void Serialize_WithOfType_UsesProvidedTypeInQuery()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .OfType("some_remote_type")
                        .ToString();

            Assert.Contains("some_remote_type", query);
        }
        public void Serialize_Map_UsesPropertyWithoutAttribute()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .WithMapping(x => x.UnMappedField, "unmapped_field")
                        .ToString();

            Assert.Contains("unmapped_field", query);
        }
 /// Query the GraphQL API over POST
 public async Task <IActionResult> Post([FromBody] GraphQLQuery query, [FromHeader] string token)
 {
     if (query == null)
     {
         throw new ArgumentNullException(nameof(query));
     }
     return(await PreformQuery(query, token));
 }
Exemplo n.º 26
0
        public void Resolve(GraphQLQuery graphQLQuery)
        {
            graphQLQuery.FieldAsync <ResponseGraphType <MapType> >(
                "map",
                arguments: new QueryArguments(
                    new QueryArgument <StringGraphType>()
            {
                Name = "mapId"
            }),
                resolve: async context =>
            {
                var id          = context.GetArgument <Guid>("mapId");
                var mapFromRepo = await _playerRepository.GetMapByIdAsync(id);
                var mapToRetun  = Mapper.Map <MapDto>(mapFromRepo);
                return(Response(mapToRetun));
            });

            graphQLQuery.FieldAsync <ResponseListGraphType <MapType> >(
                "maps",
                resolve: async context =>
            {
                var mapsFromRepo = await _playerRepository.GetAllMapsAsync();
                var mapsToReturn = Mapper.Map <IEnumerable <MapDto> >(mapsFromRepo);
                return(Response(mapsToReturn));
            });

            graphQLQuery.FieldAsync <ResponseGraphType <MapType> >(
                "createMap",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <MapInputType> > {
                Name = "map"
            }
                    ),
                resolve: async context =>
            {
                var map       = context.GetArgument <MapForCreationDto>("map");
                var mapEntity = Mapper.Map <Map>(map);
                await _playerRepository.AddMapAsync(mapEntity);
                var mapToReturn = Mapper.Map <MapDto>(mapEntity);
                return(Response(mapToReturn));
            });

            graphQLQuery.FieldAsync <ResponseGraphType <MapType> >(
                "updateMap",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <MapInputType> > {
                Name = "map"
            }
                    ),
                resolve: async context =>
            {
                var map       = context.GetArgument <MapForManipulationDto>("map");
                var mapEntity = Mapper.Map <Map>(map);
                await _playerRepository.UpdateMapAsync(mapEntity);
                var mapToReturn = Mapper.Map <MapDto>(mapEntity);
                return(Response(mapToReturn));
            });
        }
Exemplo n.º 27
0
        public async Task <ActionResult> CreateOrder()
        {
            CreateOrderVm createOrderVm = new CreateOrderVm();

            //get customers
            var          graphQLClient = new GraphQLClient("http://localhost:13515/api/school");
            GraphQLQuery graphQLQuery  = GraphQLHelper.GetGraphQLQuery("GetCustomers");
            var          heroRequest   = new GraphQLRequest {
                Query = graphQLQuery.Body, OperationName = "GetAllCustomers"
            };
            var graphQLResponse = await graphQLClient.PostAsync(heroRequest);

            string          json      = JsonConvert.SerializeObject(graphQLResponse.Data);
            var             result    = JsonConvert.DeserializeObject <Dictionary <string, List <Customer> > >(json);
            List <Customer> customers = new List <Customer>();

            foreach (var obj in result.Values.ElementAt(0))
            {
                customers.Add(obj);
            }
            createOrderVm.Customers = customers;

            //get employees
            graphQLQuery = GraphQLHelper.GetGraphQLQuery("GetEmployees");
            heroRequest  = new GraphQLRequest {
                Query = graphQLQuery.Body, OperationName = "GetAllEmployees"
            };
            graphQLResponse = await graphQLClient.PostAsync(heroRequest);

            json = JsonConvert.SerializeObject(graphQLResponse.Data);
            var             result2   = JsonConvert.DeserializeObject <Dictionary <string, List <Employee> > >(json);
            List <Employee> employees = new List <Employee>();

            foreach (var obj in result2.Values.ElementAt(0))
            {
                employees.Add(obj);
            }
            createOrderVm.Employees = employees;

            //get shippers
            graphQLQuery = GraphQLHelper.GetGraphQLQuery("GetShippers");
            heroRequest  = new GraphQLRequest {
                Query = graphQLQuery.Body, OperationName = "GetAllShippers"
            };
            graphQLResponse = await graphQLClient.PostAsync(heroRequest);

            json = JsonConvert.SerializeObject(graphQLResponse.Data);
            var            result3  = JsonConvert.DeserializeObject <Dictionary <string, List <Shipper> > >(json);
            List <Shipper> shippers = new List <Shipper>();

            foreach (var obj in result3.Values.ElementAt(0))
            {
                shippers.Add(obj);
            }
            createOrderVm.Shippers = shippers;

            return(View(createOrderVm));
        }
        public void Serialize_MultiArgumentWithoutProperty_AddsProperArgumentSyntax()
        {
            var query = new GraphQLQuery <BlogPost>()
                        .WithArgument("id", 2)
                        .WithArgument("before", "8/31/2020")
                        .ToString();

            Assert.Contains("blog_post(id: 2, before: \"8/31/2020\"", query);
        }
Exemplo n.º 29
0
        public Task <OneOf <User, IAniListError> > GetAniListNotificationCount(CancellationToken cToken = default)
        {
            var query = new GraphQLQuery
            {
                Query = QueryStore.GetUserNotificationCount
            };

            return(GetResponseAsync <User>(query, cToken));
        }
Exemplo n.º 30
0
        public Task <OneOf <User, IAniListError> > GetCurrentUser(CancellationToken cToken)
        {
            var query = new GraphQLQuery
            {
                Query = QueryStore.GetCurrentUser
            };

            return(GetResponseAsync <User>(query, cToken));
        }