public async Task DocumentExecuter_has_valid_options() { var de = new DocumentExecuter(); var valid = await de.ExecuteAsync(new ExecutionOptions { Query = "{test}", Schema = Schema, }); valid.Data.ShouldNotBeNull(); await Assert.ThrowsAsync <InvalidOperationException>(async() => { await de.ExecuteAsync(new ExecutionOptions() { Query = null, Schema = Schema, }); }); await Assert.ThrowsAsync <InvalidOperationException>(async() => { await de.ExecuteAsync(new ExecutionOptions() { Query = "{test}", Schema = null, }); }); }
public async Task DocumentExecuter_has_valid_options() { var de = new DocumentExecuter(); var valid = await de.ExecuteAsync(new ExecutionOptions { Query = "{test}", Schema = Schema, }).ConfigureAwait(false); valid.Data.ShouldNotBeNull(); var result = await de.ExecuteAsync(new ExecutionOptions() { Query = null, Schema = Schema, }).ConfigureAwait(false); result.Errors.Single().ShouldBeOfType(typeof(QueryMissingError)); result.Errors.Single().Locations.ShouldBeNull(); result.Errors.Single().Path.ShouldBeNull(); await Assert.ThrowsAsync <InvalidOperationException>(async() => { await de.ExecuteAsync(new ExecutionOptions() { Query = "{test}", Schema = null, }).ConfigureAwait(false); }).ConfigureAwait(false); }
public async Task <string> QueryGraphQLAsync(string query) { var result = await DocumentExecuter .ExecuteAsync(options => { options.Schema = Schema; options.Query = query; }) .ConfigureAwait(false); var json = new DocumentWriter(indent: true).Write(result); return(json); }
public void apply_to_called_once_with_multiple_execute() { var docExec = new DocumentExecuter(); var execOptions = new ExecutionOptions(); execOptions.Schema = new Schema(); var mockMiddleware = new ApplyCounterMiddlewareBuilder(); execOptions.FieldMiddleware = mockMiddleware; docExec.ExecuteAsync(execOptions).Wait(); docExec.ExecuteAsync(execOptions).Wait(); Assert.Equal(1, mockMiddleware.AppliedCount); }
public async Task Invoke(HttpContext httpContext) { var logger = httpContext.RequestServices.GetService <ILogger <GraphQlMiddleware> >(); HttpRequest request = httpContext.Request; HttpResponse response = httpContext.Response; // GraphQL HTTP only supports GET and POST methods. if (request.Method != "GET" && request.Method != "POST") { response.Headers.Add("Allow", "GET, POST"); response.StatusCode = 405; return; } // Check authorization if (options.AuthorizationPolicy != null) { var authorizationService = httpContext.RequestServices.GetRequiredService <IAuthorizationService>(); var authzResult = await authorizationService.AuthorizeAsync(httpContext.User, options.AuthorizationPolicy); if (!authzResult.Succeeded) { await httpContext.ForbidAsync(); return; } } GraphQlParameters parameters = await GetParametersAsync(request); ISchema schema = schemaProvider.Create(httpContext.RequestServices); var result = await executer.ExecuteAsync(executionOptions => { executionOptions.Schema = schema; executionOptions.Query = parameters.Query; executionOptions.OperationName = parameters.OperationName; executionOptions.Inputs = parameters.GetInputs(); executionOptions.CancellationToken = httpContext.RequestAborted; executionOptions.ComplexityConfiguration = options.ComplexityConfiguration; executionOptions.UserContext = httpContext; executionOptions.ExposeExceptions = options.ExposeExceptions; ConfigureDocumentExecutionListeners(executionOptions, executionListeners); }); if (result.Errors?.Count > 0) { logger.LogError("GraphQL Result {Errors}", result.Errors); } var writer = new DocumentWriter(indent: options.FormatOutput); var json = writer.Write(result); response.StatusCode = 200; response.ContentType = "application/json; charset=utf-8"; await response.WriteAsync(json); }
public async Task should_map(IGraphQLTextSerializer serializer) { var documentExecuter = new DocumentExecuter(); var executionResult = await documentExecuter.ExecuteAsync(_ => { _.Schema = new Issue2275Schema(); _.Query = @"query($data:Input!) { request(data: $data) }"; _.Variables = serializer.Deserialize <Inputs>(@"{ ""data"": { ""clientId"": 2, ""filters"": [{ ""key"": ""o"", ""value"": 25 }] } }"); }).ConfigureAwait(false); var json = serializer.Serialize(executionResult); executionResult.Errors.ShouldBeNull(); json.ShouldBe(@"{ ""data"": { ""request"": ""2: [o=25]"" } }"); }
public async Task issue_1155_throws() { var schema = Schema.For(@" type Test { id: ID! name: String! } type Query { test: Test! } ", builder => { builder.Types.Include <Query>(); }); var executor = new DocumentExecuter(); var result = await executor.ExecuteAsync(options => { options.Schema = schema; options.Query = "{ test { id name } }"; }).ConfigureAwait(false); result.Errors.Count.ShouldBe(1); result.Errors[0].Code.ShouldBe("INVALID_OPERATION"); result.Errors[0].Message.ShouldBe("Error trying to resolve field 'name'."); result.Errors[0].InnerException.ShouldBeOfType <InvalidOperationException>().Message.ShouldBe("Expected to find property or method 'name' on type 'Test' but it does not exist."); }
public async Task issue_1155_with_custom_root_does_not_throw() { var schema = Schema.For(@" type Test { id: ID! name: String! } type Query { test: Test! } ", builder => { builder.Types.Include <Query>(); }); var executor = new DocumentExecuter(); var result = await executor.ExecuteAsync(options => { options.Schema = schema; options.Query = "{ test { id name } }"; options.Root = new QueryEx(); }).ConfigureAwait(false); result.Errors.ShouldBeNull(); var data = result.Data.ShouldBeOfType <Dictionary <string, object> >(); var t = data["test"].ShouldBeOfType <Dictionary <string, object> >(); t["id"].ShouldBe("foo"); t["name"].ShouldBe("bar"); }
protected async Task <IActionResult> RunQuery(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) { #if !DEBUG foreach (var error in result.Errors) { _logger.LogError(error, $"Something wrong while processing the GraphQL request."); } #endif return(BadRequest(result)); } return(Ok(result)); }
public async Task Bug2839Test() { var schema = new Schema { Query = new TestQuery() }; schema.ReplaceScalar(new MyDateTimeGraphType()); var exec = new DocumentExecuter(); var result = exec.ExecuteAsync(options => { options.Schema = schema; options.Query = "{ test { thisIsAString, thisIsADateTime } }"; } ).Result; var writer = new DocumentWriter(options => { options.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MMM-dd", Culture = System.Globalization.CultureInfo.InvariantCulture, }); options.ContractResolver = new ExecutionResultContractResolver(new ErrorInfoProvider()) { NamingStrategy = new KebabCaseNamingStrategy(true, false, false) }; }); var str = await writer.WriteToStringAsync(result); str.ShouldBeCrossPlatJson("{\"data\":{\"test\":{\"this-is-a-string\":\"String Value\",\"this-is-a-date-time\":\"2022-Jan-04\"}}}"); }
public async Task <QueryResponse> Get(string query) { var schema = new Schema { Query = new UserQuery() }; var executer = new DocumentExecuter(); var result = await executer.ExecuteAsync(opt => { opt.Schema = schema; opt.Query = query; }); if (result.Errors is null || result.Data != null) { return(new SuccessfullQueryResponse(result.Data)); } if (result.Errors.Any() || result.Data is null) { return(new FailedQueryResponse(result.Errors.Select(x => x.Message))); } return(new PartiallySuccessfullQueryResponse(result.Data, result.Errors.Select(x => x.Message))); }
static void Main(string[] args) { string queryStr; if (args.Count() == 1) { queryStr = args[0]; } else { Console.WriteLine("Query string expected as argument"); return; } var schema = Schema.For( File.ReadAllLines("schema.graphql"), _ => { _.Types.Include <Query.Query>(); }); var execOptions = new ExecutionOptions { Schema = schema, Query = queryStr }; var docExec = new DocumentExecuter(); var task = docExec.ExecuteAsync(execOptions); task.Wait(); var result = JsonNet.Serialize(task.Result.Data); Console.WriteLine($"Request: {queryStr}"); Console.WriteLine($"Response: {result}"); }
public async Task should_map(IDocumentWriter documentWriter) { var documentExecuter = new DocumentExecuter(); var executionResult = await documentExecuter.ExecuteAsync(_ => { _.Schema = new Issue2275Schema(); _.Query = @"query($data:Input!) { request(data: $data) }"; _.Inputs = @" { ""data"": { ""clientId"": 2, ""filters"": [{ ""key"": ""o"", ""value"": 25 }] } }".ToInputs(); }); var json = await documentWriter.WriteToStringAsync(executionResult); executionResult.Errors.ShouldBeNull(); json.ShouldBe(@"{ ""data"": { ""request"": ""2: [o=25]"" } }"); }
private async Task HandleIntrospectionQuery(RequestPayload requestPayload, HttpContext httpContext) { var schema = _schemaProvider.Schema; var convertedSchema = _schema ?? _schemaConverter.Convert(schema); var docuemntExecutor = new DocumentExecuter(); var executionOptions = new ExecutionOptions() { Schema = convertedSchema, OperationName = requestPayload.OperationName, Query = requestPayload.Query, Inputs = new Inputs(), EnableMetrics = false, ExposeExceptions = true, SetFieldMiddleware = false, FieldNameConverter = _graphOptions.FieldNameConverter == FieldNameConverter.Default ? _defaultConverter : _camelCaseConverter }; var result = await docuemntExecutor.ExecuteAsync(executionOptions); httpContext.Response.ContentType = "application/json"; httpContext.Response.StatusCode = 200; await new DocumentWriter().WriteAsync(httpContext.Response.Body, result); }
public async Task <IActionResult> Post([FromBody] GraphQLQuery query) { Inputs inputs = query.Variables.ToInputs(); ExecutionResult result = null; using (Schema schema = new Schema()) { schema.Query = new Queries(DataContext); void options(ExecutionOptions x) { x.Schema = schema; x.Query = query.Query; x.OperationName = query.OperationName; x.Inputs = inputs; } DocumentExecuter documentExecuter = new DocumentExecuter(); result = await documentExecuter.ExecuteAsync(options); if (result?.Errors?.Count > 0) { return(BadRequest(result.Errors)); } } return(Ok(result?.Data)); }
public async Task schema_first_generate_exception_with_normal_stack_trace_for_property() { var schema = Schema.For(@" type Query { method: String! property: Int! } ", builder => builder.Types.Include <Query>()); var executor = new DocumentExecuter(); var result = await executor.ExecuteAsync(options => { options.Schema = schema; options.Query = "{ property }"; }).ConfigureAwait(false); result.Errors.Count.ShouldBe(1); result.Errors[0].Code.ShouldBe("DIVIDE_BY_ZERO"); result.Errors[0].Message.ShouldBe("Error trying to resolve field 'property'."); var stack = result.Errors[0].InnerException.ShouldBeOfType <DivideByZeroException>().StackTrace; if (stack.StartsWith(" в ")) { stack = stack.Remove(0, 5); } if (stack.StartsWith(" at ")) { stack = stack.Remove(0, 6); } stack.ShouldStartWith("GraphQL.Tests.Utilities.SchemaBuilderExecutionTests.Query.get_Property()"); }
static void Main(string[] args) { var executer = new DocumentExecuter(); var writer = new DocumentWriter(); //var query = @"{ // artists { // name // } // }"; var query = "{ artist(name: \"Alice Cooper\") { name } }"; var root = new QueryRoot(); var schema = new Schema <QueryRoot>(); var result = executer.ExecuteAsync(config => { config.Schema = schema; config.Root = root; config.Query = query; }); Console.WriteLine(writer.Write(result.Result)); }
private static async Task ExecuteAsync(HttpContext context, ISchema schema) { GraphQLRequest request; using (var reader = new StreamReader(context.Request.Body)) using (var jsonReader = new JsonTextReader(reader)) { var ser = new JsonSerializer(); request = ser.Deserialize <GraphQLRequest>(jsonReader); } var executer = new DocumentExecuter(); var result = await executer.ExecuteAsync(options => { options.Schema = schema; if (request == null) { return; } options.Query = request.Query; options.OperationName = request.OperationName; options.Inputs = request.Variables.ToInputs(); }); context.Response.ContentType = "application/json"; context.Response.StatusCode = result.Errors?.Any() == true ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.OK; var writer = new DocumentWriter(); await writer.WriteAsync(context.Response.Body, result); }
public void Query_sandbox() { const string query = @" { customers(limit: 10) { customerId companyName contactName } }"; using (var data = CreateContext()) { var schema = new NorthwindGraph(); var documentExecutor = new DocumentExecuter(); var result = documentExecutor.ExecuteAsync(schema, data, query, null).Result; Assert.Null(result.Errors); var jsonResult = new DocumentWriter().Write(result); WriteLine(); WriteLine(jsonResult); } }
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); }
public void WithDecimal_HasCorrectType() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(EchoSchema)); var query = @"{ __type(name : ""Input_Schema1Request"") { name fields{ name type{ kind name } } }"; var exec = new DocumentExecuter(new AntlrDocumentBuilder(), new DocumentValidator()); var result = exec.ExecuteAsync(schema, null, query, null).Result; var writer = new DocumentWriter(indent: true); var writtenResult = writer.Write(result.Data); var errors = result.Errors?.FirstOrDefault(); Assert.Null(errors?.Message); Assert.True(writtenResult.Contains("decimal")); }
static void Main(string[] args) { IServiceCollection services = new ServiceCollection(); services.AddScoped <IDataLoaderContextAccessor, DataLoaderContextAccessor>() .AddScoped <DataLoaderDocumentListener>() .AddScoped <IChefRepository, ChefRepository>() .AddScoped <IPersonRepository, PersonRepository>() .AddScoped <IDependencyResolver>(s => new FuncDependencyResolver(s.GetRequiredService)) .AddScoped <TestSchema>() .AddScoped <Query>() .AddScoped <Data>() .AddScoped <ChefType>() .AddScoped <PersonType>(); var serviceProvider = services.BuildServiceProvider(); var listener = serviceProvider.GetRequiredService <DataLoaderDocumentListener>(); var executer = new DocumentExecuter(); var schema = serviceProvider.GetRequiredService <TestSchema>(); var result = executer.ExecuteAsync(_ => { _.Schema = schema; _.ExposeExceptions = true; _.Query = "{ chefs { id name employees { id name } } }"; _.Listeners.Add(listener); }); var json = new DocumentWriter(indent: true).Write(result.Result); Console.WriteLine(json); Console.Read(); }
public void FieldDescription_Works() { var schemaGenerator = new SchemaGenerator(new MockServiceProvider()); var schema = schemaGenerator.CreateSchema(typeof(AsyncSchema)); var query = @"{ __schema{ types{ name, fields { name description } } } }"; var exec = new DocumentExecuter(new GraphQLDocumentBuilder(), new DocumentValidator(), new ComplexityAnalyzer()); var result = exec.ExecuteAsync(schema, null, query, null).Result; var writer = new DocumentWriter(indent: true); var writtenResult = writer.Write(result.Data); var errors = result.Errors?.FirstOrDefault(); Assert.Null(errors?.Message); Assert.True(writtenResult.Contains("{VerifyComment}")); }
public void Bug2839Test() { var schema = new Schema { Query = new TestQuery() }; schema.ReplaceScalar(new MyDateTimeGraphType()); var exec = new DocumentExecuter(); var result = exec.ExecuteAsync(options => { options.Schema = schema; options.Query = "{ test { thisIsAString, thisIsADateTime } }"; } ).Result; var writer = new GraphQLSerializer(options => { options.PropertyNamingPolicy = new MyNamingPolicy(); options.Converters.Add(new MyDateTimeConverter()); }); var str = writer.Serialize(result); str.ShouldBeCrossPlatJson("{\"data\":{\"TEST\":{\"THISISASTRING\":\"String Value\",\"THISISADATETIME\":\"2022-Jan-04\"}}}"); }
public async Task ExecuteAsync(ExecutionContext executionContext, Func <Task> next) { var documentExecuter = new DocumentExecuter(); executionContext.UserContext.Add("serviceProvider", _serviceProvider); var result = await documentExecuter.ExecuteAsync(_ => { _.Schema = _schema; _.Query = executionContext.Request.Query; _.OperationName = executionContext.Request.OperationName; _.Inputs = executionContext.Request.Variables?.ToInputs(); _.CancellationToken = executionContext.CancellationToken; _.ComplexityConfiguration = executionContext.ComplexityConfiguration; _.EnableMetrics = executionContext.EnableMetrics; _.ExposeExceptions = executionContext.ExposeExceptions; _.FieldMiddleware = executionContext.FieldMiddleware; foreach (var listener in executionContext.Listeners) { _.Listeners.Add(listener); } _.MaxParallelExecutionCount = executionContext.MaxParallelExecutionCount; _.ThrowOnUnhandledException = executionContext.ThrowOnUnhandledException; _.UnhandledExceptionDelegate = executionContext.UnhandledExceptionDelegate; _.UserContext = executionContext.UserContext; _.ValidationRules = executionContext.ValidationRules.Concat(DocumentValidator.CoreRules); _.UserContext = executionContext.UserContext; }); executionContext.Result = result; }
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 executer exception", ex); return(BadRequest(ex)); } }
public static async Task <object> ExecuteQuery(string queryString, ServiceCollection services, DbContext dataContext, Inputs inputs) { queryString = queryString.Replace("'", "\""); EfGraphQLConventions.RegisterConnectionTypesInContainer(services); EfGraphQLConventions.RegisterInContainer(services, dataContext); using (var provider = services.BuildServiceProvider()) using (var schema = new Schema(new FuncDependencyResolver(provider.GetRequiredService))) { var documentExecuter = new DocumentExecuter(); var executionOptions = new ExecutionOptions { Schema = schema, Query = queryString, UserContext = dataContext, Inputs = inputs }; var executionResult = await documentExecuter.ExecuteAsync(executionOptions).ConfigureAwait(false); if (executionResult.Errors != null && executionResult.Errors.Count > 0) { if (executionResult.Errors.Count == 1) { throw executionResult.Errors.First(); } throw new AggregateException(executionResult.Errors); } return(executionResult.Data); } }
public void validate_core_schema() { var documentExecuter = new DocumentExecuter(); var executionResult = documentExecuter.ExecuteAsync(new Schema(), null, SchemaIntrospection.IntrospectionQuery, null).Result; var json = new DocumentWriter(true).Write(executionResult.Data); json.ShouldBe(IntrospectionResult.Data); }
private ExecutionResult ExecuteQuery(ISchema schema, string query) { return(_executer.ExecuteAsync(_ => { _.Schema = schema; _.Query = query; }).GetAwaiter().GetResult()); }
public void validate_core_schema() { var documentExecuter = new DocumentExecuter(); var executionResult = documentExecuter.ExecuteAsync(new Schema(), null, SchemaIntrospection.IntrospectionQuery, null).Result; var json = new DocumentWriter(true).Write(executionResult.Data); json.ShouldEqual(IntrospectionResult.Data); }
public void apply_to_called_once_with_multiple_execute() { var docExec = new DocumentExecuter(); var execOptions = new ExecutionOptions { Schema = new Schema(), Query = "{ abcd }" }; var mockMiddleware = new ApplyCounterMiddlewareBuilder(); execOptions.FieldMiddleware = mockMiddleware; docExec.ExecuteAsync(execOptions).Wait(); docExec.ExecuteAsync(execOptions).Wait(); mockMiddleware.AppliedCount.ShouldBe(1); }
public void validate_non_null_schema() { var documentExecuter = new DocumentExecuter(); var executionResult = documentExecuter.ExecuteAsync(new TestSchema(), null, InputObjectBugQuery, null).Result; var json = new DocumentWriter(true).Write(executionResult.Data); executionResult.Errors.ShouldBeNull(); json.ShouldBe(InputObjectBugResult); }
public async Task ExecutingThenDisposing_DoesNotThrowException() { var executer = new DocumentExecuter(); var schema = new Schema(); await executer.ExecuteAsync(schema, null, "{noop}", null).ConfigureAwait(false); Should.NotThrow(() => schema.Dispose()); }
public async Task<ExecutionResult> Execute( Schema schema, object rootObject, string query, string operationName = null, Inputs inputs = null) { var executer = new DocumentExecuter(); return await executer.ExecuteAsync(schema, rootObject, query, operationName); }
public GraphQLModule(ISchema schema) { _schema = schema; Get["/graphql", runAsync: true] = async (_, token) => { var queryModel = this.Bind<GraphQLQuery>(); var executer = new DocumentExecuter(); var queryResult = await executer.ExecuteAsync(_schema, null, queryModel.Query, null); return queryResult; ; }; }