Example #1
0
        private async Task WriteResponseAsync(HttpContext context, ExecutionResult result)
        {
            var json = await _writer.WriteToStringAsync(result);

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = result.Errors?.Any() == true ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.OK;

            await context.Response.WriteAsync(json);
        }
 static async Task WriteStream(
     IDocumentWriter writer,
     ExecutionResult result,
     HttpResponse response,
     CancellationToken cancellation)
 {
     response.Headers.Add("Content-Type", "application/json");
     //TODO: no point doing ToString
     await response.WriteAsync(await writer.WriteToStringAsync(result), cancellation);
 }
        public ExecutionResult AssertQuery(Action <ExecutionOptions> options, ExecutionResult expectedExecutionResult)
        {
            var runResult = Executer.ExecuteAsync(options).Result;

            var writtenResult  = Writer.WriteToStringAsync(runResult).Result;
            var expectedResult = Writer.WriteToStringAsync(expectedExecutionResult).Result;

            string additionalInfo = null;

            if (runResult.Errors?.Any() == true)
            {
                additionalInfo = string.Join(Environment.NewLine, runResult.Errors
                                             .Where(x => x.InnerException is GraphQLSyntaxErrorException)
                                             .Select(x => x.InnerException.Message));
            }

            writtenResult.ShouldBe(expectedResult, additionalInfo);

            return(runResult);
        }
        public static async Task <string> ExecuteAsync(this ISchema schema, IDocumentWriter documentWriter, Action <ExecutionOptions> configure)
        {
            var executor = new DocumentExecuter();
            var result   = await executor.ExecuteAsync(options =>
            {
                options.Schema = schema;
                configure(options);
            }).ConfigureAwait(false);

            return(await documentWriter.WriteToStringAsync(result).ConfigureAwait(false));
        }
Example #5
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,
                UserContext = _userContext
            };

            var validationRuleServices = _serviceProvider.GetServices <IValidationRule>();

            executionOptions.ValidationRules = DocumentValidator.CoreRules().Concat(validationRuleServices);

            //Using middleware example
            executionOptions.FieldMiddleware.Use(next =>
            {
                return(context =>
                {
                    _logger.LogDebug($"FieldName middleware => {context.FieldName}");
                    return next(context);
                });
            });

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

            HttpStatusCode statusCode = HttpStatusCode.OK;

            if (result.Errors?.Any() ?? false)
            {
                statusCode = HttpStatusCode.InternalServerError;
                if (result.Errors.Any(x => x.Code == "VALIDATION_ERROR"))
                {
                    statusCode = HttpStatusCode.BadRequest;
                }
                else if (result.Errors.Any(x => x.Code == "UNAUTHORIZED_ACCESS"))
                {
                    statusCode = HttpStatusCode.Forbidden;
                }
            }

            return(new ContentResult
            {
                Content = await _documentWriter.WriteToStringAsync(result),
                ContentType = "application/json; charset=utf-8",
                StatusCode = (int)statusCode
            });
        }
Example #6
0
        public async void Writes_Correct_Execution_Result_With_Null_Data_And_Null_Errors(IDocumentWriter writer)
        {
            var executionResult = new ExecutionResult();

            var expected = @"{
              ""data"": null
            }";

            var actual = await writer.WriteToStringAsync(executionResult);

            actual.ShouldBeCrossPlatJson(expected);
        }
        public async Task <ExecutionResult> AssertQueryIgnoreErrors(
            string query,
            ExecutionResult expectedExecutionResult,
            Inputs inputs      = null,
            object root        = null,
            object userContext = null,
            CancellationToken cancellationToken = default(CancellationToken),
            int expectedErrorCount = 0,
            bool renderErrors      = false)
        {
            var runResult = await _executer.ExecuteAsync(_ =>
            {
                _.Schema            = _schema;
                _.Query             = query;
                _.Root              = root;
                _.Inputs            = inputs;
                _.UserContext       = userContext;
                _.CancellationToken = cancellationToken;
            });

            var renderResult = renderErrors ? runResult : new ExecutionResult {
                Data = runResult.Data
            };

            var writtenResult = await _writer.WriteToStringAsync(renderResult);

            var expectedResult = await _writer.WriteToStringAsync(expectedExecutionResult);

            // #if DEBUG
            //             Console.WriteLine(writtenResult);
            // #endif

            writtenResult.Should().Be(expectedResult);

            var errors = runResult.Errors ?? new ExecutionErrors();

            errors.Count().Should().Be(expectedErrorCount);

            return(runResult);
        }
Example #8
0
        public async Task introspection_should_return_applied_directives(IDocumentWriter documentWriter)
        {
            var documentExecuter = new DocumentExecuter();
            var executionResult  = await documentExecuter.ExecuteAsync(_ =>
            {
                _.Schema = new AppliedSchema().EnableExperimentalIntrospectionFeatures(ExperimentalIntrospectionFeaturesMode.IntrospectionAndExecution);
                _.Query  = "AppliedDirectives".ReadGraphQLRequest();
            });

            var json = await documentWriter.WriteToStringAsync(executionResult);

            executionResult.Errors.ShouldBeNull();

            json.ShouldBe("AppliedDirectivesResult".ReadJsonResult());
        }
        public async Task validate_non_null_schema(IDocumentWriter documentWriter)
        {
            var documentExecuter = new DocumentExecuter();
            var executionResult  = await documentExecuter.ExecuteAsync(_ =>
            {
                _.Schema = new TestSchema();
                _.Query  = InputObjectBugQuery;
            });

            var json = await documentWriter.WriteToStringAsync(executionResult);

            executionResult.Errors.ShouldBeNull();

            ShouldBe(json, InputObjectBugResult);
        }
Example #10
0
        public async void Writes_Correct_Execution_Result_With_Empty_Data_Errors_And_Extensions(IDocumentWriter writer)
        {
            var executionResult = new ExecutionResult
            {
                Data       = new Dictionary <string, object>(),
                Errors     = new ExecutionErrors(),
                Extensions = new Dictionary <string, object>()
            };

            var expected = @"{ ""data"": {} }";

            var actual = await writer.WriteToStringAsync(executionResult);

            actual.ShouldBeCrossPlatJson(expected);
        }
Example #11
0
        public override void Assert(Scenario scenario, HttpContext context, ScenarioAssertionException ex)
        {
            var expectedResult   = CreateQueryResult(_result);
            var actualResultJson = ex.ReadBody(context);

            if (_ignoreExtensions)
            {
                expectedResult.Extensions = null;

                var actualResult = actualResultJson.ToDictionary();
                if (actualResult.ContainsKey(extensionsKey))
                {
                    actualResult.Remove(extensionsKey);
                }
                actualResultJson = _writer.WriteToStringAsync(actualResult).GetAwaiter().GetResult();
            }

            var expectedResultJson = _writer.WriteToStringAsync(expectedResult).GetAwaiter().GetResult();

            if (!actualResultJson.Equals(expectedResultJson))
            {
                ex.Add($"Expected '{expectedResult}' but got '{actualResultJson}'");
            }
        }
Example #12
0
        public async Task validate_core_schema(IDocumentWriter documentWriter)
        {
            var documentExecuter = new DocumentExecuter();
            var executionResult  = await documentExecuter.ExecuteAsync(_ =>
            {
                _.Schema = new Schema
                {
                    Query = new TestQuery()
                };
                _.Query = "IntrospectionQuery".ReadGraphQLRequest();
            });

            var json = await documentWriter.WriteToStringAsync(executionResult);

            ShouldBe(json, "IntrospectionResult".ReadJsonResult());
        }
        /// <summary>
        /// Executes a GraphQL request with the default <see cref="DocumentExecuter"/>, serializes the result using the specified <see cref="IDocumentWriter"/>, and returns the result
        /// </summary>
        /// <param name="configure">A delegate which configures the execution options</param>
        public static async Task<string> ExecuteAsync( this ISchema schema, IDocumentWriter documentWriter, Action<ExecutionOptions> configure )
        {
            if ( configure == null )
            {
                throw new ArgumentNullException( nameof( configure ) );
            }

            var executor = new DocumentExecuter();
            var result = await executor.ExecuteAsync( options =>
             {
                 options.Schema = schema;
                 configure( options );
             } ).ConfigureAwait( false );

            return await documentWriter.WriteToStringAsync( result ).ConfigureAwait( false );
        }
        public async Task validate_core_schema(IDocumentWriter documentWriter)
        {
            var documentExecuter = new DocumentExecuter();
            var executionResult  = await documentExecuter.ExecuteAsync(_ =>
            {
                _.Schema = new Schema
                {
                    Query = new TestQuery()
                };
                _.Query = SchemaIntrospection.IntrospectionQuery;
            });

            var json = await documentWriter.WriteToStringAsync(executionResult);

            ShouldBe(json, IntrospectionResult.Data);
        }
Example #15
0
        public async Task validate_core_schema_pascal_case(IDocumentWriter documentWriter)
        {
            var documentExecuter = new DocumentExecuter();
            var executionResult  = await documentExecuter.ExecuteAsync(_ =>
            {
                _.Schema = new Schema
                {
                    Query         = new TestQuery(),
                    NameConverter = PascalCaseNameConverter.Instance,
                };
                _.Query = "IntrospectionQuery".ReadGraphQLRequest();
            });

            var json = await documentWriter.WriteToStringAsync(executionResult);

            ShouldBe(json, "IntrospectionResult".ReadJsonResult().Replace("\"test\"", "\"Test\""));
        }
Example #16
0
        public async Task <string> Generate()
        {
            ExecutionResult result = await executor.ExecuteAsync(
                new ExecutionOptions
            {
                Schema = _schema,
                Query  = introspectionQuery
            }
                );

            if (result.Errors?.Any() ?? false)
            {
                throw result.Errors.First();
            }

            return(await writer.WriteToStringAsync(result));
        }
Example #17
0
        public async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
            HttpRequestMessage request, ILogger log, ExecutionContext context)
        {
            if (_config == null)
            {
                _config = new ConfigurationBuilder()
                          .SetBasePath(context.FunctionAppDirectory)
                          .AddJsonFile("local.settings.json")
                          .AddEnvironmentVariables()
                          .Build();
            }

            var query = JsonConvert.DeserializeObject <GraphQLQuery>(await request.Content.ReadAsStringAsync());

            var inputs = query.Variables.ToInputs();

            var queryToExecute = query.Query;

            var result = await _documentExecuter.ExecuteAsync(_ =>
            {
                _.Schema        = _schema;
                _.Query         = queryToExecute;
                _.OperationName = query.OperationName;
                _.Inputs        = inputs;

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

            var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;

            var json = await _documentWriter.WriteToStringAsync(result);

            var response = request.CreateResponse(httpResult);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");

            return(response);
        }
Example #18
0
        public async Task LongMaxValueShouldBeSerialized(IDocumentWriter documentWriter)
        {
            var documentExecuter = new DocumentExecuter();
            var executionResult  = await documentExecuter.ExecuteAsync(_ =>
            {
                _.Schema = new LongSchema();
                _.Query  = "{ testField }";
            });

            var json = await documentWriter.WriteToStringAsync(executionResult);

            executionResult.Errors.ShouldBeNull();

            json.ShouldBe(@"{
  ""data"": {
    ""testField"": 9223372036854775807
  }
}");
        }
Example #19
0
        public async void Can_Write_Execution_Result(IDocumentWriter writer)
        {
            var executionResult = new ExecutionResult
            {
                Executed = true,
                Data     = @"{ ""someType"": { ""someProperty"": ""someValue"" } }".ToDictionary(),
                Errors   = new ExecutionErrors
                {
                    new ExecutionError("some error 1"),
                    new ExecutionError("some error 2"),
                },
                Extensions = new Dictionary <string, object>
                {
                    { "someExtension", new { someProperty = "someValue", someOtherPropery = 1 } }
                }
            };

            var expected = @"{
              ""errors"": [
                {
                  ""message"": ""some error 1""
                },
                {
                  ""message"": ""some error 2""
                }
              ],
              ""data"": {
                ""someType"": {
                    ""someProperty"": ""someValue""
                }
              },
              ""extensions"": {
                ""someExtension"": {
                  ""someProperty"": ""someValue"",
                  ""someOtherPropery"": 1
                }
              }
            }";

            var actual = await writer.WriteToStringAsync(executionResult);

            actual.ShouldBeCrossPlatJson(expected);
        }
Example #20
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log,
            [Inject(typeof(IDocumentWriter))] IDocumentWriter _writer,
            [Inject(typeof(IDocumentExecuter))] IDocumentExecuter _executer,
            [Inject(typeof(ISchema))] ISchema schema
            )
        {
            var request = Deserialize <GraphQLRequest>(req.Body);

            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema        = schema;
                _.Query         = request.Query;
                _.OperationName = request.OperationName;
                _.Inputs        = request.Variables.ToInputs();
            });

            return(new OkObjectResult(await _writer.WriteToStringAsync(result)));
        }
Example #21
0
        public async void Writes_Path_Property_Correctly(IDocumentWriter writer)
        {
            var executionResult = new ExecutionResult
            {
                Data       = null,
                Errors     = new ExecutionErrors(),
                Extensions = null,
            };
            var executionError = new ExecutionError("Error testing index")
            {
                Path = new object[] { "parent", 23, "child" }
            };

            executionResult.Errors.Add(executionError);

            var expected = @"{ ""errors"": [{ ""message"": ""Error testing index"", ""path"": [ ""parent"", 23, ""child"" ] }] }";

            var actual = await writer.WriteToStringAsync(executionResult);

            actual.ShouldBeCrossPlatJson(expected);
        }
Example #22
0
        public async Task <IActionResult> Post(
            [FromBody] GraphQLRequest request,
            [FromServices] ISchema schema)
        {
            var result = await _executer.ExecuteAsync(_ =>
            {
                _.Schema           = schema;
                _.OperationName    = request.OperationName;
                _.Query            = request.Query;
                _.Inputs           = request.Variables.ToInputs();
                _.ExposeExceptions = true;
            });

            var json = await _writer.WriteToStringAsync(result);

            var httpResult = result.Errors?.Count > 0
                ? HttpStatusCode.BadRequest
                : HttpStatusCode.OK;

            return(Content(json, "application/json"));
        }
Example #23
0
        public async Task <T> ExecuteQuery <T>(GraphQlRequest request)
        {
            var schema = new Schema {
                Query = _applicationSummaryQuery
            };

            var queryResult = await _executer.ExecuteAsync(doc =>
            {
                doc.Schema = schema;
                doc.Query  = request.Query;

                doc.Inputs = request.Variables.ToInputs();
            })
                              .ConfigureAwait(false);

            var str = await _writer.WriteToStringAsync(queryResult);

            var result = JsonConvert.DeserializeObject <T>(str);

            return(result);
        }
    static async Task WriteMultipart(
        IDocumentWriter writer,
        HttpResponse response,
        ExecutionResult result,
        OutgoingAttachments attachments,
        CancellationToken cancellation)
    {
        List <HttpContent> httpContents = new();

        try
        {
            using MultipartFormDataContent multipart = new()
                  {
                      //TODO: no point doing ToString
                      { new StringContent(await writer.WriteToStringAsync(result)), "result" }
                  };

            foreach (var attachment in attachments.Inner)
            {
                httpContents.Add(await AddAttachment(attachment, multipart, cancellation));
            }

            response.ContentLength = multipart.Headers.ContentLength;
            response.ContentType   = multipart.Headers.ContentType?.ToString();
            await multipart.CopyToAsync(response.Body, cancellation);
        }
        finally
        {
            foreach (var httpContent in httpContents)
            {
                httpContent.Dispose();
            }

            foreach (var cleanup in attachments.Inner.Select(x => x.Value.Cleanup))
            {
                cleanup?.Invoke();
            }
        }
    }
Example #25
0
        public async void Writes_Correct_Execution_Result_With_Null_Data_And_Some_Errors(IDocumentWriter writer)
        {
            // "If an error was encountered before execution begins, the data entry should not be present in the result."
            // Source: https://github.com/graphql/graphql-spec/blob/master/spec/Section%207%20--%20Response.md#data

            var executionResult = new ExecutionResult
            {
                Errors = new ExecutionErrors
                {
                    new ExecutionError("some error 1"),
                    new ExecutionError("some error 2"),
                }
            };

            var expected = @"{
              ""errors"": [{""message"":""some error 1""},{""message"":""some error 2""}]
            }";

            var actual = await writer.WriteToStringAsync(executionResult);

            actual.ShouldBeCrossPlatJson(expected);
        }
        public async Task <IActionResult> GraphQl([FromBody] GraphQlQueryModel model)
        {
            var result = await _documentExecuter.ExecuteAsync(e =>
            {
                e.Schema                  = _schema;
                e.OperationName           = model.OperationName;
                e.Inputs                  = model.Variables?.ToInputs();
                e.Query                   = model.Query;
                e.ComplexityConfiguration = new ComplexityConfiguration {
                    MaxDepth = 15
                };
                e.FieldMiddleware.Use <InstrumentFieldsMiddleware>();
            });

            var json = await _documentWriter.WriteToStringAsync(result);

            var response = JObject.Parse(json);

            return(result.Errors?.Count > 0
                                ? (IActionResult)BadRequest(response)
                                : Ok(response));
        }
Example #27
0
            public async Task <GraphQLResponse <TResponse> > SendQueryAsync <TResponse>(GraphQLRequest request, CancellationToken cancellationToken = default)
            {
                var res = await executer
                          .ExecuteAsync(_ =>
                {
                    _.Schema = schema;
                    _.Query  = request.Query;
                    _.Root   = root;
                })
                          .ConfigureAwait(false);

                if (res.Errors is ExecutionErrors err && err.Any())
                {
                    throw new Exception();
                }

                var text = await writer
                           .WriteToStringAsync(res)
                           .ConfigureAwait(false);

                return(await new NewtonsoftJsonSerializer()
                       .DeserializeFromUtf8StreamAsync <TResponse>(new MemoryStream(Encoding.UTF8.GetBytes(text)), cancellationToken)
                       .ConfigureAwait(false));
            }