graphql-request#request TypeScript Examples

The following examples show how to use graphql-request#request. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticProps({ params }) {
  const { slug } = params;

  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default"
  );

  let data: any = await graphQLClient.request(print(allProducts), {
    where: {
      slug: { current: { eq: slug } },
    },
  });

  let product = data.allProduct.find((p) => p.slug.current === slug);

  return {
    props: {
      ...product,
    },
    revalidate: 1,
  };
}
Example #2
Source File: top-100.ts    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
getTokens = async (): Promise<BitqueryEntity[]> => {
  try {
    const [today, monthAgo] = getDateRange();

    const { ethereum } = await request(
      "https://graphql.bitquery.io/",
      gql`
        query ($from: ISO8601DateTime, $till: ISO8601DateTime, $blacklist: [String!]) {
          ethereum(network: bsc) {
            dexTrades(
              options: { desc: "Total_USD", limit: 100 }
              exchangeName: { is: "Pancake v2" }
              baseCurrency: { notIn: $blacklist }
              date: { since: $from, till: $till }
            ) {
              Total_USD: tradeAmount(calculate: sum, in: USD)
              baseCurrency {
                address
                name
                symbol
                decimals
              }
            }
          }
        }
      `,
      {
        from: monthAgo,
        till: today,
        blacklist,
      }
    );

    return ethereum.dexTrades;
  } catch (error) {
    return error;
  }
}
Example #3
Source File: typeorm.ts    From type-graphql-dataloader with MIT License 6 votes vote down vote up
test("verify query certs", async () => {
  const query = gql`
    query {
      certs {
        __typename
        name
        employees {
          __typename
          name
        }
      }
    }
  `;
  const data = await request(endpoint, query);
  await verify(data.certs, await getRepository(Cert).find());
});
Example #4
Source File: top-100.ts    From pancake-toolkit with GNU General Public License v3.0 6 votes vote down vote up
getTokens = async (): Promise<BitqueryEntity[]> => {
  try {
    const [today, monthAgo] = getDateRange();

    const { ethereum } = await request(
      "https://graphql.bitquery.io/",
      gql`
        query ($from: ISO8601DateTime, $till: ISO8601DateTime, $blacklist: [String!]) {
          ethereum(network: bsc) {
            dexTrades(
              options: { desc: "Total_USD", limit: 100 }
              exchangeName: { is: "Pancake v2" }
              baseCurrency: { notIn: $blacklist }
              date: { since: $from, till: $till }
            ) {
              Total_USD: tradeAmount(calculate: sum, in: USD)
              baseCurrency {
                address
                name
                symbol
                decimals
              }
            }
          }
        }
      `,
      {
        from: monthAgo,
        till: today,
        blacklist,
      }
    );

    return ethereum.dexTrades;
  } catch (error) {
    return error;
  }
}
Example #5
Source File: subgraph.ts    From nouns-monorepo with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Query the subgraph and return all proposals and votes
 * @returns All proposals and votes from the subgraph
 */
export async function getAllProposals(): Promise<Proposal[]> {
  const res = await request<ProposalSubgraphResponse>(
    config.nounsSubgraph,
    gql`
      {
        proposals {
          id
          proposer {
            id
          }
          description
          status
          quorumVotes
          proposalThreshold
          startBlock
          endBlock
          executionETA
          votes {
            id
            voter {
              id
            }
            votes
            supportDetailed
            reason
          }
        }
      }
    `,
  );
  return parseProposalSubgraphResponse(res);
}
Example #6
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticProps({ params }) {
  const { slug } = params;
  const graphQLClient = new GraphQLClient(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default"
  );

  let data: any = await graphQLClient.request(print(allUseCases), {
    where: {
      slug: { current: { eq: slug } },
    },
  });

  let useCase = data.allUseCase.find((p) => p.slug.current === slug);

  return {
    props: {
      ...useCase,
    },
    revalidate: 1,
  };
}
Example #7
Source File: updateLPsAPR.ts    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
getBlockAtTimestamp = async (timestamp: number) => {
  try {
    const { blocks } = await request<BlockResponse>(
      BLOCK_SUBGRAPH_ENDPOINT,
      `query getBlock($timestampGreater: Int!, $timestampLess: Int!) {
        blocks(first: 1, where: { timestamp_gt: $timestampGreater, timestamp_lt: $timestampLess }) {
          number
        }
      }`,
      { timestampGreater: timestamp, timestampLess: timestamp + 600 },
    )
    return parseInt(blocks[0].number, 10)
  } catch (error) {
    throw new Error(`Failed to fetch block number for ${timestamp}\n${error}`)
  }
}
Example #8
Source File: [slug].tsx    From livepeer-com with MIT License 6 votes vote down vote up
export async function getStaticPaths() {
  const { allProduct } = await request(
    "https://dp4k3mpw.api.sanity.io/v1/graphql/production/default",
    print(allProducts),
    {
      where: {},
    }
  );
  let paths = [];
  for (const product of allProduct) {
    paths.push({ params: { slug: product.slug.current } });
  }

  return {
    fallback: true,
    paths,
  };
}
Example #9
Source File: infoQueryHelpers.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
multiQuery = async (
  queryConstructor: (subqueries: string[]) => string,
  subqueries: string[],
  endpoint: string,
  skipCount = 1000,
) => {
  let fetchedData = {}
  let allFound = false
  let skip = 0
  try {
    while (!allFound) {
      let end = subqueries.length
      if (skip + skipCount < subqueries.length) {
        end = skip + skipCount
      }
      const subqueriesSlice = subqueries.slice(skip, end)
      // eslint-disable-next-line no-await-in-loop
      const result = await request(endpoint, queryConstructor(subqueriesSlice))
      fetchedData = {
        ...fetchedData,
        ...result,
      }
      allFound = Object.keys(result).length < skipCount || skip + skipCount > subqueries.length
      skip += skipCount
    }
    return fetchedData
  } catch (error) {
    console.error('Failed to fetch info data', error)
    return null
  }
}
Example #10
Source File: topTokens.ts    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
fetchTopTokens = async (timestamp24hAgo: number): Promise<string[]> => {
  try {
    const query = gql`
      query topTokens($blacklist: [String!], $timestamp24hAgo: Int) {
        tokenDayDatas(
          first: 30
          where: { dailyTxns_gt: 0, id_not_in: $blacklist, date_gt: $timestamp24hAgo }
          orderBy: dailyVolumeUSD
          orderDirection: desc
        ) {
          id
        }
      }
    `
    const data = await request<TopTokensResponse>(INFO_CLIENT, query, { blacklist: TOKEN_BLACKLIST, timestamp24hAgo })
    // tokenDayDatas id has compound id "0xTOKENADDRESS-NUMBERS", extracting token address with .split('-')
    return data.tokenDayDatas.map((t) => t.id.split('-')[0])
  } catch (error) {
    console.error('Failed to fetch top tokens', error)
    return []
  }
}
Example #11
Source File: query-script.ts    From anthem with Apache License 2.0 6 votes vote down vote up
graphql = async (requestData: RequestData) => {
  const [key, query, variables] = requestData;
  try {
    console.log(`- Processing query, key: ${key}`);
    const result = await request(GRAPHQL_URL, query, variables);
    writeGraphQLResponseToFile(key, result);
  } catch (err) {
    console.log(
      `- [ERROR]: An error occurred for ${key} query! No data will be saved for this query.`,
    );
  }
}
Example #12
Source File: tokenData.ts    From vvs-ui with GNU General Public License v3.0 6 votes vote down vote up
fetchTokenData = async (
  block24h: number,
  block48h: number,
  block7d: number,
  block14d: number,
  tokenAddresses: string[],
) => {
  try {
    const query = gql`
      query tokens {
        now: ${TOKEN_AT_BLOCK(null, tokenAddresses)}
        oneDayAgo: ${TOKEN_AT_BLOCK(block24h, tokenAddresses)}
        twoDaysAgo: ${TOKEN_AT_BLOCK(block48h, tokenAddresses)}
        oneWeekAgo: ${TOKEN_AT_BLOCK(block7d, tokenAddresses)}
        twoWeeksAgo: ${TOKEN_AT_BLOCK(block14d, tokenAddresses)}
      }
    `
    const data = await request<TokenQueryResponse>(INFO_CLIENT, query)
    return { data, error: false }
  } catch (error) {
    console.error('Failed to fetch token data', error)
    return { error: true }
  }
}
Example #13
Source File: helpers.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
getBetHistory = async (
  where: BetHistoryWhereClause = {},
  first = 1000,
  skip = 0,
): Promise<BetResponse[]> => {
  const response = await request(
    GRAPH_API_PREDICTION,
    gql`
      query getBetHistory($first: Int!, $skip: Int!, $where: Bet_filter) {
        bets(first: $first, skip: $skip, where: $where, order: createdAt, orderDirection: desc) {
          ${getBetBaseFields()}
          round {
            ${getRoundBaseFields()}
          }
          user {
            ${getUserBaseFields()}
          } 
        }
      }
    `,
    { first, skip, where },
  )
  return response.bets
}
Example #14
Source File: queryAavegotchis.ts    From aavegotchi-contracts with MIT License 6 votes vote down vote up
export async function queryAavegotchis(ids: string[]) {
  ids = ids.map((id) => `"${id}"`);

  const query = `
  {aavegotchis(where:{id_in:[${ids}]}) {
    id
    status
  }}
  `;

  const res = await request(maticGraphUrl, query);

  return res;
}
Example #15
Source File: index.ts    From limit-orders-lib with GNU General Public License v3.0 6 votes vote down vote up
queryOrder = async (
  orderId: string,
  chainId: number
): Promise<Order | null> => {
  try {
    const dataFromOldSubgraph = OLD_SUBGRAPH_URL[chainId]
      ? await request(OLD_SUBGRAPH_URL[chainId], GET_ORDER_BY_ID, {
          id: orderId.toLowerCase(),
        })
      : { orders: [] };

    const dataFromNewSubgraph = SUBGRAPH_URL[chainId]
      ? await request(SUBGRAPH_URL[chainId], GET_ORDER_BY_ID, {
          id: orderId.toLowerCase(),
        })
      : { orders: [] };

    const allOrders = [
      ...dataFromOldSubgraph.orders,
      ...dataFromNewSubgraph.orders,
    ];

    return _getUniqueOrdersWithHandler(allOrders).pop() ?? null;
  } catch (error) {
    throw new Error("Could not query subgraph for all orders");
  }
}
Example #16
Source File: updateLPsAPR.ts    From glide-frontend with GNU General Public License v3.0 6 votes vote down vote up
getBlockAtTimestamp = async (timestamp: number) => {
  try {
    const { blocks } = await request<BlockResponse>(
      BLOCK_SUBGRAPH_ENDPOINT,
      `query getBlock($timestampGreater: Int!, $timestampLess: Int!) {
        blocks(first: 1, where: { timestamp_gt: $timestampGreater, timestamp_lt: $timestampLess }) {
          number
        }
      }`,
      { timestampGreater: timestamp, timestampLess: timestamp + 600 },
    )
    return parseInt(blocks[0].number, 10)
  } catch (error) {
    throw new Error(`Failed to fetch block number for ${timestamp}\n${error}`)
  }
}
Example #17
Source File: profile-sdk.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
getAchievements = async (account: string): Promise<Achievement[]> => {
    try {
      const data = await request(
        profileSubgraphApi,
        gql`
          query getUser($id: String!) {
            user(id: $id) {
              points {
                id
                campaignId
                points
              }
            }
          }
        `,
        { id: account.toLowerCase() }
      );
      if (data.user === null || data.user.points.length === 0) {
        return [];
      }
      return data.user.points.reduce((accum: Achievement[], userPoint: UserPointIncreaseEvent) => {
        const campaignMeta = campaignMap.get(userPoint.campaignId);

        return [
          ...accum,
          {
            id: userPoint.campaignId,
            type: campaignMeta?.type ?? "Unknown",
            address: userPoint.id,
            title: getAchievementTitle(campaignMeta, userPoint.campaignId),
            description: getAchievementDescription(campaignMeta),
            badge: campaignMeta?.badge ?? "unknown",
            points: Number(userPoint.points),
          },
        ];
      }, []);
    } catch (error) {
      return [];
    }
  };
Example #18
Source File: useFeedSettings.ts    From apps with GNU Affero General Public License v3.0 5 votes vote down vote up
export default function useFeedSettings(): FeedSettingsReturnType {
  const { user } = useContext(AuthContext);
  const [isFirstLoad, setIsFirstLoad] = useState(true);
  const filtersKey = getFeedSettingsQueryKey(user);
  const queryClient = useQueryClient();
  const { flags } = useContext(FeaturesContext);
  const shouldShowMyFeed = isFeaturedEnabled(Features.MyFeedOn, flags);
  const [avoidRefresh, setAvoidRefresh] = usePersistentContext(
    AVOID_REFRESH_KEY,
    false,
    [true, false],
    false,
  );

  const { data: feedQuery = {}, isLoading } = useQuery<AllTagCategoriesData>(
    filtersKey,
    async () => {
      const req = await request<AllTagCategoriesData>(
        `${apiUrl}/graphql`,
        FEED_SETTINGS_QUERY,
        { loggedIn: !!user?.id },
      );

      if (user || !shouldShowMyFeed) {
        return req;
      }

      const feedSettings = isObjectEmpty(feedQuery.feedSettings)
        ? getEmptyFeedSettings()
        : feedQuery.feedSettings;

      return { ...req, feedSettings };
    },
  );

  const { tagsCategories, feedSettings, advancedSettings } = feedQuery;

  useEffect(() => {
    if (!user?.id || avoidRefresh) {
      return;
    }

    if (isFirstLoad) {
      setIsFirstLoad(false);
      return;
    }

    setTimeout(() => {
      queryClient.invalidateQueries(generateQueryKey('popular', user));
      queryClient.invalidateQueries(generateQueryKey('my-feed', user));
    }, 100);
  }, [tagsCategories, feedSettings, avoidRefresh]);

  return useMemo(() => {
    return {
      tagsCategories,
      feedSettings,
      isLoading,
      advancedSettings,
      hasAnyFilter: getHasAnyFilter(feedSettings),
      setAvoidRefresh,
    };
  }, [
    tagsCategories,
    feedSettings,
    isLoading,
    advancedSettings,
    setAvoidRefresh,
  ]);
}
Example #19
Source File: getUserLotteryData.ts    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
getGraphLotteryUser = async (account: string): Promise<LotteryUserGraphEntity> => {
  let user
  const blankUser = {
    account,
    totalCake: '',
    totalTickets: '',
    rounds: [],
  }

  try {
    const response = await request(
      GRAPH_API_LOTTERY,
      gql`
        query getUserLotteries($account: ID!) {
          user(id: $account) {
            id
            totalTickets
            totalCake
            rounds(first: 100, orderDirection: desc, orderBy: block) {
              id
              lottery {
                id
                endTime
                status
              }
              claimed
              totalTickets
            }
          }
        }
      `,
      { account: account.toLowerCase() },
    )
    const userRes = response.user

    // If no user returned - return blank user
    if (!userRes) {
      user = blankUser
    } else {
      user = {
        account: userRes.id,
        totalCake: userRes.totalCake,
        totalTickets: userRes.totalTickets,
        rounds: userRes.rounds.map((round) => {
          return {
            lotteryId: round?.lottery?.id,
            endTime: round?.lottery?.endTime,
            claimed: round?.claimed,
            totalTickets: round?.totalTickets,
            status: round?.lottery?.status,
          }
        }),
      }
    }
  } catch (error) {
    console.error(error)
    user = blankUser
  }

  return user
}
Example #20
Source File: queryAavegotchis.ts    From aavegotchi-contracts with MIT License 5 votes vote down vote up
export async function getVaultGotchis(
  addresses: string[]
): Promise<UserGotchisOwned[]> {
  console.log("Fetching Vault subgraph gotchis");

  const batchSize = 150;

  const batches = Math.ceil(addresses.length / batchSize);

  let queryData = `{`;

  for (let index = 0; index < batches; index++) {
    const batchId = index;
    const offset = batchId * batchSize;
    queryData = queryData.concat(`
      batch${batchId}: owners(where:{id_in:[${addresses
      .slice(offset, offset + batchSize)
      .map(
        (add: string) => '"' + add.toLowerCase() + '"'
      )}]},first:${batchSize}) {
        id
        gotchis(first:1000) {
          id
        }}
  `);
  }

  queryData = queryData.concat(`}`);

  if (queryData == "{}") return [];

  const res = await request(vaultGraphUrl, queryData);

  let finalResponse: VaultGotchisOwned[] = [];
  for (let index = 0; index < batches; index++) {
    const batch: VaultGotchisOwned[] = res[`batch${index}`];
    finalResponse = finalResponse.concat(batch);
  }

  const userGotchisOwned: UserGotchisOwned[] = finalResponse.map((val) => {
    return {
      gotchisOwned: val.gotchis.map((gotchi) => {
        return { id: gotchi.id, status: "3" };
      }),
      id: val.id,
    };
  });

  return removeEmpty(userGotchisOwned);
}
Example #21
Source File: index.ts    From defillama-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
async function getCompoundAssets(params: {
  targets: Address[];
  block?: number;
}) {
  // This is not an exact copy of the SDK function since we are coalescing everything into ETH, but the total TVL should be the same
  let totalCollateralValueInEth = 0;
  const queries = [];
  for (let i = 0; i < params.targets.length; i += 1000) {
    const addresses = params.targets.slice(i, i + 1000);
    const query = gql`
    {
      accounts(where:{
        id_in:[${addresses.map((addr) => `"${addr.toLowerCase()}"`).join(",")}]
      }) {
        id
        totalCollateralValueInEth
        tokens{
          symbol
          supplyBalanceUnderlying
        }
      }
    }
    `;
    const req = await request(
      "https://api.thegraph.com/subgraphs/name/graphprotocol/compound-v2",
      query
    ).then((data) =>
      data.accounts.forEach((account: any) => {
        totalCollateralValueInEth += Number(account.totalCollateralValueInEth);
      })
    );
    queries.push(req);
  }
  await Promise.all(queries);
  return {
    [ETHER_ADDRESS]: Math.floor(
      totalCollateralValueInEth * 10 ** 18
    ).toString(),
  };
}
Example #22
Source File: subqlProvider.ts    From bodhi.js with Apache License 2.0 5 votes vote down vote up
queryGraphql = (query: string): Promise<Query> =>
    request(
      this.url,
      gql`
        ${query}
      `
    );
Example #23
Source File: profile-sdk.ts    From pancake-toolkit with GNU General Public License v3.0 5 votes vote down vote up
getAchievements = async (account: string): Promise<Achievement[]> => {
    try {
      const data = await request(
        profileSubgraphApi,
        gql`
          query getUser($id: String!) {
            user(id: $id) {
              points {
                id
                campaignId
                points
              }
            }
          }
        `,
        { id: account.toLowerCase() }
      );
      if (data.user === null || data.user.points.length === 0) {
        return [];
      }
      return data.user.points.reduce((accum: Achievement[], userPoint: UserPointIncreaseEvent) => {
        const campaignMeta = campaignMap.get(userPoint.campaignId);

        return [
          ...accum,
          {
            id: userPoint.campaignId,
            type: campaignMeta?.type ?? "Unknown",
            address: userPoint.id,
            title: getAchievementTitle(campaignMeta, userPoint.campaignId),
            description: getAchievementDescription(campaignMeta),
            badge: campaignMeta?.badge ?? "unknown",
            points: Number(userPoint.points),
          },
        ];
      }, []);
    } catch (error) {
      return [];
    }
  };
Example #24
Source File: updateLPsAPR.ts    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
getAprsForFarmGroup = async (addresses: string[], blockWeekAgo: number): Promise<AprMap> => {
  try {
    const { farmsAtLatestBlock, farmsOneWeekAgo } = await request<FarmsResponse>(
      STREAMING_FAST_ENDPOINT,
      gql`
        query farmsBulk($addresses: [String]!, $blockWeekAgo: Int!) {
          farmsAtLatestBlock: pairs(first: 30, where: { id_in: $addresses }) {
            id
            volumeUSD
            reserveUSD
          }
          farmsOneWeekAgo: pairs(first: 30, where: { id_in: $addresses }, block: { number: $blockWeekAgo }) {
            id
            volumeUSD
            reserveUSD
          }
        }
      `,
      { addresses, blockWeekAgo },
    )
    const aprs: AprMap = farmsAtLatestBlock.reduce((aprMap, farm) => {
      const farmWeekAgo = farmsOneWeekAgo.find((oldFarm) => oldFarm.id === farm.id)
      // In case farm is too new to estimate LP APR (i.e. not returned in farmsOneWeekAgo query) - return 0
      let lpApr = new BigNumber(0)
      if (farmWeekAgo) {
        const volume7d = new BigNumber(farm.volumeUSD).minus(new BigNumber(farmWeekAgo.volumeUSD))
        const lpFees7d = volume7d.times(LP_HOLDERS_FEE)
        const lpFeesInAYear = lpFees7d.times(WEEKS_IN_A_YEAR)
        // Some untracked pairs like KUN-QSD will report 0 volume
        if (lpFeesInAYear.gt(0)) {
          const liquidity = new BigNumber(farm.reserveUSD)
          lpApr = lpFeesInAYear.times(100).dividedBy(liquidity)
        }
      }
      return {
        ...aprMap,
        [farm.id]: lpApr.decimalPlaces(2).toNumber(),
      }
    }, {})
    return aprs
  } catch (error) {
    throw new Error(`Failed to fetch LP APR data: ${error}`)
  }
}
Example #25
Source File: updateLPsAPR.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
getAprsForFarmGroup = async (addresses: string[], blockWeekAgo: number): Promise<AprMap> => {
  try {
    const { farmsAtLatestBlock, farmsOneWeekAgo } = await request<FarmsResponse>(
      STREAMING_FAST_ENDPOINT,
      gql`
        query farmsBulk($addresses: [String]!, $blockWeekAgo: Int!) {
          farmsAtLatestBlock: pairs(first: 30, where: { id_in: $addresses }) {
            id
            volumeUSD
            reserveUSD
          }
          farmsOneWeekAgo: pairs(first: 30, where: { id_in: $addresses }, block: { number: $blockWeekAgo }) {
            id
            volumeUSD
            reserveUSD
          }
        }
      `,
      { addresses, blockWeekAgo },
    )
    const aprs: AprMap = farmsAtLatestBlock.reduce((aprMap, farm) => {
      const farmWeekAgo = farmsOneWeekAgo.find((oldFarm) => oldFarm.id === farm.id)
      // In case farm is too new to estimate LP APR (i.e. not returned in farmsOneWeekAgo query) - return 0
      let lpApr = new BigNumber(0)
      if (farmWeekAgo) {
        const volume7d = new BigNumber(farm.volumeUSD).minus(new BigNumber(farmWeekAgo.volumeUSD))
        const lpFees7d = volume7d.times(LP_HOLDERS_FEE)
        const lpFeesInAYear = lpFees7d.times(WEEKS_IN_A_YEAR)
        // Some untracked pairs like KUN-QSD will report 0 volume
        if (lpFeesInAYear.gt(0)) {
          const liquidity = new BigNumber(farm.reserveUSD)
          lpApr = lpFeesInAYear.times(100).dividedBy(liquidity)
        }
      }
      return {
        ...aprMap,
        [farm.id]: lpApr.decimalPlaces(2).toNumber(),
      }
    }, {})
    return aprs
  } catch (error) {
    throw new Error(`Failed to fetch LP APR data: ${error}`)
  }
}
Example #26
Source File: typeorm.ts    From type-graphql-dataloader with MIT License 5 votes vote down vote up
test("verify query desks", async () => {
  const query = gql`
    query {
      desks {
        __typename
        name
        company {
          __typename
          name
        }
        employee {
          __typename
          name
        }
        chair {
          __typename
          name
          company {
            __typename
            name
          }
          desk {
            __typename
            name
            desktopComputer {
              __typename
              name
            }
          }
        }
        desktopComputer {
          __typename
          name
          propertyOf {
            __typename
            name
          }
          placedAt {
            __typename
            name
          }
          installedApps {
            __typename
            name
            installedComputers {
              __typename
              name
            }
            publishedBy {
              __typename
              name
            }
          }
        }
      }
    }
  `;
  const data = await request(endpoint, query);
  await verify(data.desks, await getRepository(Desk).find());
});
Example #27
Source File: domain.ts    From ens-metadata-service with MIT License 4 votes vote down vote up
export async function getDomain(
  provider: any,
  networkName: string,
  SUBGRAPH_URL: string,
  contractAddress: string,
  tokenId: string,
  version: Version,
  loadImages: boolean = true
): Promise<Metadata> {
  let hexId: string, intId;
  if (!tokenId.match(/^0x/)) {
    intId = tokenId;
    hexId = ethers.utils.hexZeroPad(
      ethers.utils.hexlify(ethers.BigNumber.from(tokenId)),
      32
    );
  } else {
    intId = ethers.BigNumber.from(tokenId).toString();
    hexId = tokenId;
  }
  const queryDocument: any =
    version !== Version.v2 ? GET_DOMAINS_BY_LABELHASH : GET_DOMAINS;
  const result = await request(SUBGRAPH_URL, queryDocument, { tokenId: hexId });
  const domain = version !== Version.v2 ? result.domains[0] : result.domain;
  if (!(domain && Object.keys(domain).length)) throw new SubgraphRecordNotFound(`No record for ${hexId}`)
  const { name, labelhash, createdAt, parent, resolver } = domain;

  const hasImageKey =
    resolver && resolver.texts && resolver.texts.includes(IMAGE_KEY);
  const metadata = new Metadata({
    name,
    created_date: createdAt,
    tokenId: hexId,
    version,
  });

  async function requestAvatar() {
    try {
      const [buffer, mimeType] = await getAvatarImage(provider, name);
      const base64 = buffer.toString('base64');
      return [base64, mimeType];
    } catch {
      /* do nothing */
    }
  }

  async function requestNFTImage() {
    if (hasImageKey) {
      const r = await provider.getResolver(name);
      const image = await r.getText(IMAGE_KEY);
      return image;
    }
  }

  async function requestMedia() {
    if (loadImages) {
      const [avatar, imageNFT] = await Promise.all([
        requestAvatar(),
        requestNFTImage(),
      ]);
      if (imageNFT) {
        metadata.setImage(imageNFT);
      } else {
        if (avatar) {
          const [base64, mimeType] = avatar;
          metadata.setBackground(base64, mimeType);
        }
        metadata.generateImage();
      }
    } else {
      metadata.setBackground(
        `https://metadata.ens.domains/${networkName}/avatar/${name}`
      );
      metadata.setImage(
        `https://metadata.ens.domains/${networkName}/${contractAddress}/${hexId}/image`
      );
    }
  }

  async function requestAttributes() {
    if (parent.id === eth) {
      const { registrations } = await request(SUBGRAPH_URL, GET_REGISTRATIONS, {
        labelhash,
      });
      const registration = registrations[0];
      if (registration) {
        metadata.addAttribute({
          trait_type: 'Registration Date',
          display_type: 'date',
          value: registration.registrationDate * 1000,
        });
        metadata.addAttribute({
          trait_type: 'Expiration Date',
          display_type: 'date',
          value: registration.expiryDate * 1000,
        });
      }
    }
  }
  await Promise.all([requestMedia(), requestAttributes()]);
  return metadata;
}
Example #28
Source File: index.ts    From glide-frontend with GNU General Public License v3.0 4 votes vote down vote up
useFetchSearchResults = (
  searchString: string,
): {
  tokens: TokenData[]
  pools: PoolData[]
  tokensLoading: boolean
  poolsLoading: boolean
  error: boolean
} => {
  const [searchResults, setSearchResults] = useState({
    tokens: [], // Token ids found by search query
    pools: [], // Pool ids found by search query
    loading: false, // Search query is in progress
    error: false, // GraphQL returned error
  })

  const searchStringTooShort = searchString.length < MINIMUM_SEARCH_CHARACTERS

  // New value received, reset state
  useEffect(() => {
    setSearchResults({
      tokens: [],
      pools: [],
      loading: !searchStringTooShort,
      error: false,
    })
  }, [searchString, searchStringTooShort])

  useEffect(() => {
    const search = async () => {
      try {
        const tokens = await request<TokenSearchResponse>(INFO_CLIENT, TOKEN_SEARCH, {
          symbol: searchString.toUpperCase(),
          // Most well known tokens have first letter capitalized
          name: searchString.charAt(0).toUpperCase() + searchString.slice(1),
          id: searchString.toLowerCase(),
        })
        const tokenIds = getIds([tokens.asAddress, tokens.asSymbol, tokens.asName])
        const pools = await request<PoolSearchResponse>(INFO_CLIENT, POOL_SEARCH, {
          tokens: tokenIds,
          id: searchString.toLowerCase(),
        })
        setSearchResults({
          tokens: tokenIds,
          pools: getIds([pools.asAddress, pools.as0, pools.as1]),
          loading: false,
          error: false,
        })
      } catch (error) {
        console.error(`Search failed for ${searchString}`, error)
        setSearchResults({
          tokens: [],
          pools: [],
          loading: false,
          error: true,
        })
      }
    }
    if (!searchStringTooShort) {
      search()
    }
  }, [searchString, searchStringTooShort])

  // Save ids to Redux
  // Token and Pool updater will then go fetch full data for these addresses
  // These hooks in turn will return data of tokens that have been fetched
  const tokenDatasFull = useTokenDatas(searchResults.tokens)
  const poolDatasFull = usePoolDatas(searchResults.pools)

  // If above hooks returned not all tokens/pools it means
  // that some requests for full data are in progress
  const tokensLoading = tokenDatasFull.length !== searchResults.tokens.length || searchResults.loading
  const poolsLoading = poolDatasFull.length !== searchResults.pools.length || searchResults.loading

  return {
    tokens: tokenDatasFull,
    pools: poolDatasFull,
    tokensLoading,
    poolsLoading,
    error: searchResults.error,
  }
}
Example #29
Source File: globals-graphql.spec.ts    From payload with MIT License 4 votes vote down vote up
describe('Global Versions - GraphQL', () => {
  const title = 'Global Blocks Title';
  beforeAll(async (done) => {
    // language=graphql
    const login = `
      mutation {
        loginAdmin(
          email: "${email}",
          password: "${password}"
        ) {
          token
        }
      }`;

    const response = await request(url, login);

    token = response.loginAdmin.token;

    client = new GraphQLClient(url, { headers: { Authorization: `JWT ${token}` } });

    // language=graphql
    const query = `mutation {
      updateBlocksGlobal(data: {
        title: "${title}"
        blocks: [{ quote: "Test quote", color: "red", blockName: "Some block title", blockType: "quote"}]
      }) {
        _status
        title
        blocks {
          __typename
          ... on Quote {
            quote
            color
          }
        }
      }
    }`;
    await client.request(query);

    done();
  });

  describe('Create', () => {
    it('should allow a new BlocksGlobal to be created with draft status', async () => {
      const updatedTitle = 'updated global title';

      // language=graphql
      const query = `mutation {
        updateBlocksGlobal(data: {
          title: "${updatedTitle}"
        }) {
          _status
          title
        }
      }`;
      await client.request(query);

      const response = await client.request(query);

      const data = response.updateBlocksGlobal;

      expect(data._status).toStrictEqual('draft');
      expect(data.title).toStrictEqual(updatedTitle);
    });
  });

  describe('should allow a version to be retrieved', () => {
    beforeAll(async (done) => {
      const updatedTitle = 'updated global title';

      // language=graphql
      const update = `mutation {
        updateBlocksGlobal(draft: true, data: {
          title: "${updatedTitle}"
        }) {
          _status
          title
        }
      }`;
      await client.request(update);

      // language=graphQL
      const query = `query {
        versionsBlocksGlobal(where: { version__title: { equals: "${title}" } }) {
          docs {
            id
            version {
              title
            }
          }
        }
      }`;

      const response = await client.request(query);

      versionID = response.versionsBlocksGlobal.docs[0].id;
      done();
    });

    it('should allow read of versions by version id', async () => {
      // language=graphql
      const query = `query {
        versionBlocksGlobal(id: "${versionID}") {
          id
          version {
            title
          }
        }
      }`;

      const response = await client.request(query);

      const data = response.versionBlocksGlobal;
      versionID = data.id;

      expect(data.id).toBeDefined();
      expect(data.version.title).toStrictEqual(title);
    });

    it('should allow read of versions by querying version content', async () => {
      // language=graphQL
      const query = `query {
        versionsBlocksGlobal(where: { version__title: {equals: "${title}" } }) {
          docs {
            id
            version {
              title
            }
          }
        }
      }`;

      const response = await client.request(query);

      const data = response.versionsBlocksGlobal;
      const doc = data.docs[0];
      versionID = doc.id;

      expect(doc.id).toBeDefined();
      expect(doc.version.title).toStrictEqual(title);
    });
  });

  describe('Restore', () => {
    it('should allow a version to be restored', async () => {
      // language=graphql
      const restore = `mutation {
        restoreVersionBlocksGlobal(id: "${versionID}") {
          title
        }
      }`;

      await client.request(restore);

      const query = `query {
        BlocksGlobal {
          title
        }
      }`;

      const response = await client.request(query);
      const data = response.BlocksGlobal;
      expect(data.title).toStrictEqual(title);
    });
  });
});