Esempio n. 1
0
        public Client(HttpClient httpClient)
        {
            var options = new GraphQLHttpClientOptions
            {
                EndPoint = new Uri("https://graphql.anilist.co")
            };

            _graphQlClient = new GraphQLHttpClient(options, new SystemTextJsonSerializer(), httpClient);
        }
Esempio n. 2
0
        public async Task ExampleGraphQL()
        {
            // TODO: Use dependency injection (services.AddGraphQLClient()) (IServiceCollection)
            var client = GraphQLHttpClient.Default();

            var response = await client.Query <Query>("https://mpjk0plp9.lp.gql.zone/graphql");

            Assert.Equal("R2-D2", response.Hero.Name);
        }
        public GraphQLHttpWebSocket(Uri webSocketUri, GraphQLHttpClient client)
        {
            this.webSocketUri = webSocketUri;
            this.client       = client;
            buffer            = new ArraySegment <byte>(new byte[8192]);
            ResponseStream    = _createResponseStream();

            requestSubscription = requestSubject.Select(request => Observable.FromAsync(() => _sendWebSocketRequest(request))).Concat().Subscribe();
        }
Esempio n. 4
0
 public OpenWeatherClient(OpenWeatherConfiguration openWeatherConfiguration)
 {
     weatherLocationsSemaphore = new SemaphoreSlim(1);
     graphQLHttpClient         = new GraphQLHttpClient(
         new GraphQLHttpClientOptions {
         EndPoint = new Uri(openWeatherConfiguration.GraphQLApiUrl)
     });
     cancellationTokenSource = new CancellationTokenSource();
 }
Esempio n. 5
0
        public async Task Test_Recieve_Multiple_Messages()
        {
            // Arrange
            var tokenSource = new CancellationTokenSource();

            var client        = _factory.CreateClient();
            var graphQLClient = GraphQLHttpClient.Default(client);

            // Create websocket GraphQL client
            var wsClient = _factory.Server.CreateWebSocketClient();

            wsClient.ConfigureRequest = request => request.Headers.Add("Sec-WebSocket-Protocol", "graphql-ws");

            var wsUri = new UriBuilder(_factory.Server.BaseAddress)
            {
                Scheme = "wss",
                Path   = "graphql"
            }.Uri;

            var websocket = await wsClient.ConnectAsync(wsUri, tokenSource.Token);

            var graphQLSubscriptionClient = new GraphQLSubscriptionClient(websocket, tokenSource.Token, new GraphQLFieldBuilder(), new GraphQLQueryGeneratorFromFields(), new GraphQLDeserilization());
            await graphQLSubscriptionClient.Initilize();

            // Act
            // Registrer operation
            var operation = await graphQLSubscriptionClient.ExecuteOperation <MessageAddedSubscription>();

            List <GraphQLDataResult <MessageAddedSubscription> > recievedData = new List <GraphQLDataResult <MessageAddedSubscription> >();

            operation.DataRecieved += (sender, e) =>
            {
                recievedData.Add(e.ReceivedData);
            };
            await Task.Delay(TimeSpan.FromSeconds(1));

            // Send 2 messages
            await graphQLClient.CreateMutation <SendMessageMutation>("http://localhost/graphql", arguments : new GraphQLQueryArgument("message", new MessageInputType
            {
                content = "Message 1",
                fromId  = "SAHB",
                sentAt  = DateTime.Now.AddDays(-1)
            })).Execute();

            await graphQLClient.CreateMutation <SendMessageMutation>("http://localhost/graphql", arguments : new GraphQLQueryArgument("message", new MessageInputType
            {
                content = "Message 1",
                fromId  = "SAHB",
                sentAt  = DateTime.Now.AddDays(-1)
            })).Execute();

            await Task.Delay(TimeSpan.FromSeconds(2));

            // Assert
            Assert.Equal(2, recievedData.Count);
        }
Esempio n. 6
0
        public PolicyExampleGraphQLClient(HttpClient httpClient, string?endpoint = null)
        {
            var options = new GraphQLHttpClientOptions {
                EndPoint = new Uri(endpoint ?? "https://localhost:5001/graphql")
            };

            Client = new GraphQLHttpClient(options,
                                           new NewtonsoftJsonSerializer(),
                                           httpClient);
        }
Esempio n. 7
0
        public AppSyncService()
        {
            var options = new GraphQLHttpClientOptions
            {
                EndPoint = new Uri(ApiKey.AppSyncApiUrl),
            };

            this.GraphQLHttpClient = new GraphQLHttpClient(options, new NewtonsoftJsonSerializer());
            this.GraphQLHttpClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", ApiKey.AppSyncApiKey);
        }
        public void Initialize()
        {
            var options = new GraphQLHttpClientOptions()
            {
                EndPoint           = new Uri("http://www.example.com/graph/api/graphql"),
                HttpMessageHandler = new MockHttpHandler()
            };

            _client = new GraphQLHttpClient(options, new NewtonsoftJsonSerializer());
        }
        public void Initialize()
        {
            GraphQLHttpClientOptions options = new GraphQLHttpClientOptions()
            {
                EndPoint           = new System.Uri("http://www.example.com/graph/api/graphql"),
                HttpMessageHandler = new MockHttpHandler()
            };

            _client = new GraphQLHttpClient(options);
        }
        public async Task <IViewComponentResult> InvokeAsync()
        {
            using var graphQLClient = new GraphQLHttpClient(Baseurl, new NewtonsoftJsonSerializer());

            var graphQLResponse = await graphQLClient.SendQueryAsync <COPC_Wiki.Models.WikiPages>(query.getWikiPages());

            //Console.WriteLine("raw response:");
            //Console.WriteLine(JsonSerializer.Serialize(graphQLResponse, new JsonSerializerOptions { WriteIndented = true }));
            return(View("Navigation", graphQLResponse.Data));
        }
        public async Task Test_GraphQL_Builder_Returns_Exception_When_Error_Occurs()
        {
            // Arrange
            var expected =
                "{\"query\":\"query{field}\"}";
            var httpClientMock = A.Fake <IGraphQLHttpExecutor>(x => x.Strict());

            A.CallTo(() => httpClientMock.ExecuteQuery(expected,
                                                       A <string> .Ignored,
                                                       A <HttpMethod> .Ignored,
                                                       A <string> .Ignored,
                                                       A <string> .Ignored,
                                                       A <IDictionary <string, string> > .Ignored,
                                                       A <CancellationToken> .Ignored))
            .Returns(new GraphQLExecutorResponse
            {
                Response = JsonConvert.SerializeObject(new
                {
                    Data = new
                    {
                        Field = "FieldValue"
                    },
                    Errors = new[]
                    {
                        new
                        {
                            message   = "This is not a valid query!",
                            locations = new []
                            {
                                new
                                {
                                    line   = 1,
                                    column = 0
                                },
                                new
                                {
                                    line   = 1,
                                    column = 1
                                }
                            }
                        }
                    }
                })
            });

            var client = new GraphQLHttpClient(httpClientMock, new GraphQLFieldBuilder(),
                                               new GraphQLQueryGeneratorFromFields(), new GraphQLDeserilization(), new QueryGeneratorFilter());

            // Act
            var query = client.CreateQuery(builder =>
                                           builder.Field("field"), "randomurl");

            // Assert
            await Assert.ThrowsAsync <GraphQLErrorException>(() => query.Execute());
        }
Esempio n. 12
0
        public async Task <PostListViewModel> SearchPosts(string searchTerm)
        {
            using var graphQLClient = new GraphQLHttpClient("http://hitsrvwp1.becom.at/graphql", new SystemTextJsonSerializer());

            _logger.LogInformation($"Searching posts with {searchTerm}...");
            var request = new GraphQLRequest
            {
                Query = @"
                    query SEARCH_POSTS {
                        posts(where: {search: ""{search}""}) {
                            edges {
                                cursor
                                node {
                                    author {
                                        node {
                                            firstName
                                            lastName
                                            email
                                        }
                                    }
                                    categories {
                                        nodes {
                                            name
                                        }
                                    }
                                    id
                                    date
                                    title
                                    excerpt
                               }
                           }
                           pageInfo {
                                hasNextPage
                                hasPreviousPage
                                startCursor
                                endCursor
                           }
                       }
                   }
                ".Replace("{search}", searchTerm)
            };

            var graphQLResponse = await graphQLClient.SendQueryAsync <PostsData <PostsNode> >(request);

            if (graphQLResponse.Errors != null && graphQLResponse.Errors.Length > 0)
            {
                foreach (var e in graphQLResponse.Errors)
                {
                    _logger.LogError($"Error searching posts with {searchTerm}: {e.Message}");
                }
                return(null);
            }
            _logger.LogInformation($"Posts loaded!");
            return(graphQLResponse.Data.ToOverview());
        }
Esempio n. 13
0
        internal static Task <GraphQLResponse <TResponse> > SendRequest <TResponse>(
            this GraphQLHttpWebSocket graphQlHttpWebSocket,
            GraphQLRequest request,
            GraphQLHttpClient client,
            CancellationToken cancellationToken = default)
        {
            return(Observable.Create <GraphQLResponse <TResponse> >(async observer => {
                await client.Options.PreprocessRequest(request, client);
                var websocketRequest = new GraphQLWebSocketRequest {
                    Id = Guid.NewGuid().ToString("N"),
                    Type = GraphQLWebSocketMessageType.GQL_START,
                    Payload = request
                };
                var observable = graphQlHttpWebSocket.ResponseStream
                                 .Where(response => response != null && response.Id == websocketRequest.Id)
                                 .TakeUntil(response => response.Type == GraphQLWebSocketMessageType.GQL_COMPLETE)
                                 .Select(response => {
                    Debug.WriteLine($"received response for request {websocketRequest.Id}");
                    var typedResponse =
                        client.Options.JsonSerializer.DeserializeToWebsocketResponse <TResponse>(
                            response.MessageBytes);
                    return typedResponse.Payload;
                });

                try {
                    // intialize websocket (completes immediately if socket is already open)
                    await graphQlHttpWebSocket.InitializeWebSocket().ConfigureAwait(false);
                }
                catch (Exception e) {
                    // subscribe observer to failed observable
                    return Observable.Throw <GraphQLResponse <TResponse> >(e).Subscribe(observer);
                }

                var disposable = new CompositeDisposable(
                    observable.Subscribe(observer)
                    );

                Debug.WriteLine($"submitting request {websocketRequest.Id}");
                // send request
                try {
                    await graphQlHttpWebSocket.SendWebSocketRequest(websocketRequest).ConfigureAwait(false);
                }
                catch (Exception e) {
                    Console.WriteLine(e);
                    throw;
                }

                return disposable;
            })
                   // complete sequence on OperationCanceledException, this is triggered by the cancellation token
                   .Catch <GraphQLResponse <TResponse>, OperationCanceledException>(exception =>
                                                                                    Observable.Empty <GraphQLResponse <TResponse> >())
                   .FirstOrDefaultAsync()
                   .ToTask(cancellationToken));
        }
Esempio n. 14
0
        public static CallbackMonitor <GraphQLHttpClient> ConfigureMonitorForOnWebsocketConnected(
            this GraphQLHttpClient client)
        {
            var tester = new CallbackMonitor <GraphQLHttpClient>();

            client.Options.OnWebsocketConnected = c => {
                tester.Invoke(c);
                return(Task.CompletedTask);
            };
            return(tester);
        }
Esempio n. 15
0
        public GraphQLHttpClient GetClient()
        {
            AddToken();
            var graphQlHttpClient = new GraphQLHttpClient(
                new GraphQLHttpClientOptions {
                EndPoint = new Uri($"/graphql")
            },
                new NewtonsoftJsonSerializer(), m_httpClient);;

            return(graphQlHttpClient);
        }
Esempio n. 16
0
        public LoggiPrestoClient(string apiToken, string email, string apiUrl = "https://staging.loggi.com/graphql", bool logado = true)
        {
            _client = new GraphQLHttpClient(apiUrl, new NewtonsoftJsonSerializer());

            _apiToken = apiToken;
            _email    = email;

            IsLogged = logado;

            _client.HttpClient.DefaultRequestHeaders.Add("Authorization", String.Format("ApiKey {0}:{1}", _email, _apiToken));
        }
Esempio n. 17
0
        static Query()
        {
            var uri            = new Uri("https://api.spacex.land/graphql");
            var graphQLOptions = new GraphQLHttpClientOptions
            {
                EndPoint           = uri,
                HttpMessageHandler = new NativeMessageHandler(),
            };

            graphQLHttpClient = new GraphQLHttpClient(graphQLOptions, new NewtonsoftJsonSerializer());
        }
Esempio n. 18
0
        static Mutation()
        {
            var uri            = new Uri("https://localhost:44303/graphql");
            var graphQLOptions = new GraphQLHttpClientOptions
            {
                EndPoint           = uri,
                HttpMessageHandler = new NativeMessageHandler(),
            };

            graphQLHttpClient = new GraphQLHttpClient(graphQLOptions, new NewtonsoftJsonSerializer());
        }
Esempio n. 19
0
        public GraphQLService(string apiBaseAddress, bool autoRedirectRequests, Func <DelegatingHandler> delegatingHandler, IDictionary <string, string> defaultHeaders)
        {
            if (string.IsNullOrEmpty(apiBaseAddress))
            {
                throw new ArgumentNullException(nameof(apiBaseAddress));
            }

            Debug.WriteLine($"GraphQL base url set to: {apiBaseAddress}, autoRedirects: {autoRedirectRequests} and delegatingHandler: {delegatingHandler != null}");

            BaseUrl = apiBaseAddress;

            Func <HttpMessageHandler, GraphQLHttpClient> createClient = messageHandler =>
            {
                HttpMessageHandler handler;

                if (delegatingHandler != null)
                {
                    var delegatingHandlerInstance = delegatingHandler.Invoke();
                    delegatingHandlerInstance.InnerHandler = messageHandler;
                    handler = delegatingHandlerInstance;
                }
                else
                {
                    handler = messageHandler;
                }

                if (!autoRedirectRequests)
                {
                    DisableAutoRedirects(messageHandler);
                }

                var client = new GraphQLHttpClient(new GraphQLHttpClientOptions
                {
                    HttpMessageHandler = handler,
                    EndPoint           = new Uri(apiBaseAddress)
                }, new NewtonsoftJsonSerializer());

                if (defaultHeaders != default)
                {
                    foreach (var header in defaultHeaders)
                    {
                        client.HttpClient.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                return(client);
            };

            _background = new Lazy <GraphQLHttpClient>(() => createClient(new RateLimitedHttpMessageHandler(new NativeHttpClientHandler(), Priority.Background)));

            _userInitiated = new Lazy <GraphQLHttpClient>(() => createClient(new RateLimitedHttpMessageHandler(new NativeHttpClientHandler(), Priority.UserInitiated)));

            _speculative = new Lazy <GraphQLHttpClient>(() => createClient(new RateLimitedHttpMessageHandler(new NativeHttpClientHandler(), Priority.Speculative)));
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            GraphQLHttpClient graphQLHttpClient;

            var httpClientOption = new GraphQLHttpClientOptions
            {
                EndPoint = new Uri("https://moviesg.azurewebsites.net/api")
            };

            graphQLHttpClient = new GraphQLHttpClient(httpClientOption, new NewtonsoftJsonSerializer());
            GetAllMovies(graphQLHttpClient).Wait();
        }
        public async Task <ICollection <T> > GetAll(string query, string name)
        {
            var req = new GraphQLRequest
            {
                Query = query
            };

            var client = new GraphQLHttpClient($"{Environment.GetEnvironmentVariable("ASPNETCORE_API_URL")}");
            var res    = await client.SendQueryAsync(req);

            return(res.GetDataFieldAs <ConnectionGraphQl <T> >(name).Nodes);
        }
Esempio n. 22
0
        public GraphCmsClient(GraphCmsOptions options)
        {
            options.ThrowsIfInvalid();

            _client = new GraphQLHttpClient(options.Endpoint, new SystemTextJsonSerializer());

            if (!string.IsNullOrEmpty(options.ApiToken))
            {
                _client.HttpClient.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Bearer", options.ApiToken);
            }
        }
Esempio n. 23
0
        public async Task TestSimpleMutation()
        {
            // Arrange
            var client        = _factory.CreateClient();
            var graphQLClient = GraphQLHttpClient.Default(client);

            // Act
            var result = await graphQLClient.CreateMutation <TestHelloMutation>("http://localhost/graphql").Execute();

            // Assert
            Assert.Equal("mutation", result.Hello);
        }
Esempio n. 24
0
        public OrganizationsRepository(
            IConfiguration configuration,
            IAdminBearerTokenClient adminBearerTokenClient,
            ILogger logger)
        {
            string endpoint = $"{configuration["AdminApi:Endpoint"]}/api/appadmin";

            logger.LogInformation($"Admin endpoint: {endpoint}");
            _client = new GraphQLHttpClient(endpoint, new NewtonsoftJsonSerializer());
            _adminBearerTokenClient = adminBearerTokenClient;
            _logger = logger;
        }
        public async Task Test_IntrospectionResult_Does_Not_Contain_Errors()
        {
            // Arrange
            var client        = _factory.CreateClient();
            var graphQLClient = GraphQLHttpClient.Default(client);

            // Act
            var result = await graphQLClient.CreateQuery <GraphQLIntrospectionQuery>("http://localhost/graphql").ExecuteDetailed();

            // Assert
            Assert.False(result.ContainsErrors);
        }
Esempio n. 26
0
        public async Task TestSimpleQuery()
        {
            // Arrange
            var client        = _factory.CreateClient();
            var graphQLClient = GraphQLHttpClient.Default(client);

            // Act
            var result = await graphQLClient.Execute <TestHelloQuery>(GraphQLOperationType.Query, "http://localhost/graphql");

            // Assert
            Assert.Equal("query", result.Hello);
        }
Esempio n. 27
0
        private static async Task <GraphQLResponse <FileReferencesResponse> > GetFileReferencesResponse(string searchTerm, int pageSize)
        {
            using var client = new GraphQLHttpClient("http://localhost:5002/api/v1/graphql", new NewtonsoftJsonSerializer());
            var request = CreateFileReferencesRequest(new SearchOptions {
                SearchTerm = searchTerm
            }, new PagingOptions {
                PageSize = pageSize
            });
            var response = await client.SendQueryAsync <FileReferencesResponse>(request);

            return(response);
        }
Esempio n. 28
0
        public async Task <T> QueryAsync <T>(string query)

        {
            var graphQLClient = new GraphQLHttpClient(_grapqhlEndpoint, new NewtonsoftJsonSerializer());
            var request       = new GraphQLRequest
            {
                Query = query
            };
            var graphQLResponse = await graphQLClient.SendQueryAsync <T>(request);

            return(graphQLResponse.Data);
        }
Esempio n. 29
0
        public static GraphQLHttpClient CreateGraphQLClient()
        {
            var gitHubAccessToken = CommonHelper.GetGitHubAuthToken();

            var graphQLHttpClient = new GraphQLHttpClient("https://api.github.com/graphql", new NewtonsoftJsonSerializer());

            graphQLHttpClient.HttpClient.DefaultRequestHeaders.Authorization =
                new System.Net.Http.Headers.AuthenticationHeaderValue(
                    scheme: "bearer",
                    parameter: gitHubAccessToken);
            return(graphQLHttpClient);
        }
Esempio n. 30
0
        public async Task Can_Get_Result_With_Enummember()
        {
            // Arrange
            var client        = _factory.CreateClient();
            var graphQLClient = GraphQLHttpClient.Default(client);

            // Act
            var query = await graphQLClient.CreateQuery <EmQuery>("http://localhost/graphql", arguments : new GraphQLQueryArgument("fromSrc", RdSrcWithEnumMember.correctValue)).Execute();

            // Assert
            Assert.Single(query.QryRdByEm);
        }