public static HttpQueryRequest CreateIntrospectionQuery(ISchemaFeatures features) { DocumentNode document = CreateIntrospectionQueryDocument(features); string sourceText = QuerySyntaxSerializer.Serialize(document, false); return(new HttpQueryRequest(sourceText, "introspection_phase_2")); }
public void ParseValue_ValueIsSimpleInput() { // arrange ISchema schema = SchemaBuilder.New() .AddQueryType(c => c .Name("Query") .Field("foo") .Type <StringType>() .Resolver("bar")) .AddType(new InputObjectType <SimpleInput>(d => d .Ignore(t => t.Id))) .Create(); InputObjectType type = schema.GetType <InputObjectType>("SimpleInput"); // act IValueNode valueNode = type.ParseValue( new SimpleInput { Id = 1, Name = "foo" }); // assert QuerySyntaxSerializer.Serialize(valueNode).MatchSnapshot(); }
private static void SerializeDocument( Utf8JsonWriter writer, DocumentModel document) { writer.WriteStartObject(); writer.WriteString("original", QuerySyntaxSerializer.Serialize(document.OriginalDocument)); writer.WriteString("optimized", QuerySyntaxSerializer.Serialize(document.OptimizedDocument)); writer.WriteString("hashAlgorithm", document.HashAlgorithm); writer.WriteString("hash", document.Hash); writer.WritePropertyName("operations"); writer.WriteStartArray(); foreach (OperationModel operation in document.Operations) { SerializeOperation(writer, operation); } writer.WriteEndArray(); writer.WriteEndObject(); }
private async Task WriteToStringAsync( CodeWriter writer, DocumentNode document) { await writer.WriteIndentAsync(); await writer.WriteAsync("public override string ToString() => "); await writer.WriteLineAsync(); using (writer.IncreaseIndent()) { string documentString = QuerySyntaxSerializer.Serialize(document, true) .Replace("\"", "\"\"") .Replace("\r\n", "\n") .Replace("\n\r", "\n") .Replace("\r", "\n") .Replace("\n", "\n" + writer.GetIndentString()); await writer.WriteIndentAsync(); await writer.WriteAsync("@\""); await writer.WriteAsync(documentString); await writer.WriteAsync("\";"); await writer.WriteLineAsync(); } }
public void Replace_Variable_In_Object_List_Object() { // arrange ISchema schema = CreateSchemaBuilder() .AddType(new InputObjectType(d => d .Name("Foo1") .Field("bar") .Type(new ListTypeNode(new NamedTypeNode("Foo2"))))) .AddType(new InputObjectType(d => d .Name("Foo2") .Field("bar") .Type <ListType <StringType> >())) .Create(); var value = new ObjectValueNode( new ObjectFieldNode( "bar", new ListValueNode( new ObjectValueNode( new ObjectFieldNode( "bar", new VariableNode("abc")))))); var type = schema.GetType <InputObjectType>("Foo1"); var variables = new VariableCollectionMock("abc", "def"); var typeConversion = new TypeConversion(); // act IValueNode rewritten = VariableToValueRewriter.Rewrite( value, type, variables, typeConversion); // assert QuerySyntaxSerializer.Serialize(rewritten).MatchSnapshot(); }
private static string SerializeValue(IValueNode value) { if (value is ScopedVariableNode variable) { return($"${variable.Scope.Value}:{variable.Name.Value}"); } return(QuerySyntaxSerializer.Serialize(value)); }
public void WriteTo(Stream output) { using (var sw = new StreamWriter(output)) { QuerySyntaxSerializer.Serialize(Document, sw, false); sw.Flush(); } }
public ReadOnlySpan <byte> ToSource() { using (var stream = new MemoryStream()) { using (var sw = new StreamWriter(stream)) { QuerySyntaxSerializer.Serialize(Document, sw, false); } return(stream.ToArray()); } }
public void QueryDocument_ToSource() { // arrange // act var query = new QuerySourceText("{ a }"); // assert QuerySyntaxSerializer.Serialize( Utf8GraphQLParser.Parse(query.ToSpan())) .ToString().MatchSnapshot(); }
public void FindUndeclaredVariablesFragmentDefinition() { // arrange ISchema schema = SchemaBuilder.New() .AddStarWarsTypes() .Create(); DocumentNode document = Utf8GraphQLParser.Parse( @" query getHero { ... q } fragment q on Query { hero(episode: $ep) { name } } "); OperationDefinitionNode operation = document.Definitions .OfType <OperationDefinitionNode>() .First(); var visitor = new CollectVariablesVisitor(schema); var visitationMap = new CollectVariablesVisitationMap(); visitationMap.Initialize( document.Definitions.OfType <FragmentDefinitionNode>() .ToDictionary(t => t.Name.Value)); // act operation.Accept( visitor, visitationMap, node => VisitorAction.Continue); // assert var variables = operation.VariableDefinitions.ToList(); variables.AddRange(visitor.VariableDeclarations); operation = operation.WithVariableDefinitions(variables); var definitions = new List <IDefinitionNode>(); definitions.Add(operation); definitions.AddRange( document.Definitions.OfType <FragmentDefinitionNode>()); QuerySyntaxSerializer.Serialize( new DocumentNode( definitions)).MatchSnapshot(); }
private async Task DispatchRequestsAsync( IList <BufferedRequest> requests, DocumentNode mergedQuery, IReadOnlyDictionary <string, object> variableValues, CancellationToken cancellationToken) { int index = 0; try { var mergedRequest = new QueryRequest( QuerySyntaxSerializer.Serialize(mergedQuery, false)) { VariableValues = variableValues, Services = _services }; var mergedResult = (IReadOnlyQueryResult)await _queryExecutor .ExecuteAsync(mergedRequest, cancellationToken) .ConfigureAwait(false); var handledErrors = new HashSet <IError>(); for (int i = 0; i < requests.Count; i++) { index = i; IQueryResult result = ExtractResult( requests[i].Aliases, mergedResult, handledErrors); if (handledErrors.Count < mergedResult.Errors.Count && i == requests.Count - 1) { foreach (IError error in mergedResult.Errors .Except(handledErrors)) { result.Errors.Add(error); } } requests[i].Promise.SetResult(result); } } catch (Exception ex) { for (int i = index; i < requests.Count; i++) { requests[i].Promise.SetException(ex); } } }
public async Task WriteToAsync( Stream output, CancellationToken cancellationToken) { using (var sw = new StreamWriter(output)) { await Task.Run(() => QuerySyntaxSerializer.Serialize(Document, sw, false)) .ConfigureAwait(false); await sw.FlushAsync().ConfigureAwait(false); } }
public override object ParseLiteral(IValueNode literal) { if (literal == null) { throw new ArgumentNullException(nameof(literal)); } if (literal is NullValueNode) { return(null); } if (literal is StringValueNode stringLiteral) { var reader = new GeoJsonReader(); var geoObject = reader.Read <Geometry>(stringLiteral.Value); if (geoObject == null) { var error = new ErrorBuilder() .SetCode("INVALID_ARG") .SetMessage($"Couldn't convert {literal} to GeoJson") .AddLocation(literal.Location.Line, literal.Location.Column) .Build(); throw new QueryException(error); } return(geoObject); } if (literal is ObjectValueNode obj) { var objStr = QuerySyntaxSerializer.Serialize(literal); var reader = new GeoJsonReader(); var geoObject = reader.Read <Geometry>(objStr); if (geoObject == null) { var error = new ErrorBuilder() .SetCode("INVALID_ARG") .SetMessage($"Couldn't convert {literal} to GeoJson") .AddLocation(literal.Location.Line, literal.Location.Column) .Build(); throw new QueryException(error); } return(geoObject); } throw new ArgumentException("The point type can only parse object literals", nameof(literal)); }
public void IntrospectionWithoutDirectiveIsRepeatableField() { // arrange var features = new SchemaFeatures { HasRepeatableDirectives = false }; // act DocumentNode document = IntrospectionClient.CreateIntrospectionQuery(features); // assert QuerySyntaxSerializer.Serialize(document).MatchSnapshot(); }
public void IntrospectionWithSubscription() { // arrange var features = new SchemaFeatures { HasSubscriptionSupport = true }; // act DocumentNode document = IntrospectionClient.CreateIntrospectionQuery(features); // assert QuerySyntaxSerializer.Serialize(document).MatchSnapshot(); }
public void IntrospectionWithDirectiveLocationField() { // arrange var features = new SchemaFeatures { HasDirectiveLocations = true }; // act DocumentNode document = IntrospectionClient.CreateIntrospectionQuery(features); // assert QuerySyntaxSerializer.Serialize(document).MatchSnapshot(); }
public void ExtractField_WithCustomRewriters() { // arrange ISchema schema = Schema.Create( FileResource.Open("Stitching.graphql"), c => { c.RegisterType <DateTimeType>(); c.RegisterDirective <DelegateDirectiveType>(); c.RegisterDirective <ComputedDirectiveType>(); c.Use(next => context => Task.CompletedTask); }); DocumentNode query = Utf8GraphQLParser.Parse( FileResource.Open("StitchingQuery.graphql")); OperationDefinitionNode operation = query.Definitions .OfType <OperationDefinitionNode>().Single(); FieldNode selection = operation .SelectionSet.Selections .OfType <FieldNode>().First(); var rewriters = new List <IQueryDelegationRewriter> { new DummyRewriter() }; // act var rewriter = new ExtractFieldQuerySyntaxRewriter( schema, rewriters); ExtractedField extractedField = rewriter.ExtractField( "customer", query, operation, selection, schema.GetType <ObjectType>("Query")); // assert DocumentNode document = RemoteQueryBuilder.New() .SetRequestField(extractedField.Field) .AddFragmentDefinitions(extractedField.Fragments) .AddVariables(extractedField.Variables) .Build(); QuerySyntaxSerializer.Serialize(document) .MatchSnapshot(); }
private static async Task <DocumentNode> ExecuteIntrospectionAsync( HttpClient httpClient, HttpQueryClient queryClient, SchemaFeatures features) { DocumentNode query = CreateIntrospectionQuery(features); var request = new HttpQueryRequest { Query = QuerySyntaxSerializer.Serialize(query) }; string json = await queryClient.FetchStringAsync( request, httpClient) .ConfigureAwait(false); return(IntrospectionDeserializer.Deserialize(json)); }
public void SimpleShortHandQuery() { // arrange string query_a = "{ a { b } }"; string query_b = "{ c { d } }"; string query_c = "{ a { c } }"; // act var rewriter = new MergeQueryRewriter(Array.Empty <string>()); rewriter.AddQuery(Parser.Default.Parse(query_a), "_a", false); rewriter.AddQuery(Parser.Default.Parse(query_b), "_b", false); rewriter.AddQuery(Parser.Default.Parse(query_c), "_c", false); DocumentNode document = rewriter.Merge(); // assert QuerySyntaxSerializer.Serialize(document).MatchSnapshot(); }
public void QueryWithPrivateVariables() { // arrange DocumentNode query_a = Parser.Default.Parse( FileResource.Open("StitchingQueryWithUnion.graphql")); DocumentNode query_b = Parser.Default.Parse( FileResource.Open("StitchingQueryWithVariables.graphql")); // act var rewriter = new MergeQueryRewriter(Array.Empty <string>()); rewriter.AddQuery(query_a, "_a", false); rewriter.AddQuery(query_b, "_b", false); DocumentNode document = rewriter.Merge(); // assert QuerySyntaxSerializer.Serialize(document).MatchSnapshot(); }
protected override void Configure(IObjectTypeDescriptor <IInputField> descriptor) { descriptor .Name(Names.__InputValue) .Description(TypeResources.InputValue_Description) // Introspection types must always be bound explicitly so that we // do not get any interference with conventions. .BindFields(BindingBehavior.Explicit); descriptor .Field(t => t.Name) .Name(Names.Name) .Type <NonNullType <StringType> >(); descriptor .Field(t => t.Description) .Name(Names.Description); descriptor .Field(t => t.Type) .Name(Names.Type) .Type <NonNullType <__Type> >(); descriptor .Field(t => t.DefaultValue) .Name(Names.DefaultValue) .Description(TypeResources.InputValue_DefaultValue) .Type <StringType>() .Resolver(c => { IInputField field = c.Parent <IInputField>(); if (field.DefaultValue.IsNull()) { return(null); } if (field.DefaultValue is not null) { return(QuerySyntaxSerializer.Serialize(field.DefaultValue)); } return(null); }); }
private static void SerializeArguments( StringBuilder serialized, IReadOnlyList <ArgumentNode> arguments) { for (int i = 0; i < arguments.Count; i++) { if (i != 0) { serialized.Append(','); serialized.Append(' '); } ArgumentNode argument = arguments[i]; serialized.Append(argument.Name.Value); serialized.Append(':'); serialized.Append(' '); serialized.Append(QuerySyntaxSerializer.Serialize(argument.Value)); } }
public void QueryWithGlobalVariables() { // arrange DocumentNode query_a = Parser.Default.Parse( FileResource.Open("MergeQueryWithVariable.graphql")); DocumentNode query_b = Parser.Default.Parse( FileResource.Open("MergeQueryWithVariable.graphql")); // act var rewriter = new MergeQueryRewriter( new HashSet <string>(new[] { "global" })); rewriter.AddQuery(query_a, "_a", true); rewriter.AddQuery(query_b, "_b", true); DocumentNode document = rewriter.Merge(); // assert QuerySyntaxSerializer.Serialize(document).MatchSnapshot(); }
public void BuildRemoteQueryCanOverrideOperationName() { // arrange IImmutableStack<SelectionPathComponent> path = SelectionPathParser.Parse("a.b.c.d(a: $fields:bar)"); DocumentNode initialQuery = Utf8GraphQLParser.Parse( @"{ foo { bar { baz { ... on Baz { qux } } } } } "); FieldNode field = initialQuery.Definitions .OfType<OperationDefinitionNode>().Single() .SelectionSet.Selections .OfType<FieldNode>().Single() .SelectionSet.Selections .OfType<FieldNode>().Single(); // act DocumentNode newQuery = RemoteQueryBuilder.New() .SetOperation(new NameNode( nameof(BuildRemoteQueryCanOverrideOperationName)), OperationType.Query) .SetSelectionPath(path) .SetRequestField(field) .AddVariable("__fields_bar", new NamedTypeNode(null, new NameNode("String"))) .Build("abc", new Dictionary<(NameString Type, NameString Schema), NameString>()); // assert QuerySyntaxSerializer.Serialize(newQuery).MatchSnapshot(); }
protected override void Configure( IObjectTypeDescriptor <InputField> descriptor) { descriptor.Name("__InputValue"); descriptor.Description( "Arguments provided to Fields or Directives and the input " + "fields of an InputObject are represented as Input Values " + "which describe their type and optionally a default value."); descriptor.BindFields(BindingBehavior.Explicit); descriptor.Field(t => t.Name) .Type <NonNullType <StringType> >(); descriptor.Field(t => t.Description); descriptor.Field(t => t.Type) .Type <NonNullType <__Type> >(); descriptor.Field(t => t.DefaultValue) .Description( "A GraphQL-formatted string representing the default " + "value for this input value.") .Type <StringType>() .Resolver(c => { InputField field = c.Parent <InputField>(); if (field.DefaultValue.IsNull()) { return(null); } if (field.DefaultValue != null) { return(QuerySyntaxSerializer .Serialize(field.DefaultValue)); } return(null); }); }
private static async Task <DocumentNode> ExecuteIntrospectionAsync( HttpClient httpClient, HttpQueryClient queryClient, SchemaFeatures features) { DocumentNode query = CreateIntrospectionQuery(features); var request = new HttpQueryRequest { Query = QuerySyntaxSerializer.Serialize(query), OperationName = "introspection_phase_2" }; (string json, HttpResponseMessage _)response = await queryClient.FetchStringAsync( request, httpClient) .ConfigureAwait(false); return(IntrospectionDeserializer.Deserialize(response.json)); }
public void QueryDocument_WriteTo() { // arrange DocumentNode document = Utf8GraphQLParser.Parse("{ a }"); var query = new QueryDocument(document); byte[] buffer; // act using (var stream = new MemoryStream()) { query.WriteTo(stream); buffer = stream.ToArray(); } // assert QuerySyntaxSerializer.Serialize( Utf8GraphQLParser.Parse(buffer)) .ToString().MatchSnapshot(); }
private static Stream CreateMessageStream( this OperationMessage message, bool largeMessage) { if (message is DataStartMessage dataStart) { string query = QuerySyntaxSerializer.Serialize( dataStart.Payload.Query); var payload = new Dictionary <string, object> { { "query", query }, }; if (dataStart.Payload.QueryName != null) { payload["namedQuery"] = dataStart.Payload.QueryName; } if (dataStart.Payload.OperationName != null) { payload["operationName"] = dataStart.Payload.OperationName; } if (dataStart.Payload.Variables != null) { payload["variables"] = dataStart.Payload.Variables; } message = new HelperOperationMessage( dataStart.Type, dataStart.Id, payload); } string json = JsonConvert.SerializeObject(message, _settings); if (largeMessage) { json += new string(' ', 1024 * 16); } return(new MemoryStream(Encoding.UTF8.GetBytes(json))); }
public void ExtractField(string schemaFile, string queryFile) { // arrange ISchema schema = Schema.Create( FileResource.Open(schemaFile), c => { c.RegisterType <DateTimeType>(); c.RegisterDirective <DelegateDirectiveType>(); c.RegisterDirective <ComputedDirectiveType>(); c.Use(next => context => Task.CompletedTask); }); DocumentNode query = Parser.Default.Parse( FileResource.Open(queryFile)); OperationDefinitionNode operation = query.Definitions .OfType <OperationDefinitionNode>().Single(); FieldNode selection = operation .SelectionSet.Selections .OfType <FieldNode>().First(); // act var rewriter = new ExtractFieldQuerySyntaxRewriter(schema, Array.Empty <IQueryDelegationRewriter>()); ExtractedField extractedField = rewriter.ExtractField( "customer", query, operation, selection, schema.GetType <ObjectType>("Query")); // assert DocumentNode document = RemoteQueryBuilder.New() .SetRequestField(extractedField.Field) .AddFragmentDefinitions(extractedField.Fragments) .AddVariables(extractedField.Variables) .Build(); QuerySyntaxSerializer.Serialize(document) .MatchSnapshot(new SnapshotNameExtension( schemaFile, queryFile)); }
public void BuildRemoteQuery() { // arrange IImmutableStack <SelectionPathComponent> path = SelectionPathParser.Parse("a.b.c.d(a: $fields:bar)"); DocumentNode initialQuery = Parser.Default.Parse( @"{ foo { bar { baz { ... on Baz { qux } } } } } "); FieldNode field = initialQuery.Definitions .OfType <OperationDefinitionNode>().Single() .SelectionSet.Selections .OfType <FieldNode>().Single() .SelectionSet.Selections .OfType <FieldNode>().Single(); // act DocumentNode newQuery = RemoteQueryBuilder.New() .SetOperation(OperationType.Query) .SetSelectionPath(path) .SetRequestField(field) .AddVariable("fields_bar", new NamedTypeNode(null, new NameNode("String"))) .Build(); // assert QuerySyntaxSerializer.Serialize(newQuery).MatchSnapshot(); }