Exemple #1
0
        public async Task GetItems_DescSorting_AllItems_Are_Returned_DescSortedOnNullableObject()
        {
            // arrange
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(sp =>
            {
                IMongoDatabase database = _mongoResource.CreateDatabase();
                IMongoCollection <Parent> collection = database.GetCollection <Parent>("col");
                collection.InsertMany(new[]
                {
                    new Parent {
                        Model = new Model {
                            Foo = "def", Bar = 1, Baz = true, BazNullable = 1
                        }
                    },
                    new Parent {
                        Model = new Model {
                            Foo = "abc", Bar = 2, Baz = false, BazNullable = 2
                        }
                    },
                    new Parent {
                    }
                });
                return(collection);
            });

            ISchema schema = SchemaBuilder.New()
                             .AddQueryType <QueryType>()
                             .AddServices(serviceCollection.BuildServiceProvider())
                             .Create();

            IQueryExecutor executor = schema.MakeExecutable();

            IReadOnlyQueryRequest request = QueryRequestBuilder.New()
                                            .SetQuery(
                "{ items(order_by: { model: { bazNullable: DESC } }) { model { bazNullable } } }")
                                            .Create();

            // act
            IExecutionResult result = await executor.ExecuteAsync(request);

            // assert
            Assert.Null(result.Errors);
            result.MatchSnapshot();
        }
Exemple #2
0
        private async Task <CustomEntityRenderDetails> GetCustomEntityModel(PageActionRoutingState state)
        {
            var query = new GetCustomEntityRenderDetailsByIdQuery();

            query.CustomEntityId = state.PageRoutingInfo.CustomEntityRoute.CustomEntityId;
            query.PageTemplateId = state.PageData.Template.PageTemplateId;

            // If we're editing the custom entity, we need to get the version we're editing, otherwise just get latest
            if (state.InputParameters.IsEditingCustomEntity)
            {
                query.WorkFlowStatus        = state.VisualEditorMode.ToWorkFlowStatusQuery();
                query.CustomEntityVersionId = state.InputParameters.VersionId;
            }
            var model = await _queryExecutor.ExecuteAsync(query);

            return(model);
        }
        public async Task ToJson_NoIndentation()
        {
            // arrange
            IQueryExecutor executor = SchemaBuilder.New()
                                      .AddQueryType(d => d
                                                    .Name("Query")
                                                    .Field("foo")
                                                    .Resolver("bar"))
                                      .Create()
                                      .MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync("{ foo }");

            // assert
            result.ToJson(false).MatchSnapshot();
        }
Exemple #4
0
        public async Task CustomDirectiveIsPassedOn()
        {
            // arrange
            IHttpClientFactory clientFactory = CreateRemoteSchemas();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(clientFactory);
            serviceCollection.AddStitchedSchema(builder =>
                                                builder.AddSchemaFromHttp("contract")
                                                .AddSchemaFromHttp("customer")
                                                .AddSchemaConfiguration(c =>
            {
                c.RegisterExtendedScalarTypes();
            })
                                                .AddSchemaConfiguration(c =>
                                                                        c.RegisterType <PaginationAmountType>()));

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor = services
                                      .GetRequiredService <IQueryExecutor>();
            IExecutionResult result = null;

            // act
            using (IServiceScope scope = services.CreateScope())
            {
                IReadOnlyQueryRequest request =
                    QueryRequestBuilder.New()
                    .SetQuery(@"
                            query a($d: DateTime!) {
                                a: extendedScalar(d: ""2018-01-01T01:00:00.000Z"")
                                b: extendedScalar(d: $d)
                                    @custom(d: ""2020-09-01T01:00:00.000Z"")
                            }")
                    .SetVariableValue("d", "2019-01-01T01:00:00.000Z")
                    .SetServices(scope.ServiceProvider)
                    .Create();

                result = await executor.ExecuteAsync(request);
            }

            // assert
            Snapshot.Match(result);
        }
Exemple #5
0
        public async Task ReplaceField()
        {
            // arrange
            IHttpClientFactory clientFactory = CreateRemoteSchemas();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(clientFactory);
            serviceCollection.AddStitchedSchema(builder =>
                                                builder.AddSchemaFromHttp("contract")
                                                .AddSchemaFromHttp("customer")
                                                .IgnoreField("customer",
                                                             new FieldReference("Customer", "name"))
                                                .RenameField("customer",
                                                             new FieldReference("Customer", "street"), "name")
                                                .AddSchemaConfiguration(c =>
                                                                        c.RegisterType <PaginationAmountType>()));

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor = services
                                      .GetRequiredService <IQueryExecutor>();
            IExecutionResult result = null;

            // act
            using (IServiceScope scope = services.CreateScope())
            {
                IReadOnlyQueryRequest request =
                    QueryRequestBuilder.New()
                    .SetQuery(@"
                            query a($id: ID!) {
                                a: customer(id: $id) {
                                    name
                                }
                            }")
                    .SetVariableValue("id", "Q3VzdG9tZXIKZDE=")
                    .SetServices(scope.ServiceProvider)
                    .Create();

                result = await executor.ExecuteAsync(request);
            }

            // assert
            Snapshot.Match(result);
        }
Exemple #6
0
        public async Task DelegateWithGuidFieldArgument()
        {
            // arrange
            IHttpClientFactory clientFactory = CreateRemoteSchemas();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(clientFactory);
            serviceCollection.AddStitchedSchema(builder =>
                                                builder.AddSchemaFromHttp("contract")
                                                .AddSchemaFromHttp("customer")
                                                .AddExtensionsFromString(
                                                    FileResource.Open("StitchingExtensions.graphql"))
                                                .AddSchemaConfiguration(c =>
            {
                c.RegisterExtendedScalarTypes();
                c.RegisterType <PaginationAmountType>();
            }));

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor = services
                                      .GetRequiredService <IQueryExecutor>();
            IExecutionResult result = null;

            // act
            using (IServiceScope scope = services.CreateScope())
            {
                IReadOnlyQueryRequest request =
                    QueryRequestBuilder.New()
                    .SetQuery(@"
                        {
                            customer(id: ""Q3VzdG9tZXIKZDE="") {
                                guid
                            }
                        }")
                    .SetServices(scope.ServiceProvider)
                    .Create();

                result = await executor.ExecuteAsync(request);
            }

            // assert
            Snapshot.Match(result);
        }
        protected override async Task ExecuteRequestAsync(
            HttpContext context,
            IServiceProvider services)
        {
            var builder = QueryRequestBuilder.New();

#if ASPNETCLASSIC
            IReadableStringCollection requestQuery = context.Request.Query;
#else
            IQueryCollection requestQuery = context.Request.Query;
#endif

            builder
            .SetQuery(requestQuery[_queryIdentifier])
            .SetQueryName(requestQuery[_namedQueryIdentifier])
            .SetOperation(requestQuery[_operationNameIdentifier]);

            string variables = requestQuery[_variablesIdentifier];
            if (variables != null &&
                variables.Any() &&
                Utf8GraphQLRequestParser.ParseJson(variables)
                is IReadOnlyDictionary <string, object> v)
            {
                builder.SetVariableValues(v);
            }

            IReadOnlyQueryRequest request =
                await BuildRequestAsync(
                    context,
                    services,
                    builder)
                .ConfigureAwait(false);

            IExecutionResult result = await _queryExecutor
                                      .ExecuteAsync(request, context.GetCancellationToken())
                                      .ConfigureAwait(false);

            SetResponseHeaders(context.Response);

            await _resultSerializer.SerializeAsync(
                result,
                context.Response.Body,
                context.GetCancellationToken())
            .ConfigureAwait(false);
        }
Exemple #8
0
        public async Task Scalar_Serializes_And_Deserializes_Correctly(
            string fieldName)
        {
            // arrange
            IHttpClientFactory clientFactory = CreateRemoteSchemas();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(clientFactory);
            serviceCollection.AddStitchedSchema(builder => builder
                                                .AddSchemaFromHttp("contract")
                                                .AddSchemaFromHttp("customer"));

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor = services
                                      .GetRequiredService <IQueryExecutor>();
            IExecutionResult result = null;

            // act
            using (IServiceScope scope = services.CreateScope())
            {
                IReadOnlyQueryRequest request =
                    QueryRequestBuilder.New()
                    .SetQuery($@"
                            query a($contractId: ID!) {{
                                contract(contractId: $contractId) {{
                                    ... on LifeInsuranceContract {{
                                        {fieldName}
                                    }}
                                }}
                            }}")
                    .SetVariableValue(
                        "contractId",
                        "TGlmZUluc3VyYW5jZUNvbnRyYWN0CmQx")
                    .SetServices(scope.ServiceProvider)
                    .Create();

                result = await executor.ExecuteAsync(request);
            }

            // assert
            result.MatchSnapshot(new SnapshotNameExtension(fieldName));
        }
        public async Task AllowInputObjectTypesAsArguments()
        {
            // arrange
            var serviceCollection = new ServiceCollection();

            var connections = new Dictionary <string, HttpClient>();

            serviceCollection.AddSingleton(CreateRemoteSchemas(connections));

            serviceCollection.AddStitchedSchema(builder => builder
                                                .AddSchemaFromHttp("server_1")
                                                .AddExtensionsFromString(
                                                    @"
                    extend type Query {
                        baz(a: Bar): String
                            @delegate(
                                schema: ""server_1""
                                path: ""foo(a:$arguments:a)"")
                    }
                    "));

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor = services
                                      .GetRequiredService <IQueryExecutor>();

            // act
            IExecutionResult result = null;

            using (IServiceScope scope = services.CreateScope())
            {
                IReadOnlyQueryRequest request = QueryRequestBuilder.New()
                                                .SetQuery("{ baz(a: { a: \"String 123\" }) }")
                                                .SetServices(scope.ServiceProvider)
                                                .Create();

                result = await executor.ExecuteAsync(request);
            }

            // assert
            result.MatchSnapshot(new SnapshotNameExtension("result"));
            executor.Schema.ToString().MatchSnapshot(
                new SnapshotNameExtension("schema"));
        }
Exemple #10
0
        public async Task <ICollection <EntityDependencySummary> > ExecuteAsync(GetEntityDependencySummaryByRelatedEntityQuery query, IExecutionContext executionContext)
        {
            // Where there are duplicates, prioritise relationships that cannot be deleted
            var dbDependencyPreResult = await _dbContext
                                        .UnstructuredDataDependencies
                                        .AsNoTracking()
                                        .Where(r => r.RelatedEntityDefinitionCode == query.EntityDefinitionCode && r.RelatedEntityId == query.EntityId)
                                        .ToListAsync();

            // Query is split because EF core cannot translate groupings yet
            var dbDependencyGroups = dbDependencyPreResult
                                     .GroupBy(r => new { r.RootEntityDefinitionCode, r.RootEntityId }, (d, e) => e.OrderByDescending(x => x.RelatedEntityCascadeActionId == (int)RelatedEntityCascadeAction.None).FirstOrDefault())
                                     .GroupBy(r => r.RootEntityDefinitionCode)
                                     .ToList();

            var allRelatedEntities = new List <EntityDependencySummary>();

            foreach (var dbDependencyGroup in dbDependencyGroups)
            {
                var definition = _entityDefinitionRepository.GetByCode(dbDependencyGroup.Key) as IDependableEntityDefinition;
                IQuery <IDictionary <int, RootEntityMicroSummary> > getEntitiesQuery;

                EntityNotFoundException.ThrowIfNull(definition, dbDependencyGroup.Key);
                getEntitiesQuery = definition.CreateGetEntityMicroSummariesByIdRangeQuery(dbDependencyGroup.Select(e => e.RootEntityId));

                var entityMicroSummaries = await _queryExecutor.ExecuteAsync(getEntitiesQuery, executionContext);

                foreach (var entityMicroSummary in entityMicroSummaries.OrderBy(e => e.Value.RootEntityTitle))
                {
                    var dbDependency = dbDependencyGroup.SingleOrDefault(e => e.RootEntityId == entityMicroSummary.Key);

                    var entityDependencySummary = new EntityDependencySummary();
                    entityDependencySummary.Entity = entityMicroSummary.Value;

                    // relations for previous versions can be removed even when they are required.
                    entityDependencySummary.CanDelete =
                        dbDependency.RelatedEntityCascadeActionId != (int)RelatedEntityCascadeAction.None ||
                        entityDependencySummary.Entity.IsPreviousVersion;

                    allRelatedEntities.Add(entityDependencySummary);
                }
            }

            return(allRelatedEntities);
        }
        public async Task ExtendedScalarAsInAndOutputType()
        {
            // arrange
            IHttpClientFactory clientFactory = CreateRemoteSchemas();

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(clientFactory);
            serviceCollection.AddStitchedSchema(builder =>
                                                builder.AddSchemaFromHttp("contract")
                                                .AddSchemaFromHttp("customer")
                                                .AddSchemaConfiguration(c =>
            {
                c.RegisterExtendedScalarTypes();
            })
                                                .AddSchemaConfiguration(c =>
                                                                        c.RegisterType <PaginationAmountType>()));

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor = services
                                      .GetRequiredService <IQueryExecutor>();
            IExecutionResult result = null;

            // act
            using (IServiceScope scope = services.CreateScope())
            {
                var request = new QueryRequest(@"
                query a($d: DateTime!) {
                    a: extendedScalar(d: ""2018-01-01T01:00:00.000Z"")
                    b: extendedScalar(d: $d)
                }");
                request.VariableValues = new Dictionary <string, object>
                {
                    { "d", "2019-01-01T01:00:00.000Z" }
                };
                request.Services = scope.ServiceProvider;

                result = await executor.ExecuteAsync(request);
            }

            // assert
            Snapshot.Match(result);
        }
Exemple #12
0
        public async Task OutputType_ClrValue_CannotBeParsed()
        {
            // arrange
            var schema = Schema.Create(t =>
            {
                t.RegisterQueryType <QueryType>();
            });

            IQueryExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                "{ stringToFoo(name: \"  \") }");

            // assert
            result.MatchSnapshot(options =>
                                 options.IgnoreField("Errors[0].Exception"));
        }
        public static Task <IExecutionResult> ExecuteAsync(
            this IQueryExecutor executor,
            Action <IQueryRequestBuilder> buildRequest)
        {
            if (executor == null)
            {
                throw new ArgumentNullException(nameof(executor));
            }

            if (buildRequest == null)
            {
                throw new ArgumentNullException(nameof(buildRequest));
            }

            return(executor.ExecuteAsync(
                       buildRequest,
                       CancellationToken.None));
        }
Exemple #14
0
        public async Task <CustomEntityDataModelSchema> ExecuteAsync(GetCustomEntityDataModelSchemaDetailsByDefinitionCodeQuery query, IExecutionContext executionContext)
        {
            var definitionQuery = new GetCustomEntityDefinitionSummaryByCodeQuery(query.CustomEntityDefinitionCode);
            var definition      = await _queryExecutor.ExecuteAsync(definitionQuery, executionContext);

            if (definition == null)
            {
                return(null);
            }

            var result = new CustomEntityDataModelSchema();

            result.CustomEntityDefinitionCode = definition.CustomEntityDefinitionCode;

            _dynamicDataModelTypeMapper.Map(result, definition.DataModelType);

            return(result);
        }
        public async Task List_NonNullElementHasError(string fieldType)
        {
            // arrange
            IQueryExecutor executor = CreateExecutor();

            IReadOnlyQueryRequest request =
                QueryRequestBuilder.New()
                .SetQuery($"{{ foo {{ {fieldType} {{ c }} }} }}")
                .AddProperty("b", null)
                .Create();

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                request, CancellationToken.None);

            // assert
            result.MatchSnapshot(SnapshotNameExtension.Create(fieldType));
        }
        public static Task <IExecutionResult> ExecuteAsync(
            this IQueryExecutor executor,
            IReadOnlyQueryRequest request)
        {
            if (executor == null)
            {
                throw new ArgumentNullException(nameof(executor));
            }

            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            return(executor.ExecuteAsync(
                       request,
                       CancellationToken.None));
        }
        public async Task LineString_Execution_With_CRS()
        {
            ISchema schema = SchemaBuilder.New()
                             .BindClrType <Coordinate, GeoJSONPositionScalar>()
                             .AddType <GeoJSONLineStringType>()
                             .AddQueryType(d => d
                                           .Name("Query")
                                           .Field("test")
                                           .Resolver(geom))
                             .Create();

            IQueryExecutor   executor = schema.MakeExecutable();
            IExecutionResult result   = await executor.ExecuteAsync(
                "{ test { crs }}");

            // assert
            result.MatchSnapshot();
        }
Exemple #18
0
        public async Task ExecuteShortHandQueryWithTracing()
        {
            // arrange
            Schema         schema   = CreateSchema();
            IQueryExecutor executor = QueryExecutionBuilder
                                      .BuildDefault(schema, new QueryExecutionOptions
            {
                EnableTracing = true
            });
            var request = new QueryRequest("{ a }");

            // act
            IExecutionResult result = await executor.ExecuteAsync(request);

            // assert
            Assert.NotEmpty(result.Extensions);
            Assert.True(result.Extensions.ContainsKey("tracing"));
        }
        public async Task <PagedQueryResult <PageRenderSummary> > ExecuteAsync(SearchPageRenderSummariesQuery query, IExecutionContext executionContext)
        {
            var dbPagedResult = await CreateQuery(query, executionContext)
                                .ToPagedResultAsync(query);

            var allPageIds    = dbPagedResult.Items.Select(p => p.PageId);
            var allPageRoutes = await _queryExecutor.ExecuteAsync(new GetPageRoutesByIdRangeQuery(allPageIds));

            var results = new List <PageRenderSummary>(dbPagedResult.Items.Count);

            foreach (var dbResult in dbPagedResult.Items)
            {
                var mappedResult = _pageRenderSummaryMapper.Map <PageRenderSummary>(dbResult, allPageRoutes);
                results.Add(mappedResult);
            }

            return(dbPagedResult.ChangeType(results));
        }
        public async Task <ICollection <CustomEntityRoute> > ExecuteAsync(GetCustomEntityRoutesByDefinitionCodeQuery query, IExecutionContext executionContext)
        {
            return(await _customEntityCache.GetOrAddAsync(query.CustomEntityDefinitionCode, async() =>
            {
                var dbRoutes = await _dbContext
                               .CustomEntities
                               .Include(c => c.CustomEntityVersions)
                               .Include(c => c.Locale)
                               .AsNoTracking()
                               .Where(e => e.CustomEntityDefinitionCode == query.CustomEntityDefinitionCode && (e.LocaleId == null || e.Locale.IsActive))
                               .ToListAsync();

                var allLocales = await _queryExecutor.ExecuteAsync(new GetAllActiveLocalesQuery(), executionContext);
                var localesLookup = allLocales.ToDictionary(l => l.LocaleId);

                return await MapRoutesAsync(query, dbRoutes, localesLookup);;
            }));
        }
Exemple #21
0
        public async Task EnsureQueryResultContainsExtensionTracing()
        {
            // arrange
            Schema         schema   = CreateSchema();
            IQueryExecutor executor = QueryExecutionBuilder
                                      .BuildDefault(schema, new QueryExecutionOptions
            {
                TracingPreference = TracingPreference.Always
            });
            var request = new QueryRequest("{ a }");

            // act
            IExecutionResult result = await executor.ExecuteAsync(request);

            // assert
            Assert.NotEmpty(result.Extensions);
            Assert.True(result.Extensions.ContainsKey("tracing"));
        }
        public async Task ExecuteQueryThatReturnsId_IdShouldBeOpaque()
        {
            // arrange
            var schema = Schema.Create(t =>
            {
                t.RegisterQueryType <SomeQuery>();
                t.UseGlobalObjectIdentifier();
            });

            IQueryExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result =
                await executor.ExecuteAsync("{ id string }");

            // assert
            result.MatchSnapshot();
        }
        public async Task NodeResolver_ResolveNode()
        {
            // arrange
            ISchema schema = SchemaBuilder.New()
                             .EnableRelaySupport()
                             .AddType <EntityType>()
                             .AddQueryType <Query>()
                             .Create();

            IQueryExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync("{ node(id: \"RW50aXR5LXhmb28=\")  { ... on Entity { id name } } }");


            // assert
            result.MatchSnapshot();
        }
Exemple #24
0
        public async Task SchemaBuilder_BindType()
        {
            // arrange
            string sourceText = "type Query { hello: String }";

            // act
            ISchema schema = SchemaBuilder.New()
                             .AddDocumentFromString(sourceText)
                             .BindComplexType <Query>()
                             .Create();

            // assert
            IQueryExecutor   executor = schema.MakeExecutable();
            IExecutionResult result   =
                await executor.ExecuteAsync("{ hello }");

            result.MatchSnapshot();
        }
Exemple #25
0
        public async Task ExecuteShortHandQuery()
        {
            // arrange
            Schema         schema   = CreateSchema();
            IQueryExecutor executor = QueryExecutionBuilder
                                      .BuildDefault(schema);
            var request =
                QueryRequestBuilder.New()
                .SetQuery("{ a }")
                .Create();

            // act
            IExecutionResult result = await executor.ExecuteAsync(request);

            // assert
            Assert.Empty(result.Errors);
            result.MatchSnapshot();
        }
Exemple #26
0
        public async Task ExecuteQueryWith2OperationsAndInvalidOpName_Error()
        {
            // arrange
            Schema         schema   = CreateSchema();
            IQueryExecutor executor = schema.MakeExecutable();
            var            request  =
                QueryRequestBuilder.New()
                .SetQuery("query a { a } query b { a }")
                .SetOperation("c")
                .Create();

            // act
            IExecutionResult result = await executor.ExecuteAsync(request);

            // assert
            Assert.NotNull(result.Errors);
            result.MatchSnapshot();
        }
        public async Task Polygon_Execution_With_Fragments()
        {
            ISchema schema = SchemaBuilder.New()
                             .AddSpatialTypes()
                             .AddQueryType(d => d
                                           .Name("Query")
                                           .Field("test")
                                           .Type <GeoJSONPolygonType>()
                                           .Resolver(geom))
                             .Create();
            IQueryExecutor executor = schema.MakeExecutable();
            // act
            IExecutionResult result = await executor.ExecuteAsync(
                "{ test { ... on Polygon { type coordinates bbox crs }}}");

            // assert
            result.MatchSnapshot();
        }
        public async Task TestTimeSeriesPeriode()
        {
            IServiceProvider serviceProvider =
                new ServiceCollection()
                .AddSingleton <ITimeSeriesRepository, TimeSeriesRepository>()
                .AddSingleton <IDatabaseConfig>(sp =>
                                                new DatabaseConfig()
            {
                DatabaseConnectionString = dbConnectionString
            }
                                                )
                .BuildServiceProvider();

            IQueryExecutor executor = Schema.Create(c =>
            {
                c.RegisterQueryType(new ObjectType <TimeSeriesQuery>(d => d.Name("Query")));
                c.RegisterType <GenericObject>();
            })
                                      .MakeExecutable();

            var input = new TimeSeriesPeriodeInput()
            {
                TableName = "airsaturation_percent_",
                SensorId  = 2
            };

            IReadOnlyQueryRequest request =
                QueryRequestBuilder.New()
                .SetQuery(@"query timeSeriesPeriode($input: TimeSeriesPeriodeInput){
                              timeSeriesPeriode(input: $input) {
                                from,
                                to
                              }
                            }")
                .SetServices(serviceProvider)
                .AddVariableValue("input", input)
                .Create();

            // act
            IExecutionResult result = await executor.ExecuteAsync(request);

            //Snapshot.Match(result);
            result.MatchSnapshot();
        }
        public async Task PersistedQueries_PersistedQuery_IsExecuted()
        {
            // arrange
            var serviceCollection = new ServiceCollection();

            // configure presistence
            serviceCollection.AddGraphQLSchema(b => b
                                               .AddDocumentFromString("type Query { foo: String }")
                                               .AddResolver("Query", "foo", "bar"));
            serviceCollection.AddQueryExecutor(b => b
                                               .AddSha256DocumentHashProvider()
                                               .UsePersistedQueryPipeline());

            // add in-memory query storage
            serviceCollection.AddSingleton <InMemoryQueryStorage>();
            serviceCollection.AddSingleton <IReadStoredQueries>(sp =>
                                                                sp.GetRequiredService <InMemoryQueryStorage>());
            serviceCollection.AddSingleton <IWriteStoredQueries>(sp =>
                                                                 sp.GetRequiredService <InMemoryQueryStorage>());

            IServiceProvider services =
                serviceCollection.BuildServiceProvider();

            IQueryExecutor executor =
                services.GetRequiredService <IQueryExecutor>();

            var hashProvider =
                services.GetRequiredService <IDocumentHashProvider>();
            var storage = services.GetRequiredService <InMemoryQueryStorage>();

            var    query = new QuerySourceText("{ foo }");
            string hash  = hashProvider.ComputeHash(query.AsSpan());
            await storage.WriteQueryAsync(hash, query);

            // act
            IExecutionResult result = await executor.ExecuteAsync(
                QueryRequestBuilder.New()
                .SetQueryName(hash)
                .Create());

            // assert
            Assert.True(storage.ReadWithSuccess);
            result.ToJson().MatchSnapshot();
        }
Exemple #30
0
        public async Task Output_Return_String()
        {
            // arrange
            ISchema schema = SchemaBuilder.New()
                             .AddQueryType(d => d
                                           .Name("Query")
                                           .Field("foo")
                                           .Type <AnyType>()
                                           .Resolver(ctx => "abc"))
                             .Create();

            IQueryExecutor executor = schema.MakeExecutable();

            // act
            IExecutionResult result = await executor.ExecuteAsync("{ foo }");

            // assert
            result.ToJson().MatchSnapshot();
        }