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(); }
public static HttpQueryRequest CreateIntrospectionQuery(ISchemaFeatures features) { DocumentNode document = CreateIntrospectionQueryDocument(features); string sourceText = QuerySyntaxSerializer.Serialize(document, false); return(new HttpQueryRequest(sourceText, "introspection_phase_2")); }
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(); } }
private static string SerializeQuery(DocumentNode query) { var content = new StringBuilder(); var documentWriter = new DocumentWriter(new StringWriter(content)); var serializer = new QuerySyntaxSerializer(); serializer.Visit(query, documentWriter); return(content.ToString()); }
public void QueryDocument_ToSource() { // arrange // act var query = new QuerySourceText("{ a }"); // assert QuerySyntaxSerializer.Serialize( Utf8GraphQLParser.Parse(query.ToSpan())) .ToString().MatchSnapshot(); }
public ReadOnlySpan <byte> ToSource() { using (var stream = new MemoryStream()) { using (var sw = new StreamWriter(stream)) { QuerySyntaxSerializer.Serialize(Document, sw, false); } return(stream.ToArray()); } }
private async Task <IQueryDescriptor> LoadAsync( string name, string fileName, DocumentNode document) { OperationDefinitionNode operation = document.Definitions.OfType <OperationDefinitionNode>() .FirstOrDefault(t => t.Name is null); if (operation != null) { throw new GeneratorException(HCErrorBuilder.New() .SetMessage("All operations have to have a name in order " + "to work with Strawberry Shake. Check the specified " + "operation and give it a name, then retry generating " + "the client.") .SetCode("OPERATION_NO_NAME") .AddLocation(operation) .SetExtension("fileName", fileName) .Build()); } DocumentNode rewritten = AddTypeNameQueryRewriter.Rewrite(document); byte[] rewrittenBuffer; var serializer = new QuerySyntaxSerializer(false); using (var stream = new MemoryStream()) { using (var sw = new StreamWriter(stream)) { using (var writer = new DocumentWriter(sw)) { serializer.Visit(rewritten, writer); } } await stream.FlushAsync().ConfigureAwait(false); rewrittenBuffer = stream.ToArray(); } string hash = _hashProvider.ComputeHash(rewrittenBuffer); var descriptor = new QueryDescriptor( name, _namespace, _hashProvider.Name, hash, rewrittenBuffer, document); _descriptors.Add(descriptor); return(descriptor); }
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); } } }
private static string SerializeQuery(DocumentNode query) { var queryText = new StringBuilder(); using (var stringWriter = new StringWriter(queryText)) { var serializer = new QuerySyntaxSerializer(); serializer.Visit(query, new DocumentWriter(stringWriter)); } return(queryText.ToString()); }
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 IntrospectionWithDirectiveLocationField() { // arrange var features = new SchemaFeatures { HasDirectiveLocations = true }; // 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 IntrospectionWithoutDirectiveIsRepeatableField() { // arrange var features = new SchemaFeatures { HasRepeatableDirectives = false }; // 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 string SerializeArguments( IEnumerable <ArgumentNode> arguments) { var serializer = new QuerySyntaxSerializer(); var sb = new StringBuilder(); using (var stringWriter = new StringWriter(sb)) { var documentWriter = new DocumentWriter(stringWriter); return(string.Join(", ", arguments.Select(t => { sb.Clear(); serializer.Visit(t.Value, documentWriter); return t.Name.Value + " = " + sb; }))); } }
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(); }
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(); }
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)); }
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); }); }
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(); }
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)); } }
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); }); }
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(); }
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(); }