コード例 #1
0
    public async Task <IActionResult> LatestBlogPosts()
    {
        try
        {
            var query = new GraphQLRequest(@"
                    query {
                      blogPosts(limit: 10, sort: ""published_at:desc"") {
                        id
                        title
                        published_at
                        description
                        banner {
                          url
                        }
                        tags {
                          id
                          name
                        }
                      }
                    }
                ");

            var response = await _graphQLClientRef.SendQueryAsync <BlogPostsType>(query);

            return(Ok(response.Data.BlogPosts ?? new List <BlogPost>()));
        }
        catch (Exception ex)
        {
            _logger.LogError("{exception}", ex);
            return(BadRequest());
        }
    }
コード例 #2
0
        public async Task <List <Country> > Get()
        {
            var result  = this.countryRepository.Get();
            var respone = _client.SendQueryAsync <ResponseCountryCollection>(QueryGetCountry()).GetAwaiter().GetResult();

            if (respone.Data.Country != null)
            {
                respone.Data.Country.ForEach(x => x.IsApi = true);
                return(result.Result.Union(respone.Data.Country).ToList());
            }
            return(await result);
        }
コード例 #3
0
        /// <summary>
        /// Get all Continents from graphQL server
        /// </summary>
        /// <returns>Collection of Continents</returns>
        public async Task <ICollection <Continent> > GetAllContinentsAsync()
        {
            var request = new GraphQLRequest
            {
                Query = @"{
                        continents{
			                code,
                            name,
                        }
                    }"
            };

            var continents = await _graphQLClient.SendQueryAsync <GraphQLContinentsResponse>(request);

            return(continents.Data.continents);
        }
コード例 #4
0
 public static Task <GraphQLResponse <TResponse> > SendQueryAsync <TResponse>(this IGraphQLClient client,
                                                                              string query, object?variables = null,
                                                                              string?operationName           = null, Func <TResponse> defineResponseType = null, CancellationToken cancellationToken = default)
 {
     _ = defineResponseType;
     return(client.SendQueryAsync <TResponse>(new GraphQLRequest(query, variables, operationName),
                                              cancellationToken: cancellationToken));
 }
コード例 #5
0
        public async Task <T> FetchValuesAsync <T>(
            string query)
        {
            var request  = new GraphQLHttpRequest(query);
            var response = await _httpClient.SendQueryAsync <T>(request);

            return(response.Data);
        }
コード例 #6
0
        public async Task <Page> GetSeasonalAnimeList()
        {
            var query = new GraphQLRequest
            {
                Query = @"
                    query 
                    {
                        Page(page:1, perPage:50)
                        {
                            pageInfo
                            {
                                total,
                                perPage,
                                currentPage,
                                lastPage,
                                hasNextPage
                            }
                            media(season:SUMMER, seasonYear:2020, format:TV)
                            {
                                id,
                                title
                                {
                                    userPreferred
                                }
                                coverImage
                                {
                                    large
                                }
                            }
                        }   
                    }
                "
            };

            var response = await _client.SendQueryAsync <PageInfoAndMediaResponseType>(query);

            return(response.Data.Page);
        }
コード例 #7
0
        public async Task <List <Owner> > GetAllOwners()
        {
            var query = new GraphQLRequest
            {
                Query = @"
                        query ownersQuery{
                          owners {
                            id
                            name
                            address
                            accounts {
                              id
                              type
                              description
                            }
                          }
                        }",
            };

            var response = await _client.SendQueryAsync <ResponseOwnerCollectionType>(query);

            return(response.Data.Owners);
        }
コード例 #8
0
        public async Task <IEnumerable <CountryDtoResult> > GetAll()
        {
            var query = new GraphQLRequest
            {
                Query = @"
                    query {
                        Flag {
                            svgFile
                            country {
                            name
                            capital
                            population
                            area
                            populationDensity
                            }
                        }
                    } "
            };

            var list = await _repository.SelectAsync();

            if (list.Count() > 0)
            {
                return(_mapper.Map <IEnumerable <CountryDtoResult> >(list));
            }

            var response = await _client.SendQueryAsync <ResponseDto>(query);

            var resultApi = response.Data.Flag;

            foreach (var item in resultApi)
            {
                if (await _repository.SelectByName(item.Country.Name) == null)
                {
                    await _repository.InsertAsync(new CountryEntity
                    {
                        Name              = item.Country.Name,
                        Capital           = item.Country.Capital,
                        Population        = item.Country.Population,
                        Area              = item.Country.Area,
                        PopulationDensity = item.Country.PopulationDensity,
                        SvgFile           = item.SvgFile,
                        OriginalInfo      = true,
                        ObjectJson        = JsonConvert.SerializeObject(item)
                    });
                }
            }

            return(_mapper.Map <IEnumerable <CountryDtoResult> >(await _repository.SelectAsync()));
        }
コード例 #9
0
        /// <summary>
        /// Get the first 150 most liquid market pairs ordered by desc
        /// </summary>
        /// <returns></returns>
        public async Task <Pools> GetMostLiquidMarketPairs()
        {
            var query = new GraphQLRequest
            {
                Query = @"
                {
                    pairs(first: 150, orderBy: reserveETH orderDirection: desc){
                    token0 {
                      symbol
                    }
                    token1 {
                      symbol
                    }
                    reserveETH
                    reserveUSD
                  }
                }
                "
            };

            GraphQLResponse <Pools> response = await _graphQLClient.SendQueryAsync <Pools>(query);

            return(response.Data);
        }
コード例 #10
0
        public async Task <ProductModel> GetProduct(int id)
        {
            var query = new GraphQLRequest
            {
                Query     = @"
                query productQuery($productId:ID!)
                {
                    product(id:$productID)
                    {
                       id name price rating photoFileName description stock introducedAt 
                      reviews { title review }
                    }
                }",
                Variables = new { productId = id }
            };

            var response = await _graphQLClient.SendQueryAsync <ProductModel>(query, CancellationToken.None);

            return(response.Data);
        }
コード例 #11
0
        private Schema InitSchema(IGraphQLClient gqlClient)
        {
            var request = new GraphQLRequest {
                Query = GetIntrospectionQuery()
            };

            var result = Task.Run(async() => await gqlClient.SendQueryAsync <JObject>(request, CancellationToken.None))
                         .GetAwaiter()
                         .GetResult()
                         .Data;

            var queryType = (JObject)result["__schema"]["queryType"];
            var types     = ((JArray)result["__schema"]["types"]).Cast <JObject>().ToArray();

            var dummySchema = new Schema();

            dummySchema.Initialize();
            var schemaTypes = new SchemaTypes(dummySchema, new DefaultServiceProvider());
            var cache       = new Dictionary <string, IGraphType>();

            var qt = ResolveGraphType(_ => schemaTypes[_] ?? (cache.ContainsKey(_) ? cache[_] : null), types, queryType, cache);

            var commonTypes = cache.Values.ToArray();

            foreach (var type in types)
            {
                ResolveGraphType(_ => schemaTypes[_] ?? (cache.ContainsKey(_) ? cache[_] : null), types, type, cache);
            }

            var newSchema = new Schema();

            newSchema.Query = (IObjectGraphType)qt;

            foreach (var type in cache.Values.Except(commonTypes))
            {
                newSchema.RegisterType(type);
            }

            newSchema.Initialize();
            return(newSchema);
        }
コード例 #12
0
        public async Task <List <Owner> > GetAllOwners()
        {
            var query = new GraphQLRequest
            {
                Query = @"query ownersQuery{
                              owners{
                                id,
                                name,
                                address,
                                 accounts{
                                  id,
                                  description,
                                  ownerId,
                                  type
                                }
                              }
                            }"
            };
            var response = await _graphQLClient.SendQueryAsync <ResponseOwnerCollectionType>(query);

            return(response.Data.Owners);
        }
コード例 #13
0
        public object Execute(Expression expression)
        {
            var variablesResolver = new VariablesResolver();
            var query             = queryBuilder.BuildQuery(expression, variablesResolver, out var entryPoint);
            var request           = new GraphQLRequest
            {
                Query     = query,
                Variables = variablesResolver.GetAllVariables().ToDictionary(_ => _.name, _ => _.value)
            };

            var result = Task.Run(() => client.SendQueryAsync <JToken>(request, CancellationToken.None))
                         .GetAwaiter()
                         .GetResult();

            expression = RewriteExpression(expression, result.Data[entryPoint]);

            return(expression switch
            {
                MethodCallExpression method => Expression.Lambda <Func <object> >(method).Compile()(),
                ConstantExpression constant => constant.Value,
                _ => throw new NotImplementedException()
            });
コード例 #14
0
        public async Task <IEnumerable <CountryDtoResult> > GetAll()
        {
            var query = new GraphQLRequest
            {
                Query = @"
                    query {
                        Flag {
                            svgFile
                            country {
                                name
                                capital
                                population
                                area
                                populationDensity
                                officialLanguages {
                                    name
                                }
                            }
                        }
                    } "
            };

            var response = await _client.SendQueryAsync <ResponseDto>(query);

            var resultApi = response.Data.Flag;

            foreach (var item in resultApi)
            {
                var country = await _repository.SelectByName(item.Country.Name);

                if (country == null)
                {
                    await _repository.InsertAsync(new CountryEntity
                    {
                        Name              = item.Country.Name,
                        Capital           = item.Country.Capital,
                        Population        = item.Country.Population,
                        Area              = item.Country.Area,
                        PopulationDensity = item.Country.PopulationDensity,
                        OfficialLanguage  = item.Country.OfficialLanguages.FirstOrDefault().name,
                        SvgFile           = item.SvgFile,
                        OriginalInfo      = true,
                        ObjectJson        = JsonConvert.SerializeObject(item)
                    });
                }
                else
                {
                    if (country.OfficialLanguage == null)
                    {
                        await _repository.UpdateAsync(new CountryEntity
                        {
                            Id                = country.Id,
                            Name              = country.Name,
                            Capital           = country.Capital,
                            Population        = country.Population,
                            Area              = country.Area,
                            PopulationDensity = country.PopulationDensity,
                            OfficialLanguage  = item.Country.OfficialLanguages.FirstOrDefault().name,
                            SvgFile           = country.SvgFile,
                            OriginalInfo      = true,
                            ObjectJson        = JsonConvert.SerializeObject(item)
                        });
                    }
                }
            }

            return(_mapper.Map <IEnumerable <CountryDtoResult> >(await _repository.SelectAsync()));
        }
コード例 #15
0
 public static Task <GraphQLResponse <TResponse> > SendQueryAsync <TResponse>(this IGraphQLClient client,
                                                                              GraphQLRequest request, Func <TResponse> defineResponseType, CancellationToken cancellationToken = default)
 => client.SendQueryAsync <TResponse>(request, cancellationToken);
コード例 #16
0
        public async Task <ListServiceResponse <Token> > FetchAllAsync()
        {
            var result = new ListServiceResponse <Token>();

            try
            {
                GraphQLResponse <TokenList> graphQLResponse = null;

                var list = new List <Token>();
                var last = "0x0";

                do
                {
                    var initialRequest = new GraphQLRequest
                    {
                        Query         = @"
                    query GetTokens(
                      $first: Int,
	                    $orderBy: ID,
	                    $orderDirection: String) {
                        tokens(
                          first: $first, where: {
                                id_gt: "     + $"\"{last}\"" + @"
                                },
                            orderBy: $orderBy,
                            orderDirection: $orderDirection) {
                                    id
                                    symbol
                                    name
                        }
                            }",
                        OperationName = "GetTokens",
                        Variables     = new
                        {
                            first = 500
                        }
                    };

                    graphQLResponse = await _graphQLClient.SendQueryAsync <TokenList>(initialRequest);

                    if (!(graphQLResponse.Data is null))
                    {
                        if (graphQLResponse.Data.Tokens.AnyAndNotNull())
                        {
                            list.AddRange(graphQLResponse.Data.Tokens);

                            var lastOne = graphQLResponse.Data.Tokens.Last();

                            last = lastOne.Id;
                        }
                    }

                    if (!(graphQLResponse.Errors is null))
                    {
                        result.ListResponse = null;
                        result.Message      = graphQLResponse.Errors?.FirstOrDefault().Message;
                        break;
                    }

                    Thread.Sleep(500);
                } while (!(graphQLResponse.Data is null) && (graphQLResponse.Errors is null) && graphQLResponse.Data.Tokens.AnyAndNotNull());

                result.ListResponse = list;
            }
            catch (Exception ex)
            {
                result.Message = ex.GetFullMessage();
            }
            return(result);
        }
コード例 #17
0
ファイル: Operations.cs プロジェクト: stercoris/SmartCollege
 public static System.Threading.Tasks.Task <GraphQLResponse <Response> > SendQueryAsync(IGraphQLClient client, Variables variables, System.Threading.CancellationToken cancellationToken = default)
 {
     return(client.SendQueryAsync <Response>(Request(variables), cancellationToken));
 }
コード例 #18
0
        public async Task <List <FirewallEvent> > GetFirewallEvents(string clientIP)
        {
            DateTime now      = DateTime.UtcNow;
            int      attempts = 0;
            bool     commFail = false;
            bool     apiError = false;

            if (Program.Debug)
            {
                Console.WriteLine("geq: " + now.AddMinutes(Program.FirewallEventMinutes * -1).ToString("o") + " leq: " + now.AddMinutes(1).ToString("o"));
            }

            while (attempts < 4)
            {
                try
                {
                    var query = new GraphQLRequest
                    {
                        Query = "query { viewer { zones(filter: {zoneTag: \"" + Program.ZoneID + "\"}) { firewallEventsAdaptive(filter: { datetime_geq: \"" + now.AddMinutes(Program.FirewallEventMinutes * -1).ToString("o") + "\", datetime_leq: \"" + now.AddMinutes(1).ToString("o") + "\", clientIP: \"" + clientIP + "\" }, limit: 10000, orderBy: [datetime_DESC]) { clientIP clientRequestPath }}}}"
                    };

                    var response = await _client.SendQueryAsync <ResponseData>(query);

                    if (response.Errors != null)
                    {
                        if (Program.Debug)
                        {
                            foreach (GraphQLError error in response.Errors)
                            {
                                Console.WriteLine("API error: " + error.Message);
                            }
                        }

                        apiError = true;
                        attempts++;
                        Thread.Sleep(2000);
                        continue;
                    }

                    return(response.Data.viewer.zones[0].firewallEventsAdaptive);
                }
                catch (Exception e) when(e is HttpRequestException || e is GraphQLHttpRequestException || e is TaskCanceledException)
                {
                    commFail = true;
                    attempts++;
                    Thread.Sleep(2000);
                }
            }

            if (commFail && apiError)
            {
                throw new CloudflareException("Multiple Cloudflare API errors: Errors were returned and communication failed, see debug info");
            }
            else if (apiError)
            {
                throw new CloudflareException("The Cloudflare API returned an error, see debug info");
            }
            else
            {
                throw new CloudflareException("Communication with the Cloudflare API failed");
            }
        }
コード例 #19
0
        public async Task <GraphQLData> GetAllComponentInfo(string mnf, int set, string currency)
        {
            var query = new GraphQLRequest
            {
                Query     = @"
 query MyPartSearch($q: String!, $limit: Int!, $currency: String!) {
   search(q: $q, limit: $limit, currency: $currency) {
     results {
      part {
        mpn
        category{
          name
        }
        manufacturer {
          name
        }
        manufacturer_url
        best_datasheet {
          name
          url
        }
        short_description
        octopart_url
        images{
          url
        }
        specs {
          attribute {
            name
            group
          }
          display_value
        }
        sellers(include_brokers: false, authorized_only: true) {
          company {
            name
          }
          offers {
            sku
            moq
            click_url
            updated
            inventory_level
            prices {
              price
              currency
              quantity
              converted_price
              converted_currency
            }
          }
        }
      }
    }
                        }
                      }",
                Variables = new {
                    q        = mnf,
                    limit    = set,
                    currency = currency
                }
            };



            var response = await _client.SendQueryAsync <GraphQLData>(query);

            return(response.Data);
        }
コード例 #20
0
 public Task <Result <TCast, Error.ExceptionalError> > SendQueryAsync <TResponse, TCast>(RequestAdapter <TResponse, TCast> adapter) =>
 Result.Try(async() =>
 {
     var response = (await _client.SendQueryAsync <TResponse>(adapter.Request)).Data;
     return(adapter.Selector(response));
 });