Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
Axios & Typescript: Return array object with only the props specified

I'm trying to build an API that fetches the ERC20 tokens in my balance. For this, I'm using nextjs & axios with TypeScript.

The issue I have is that the response outputed by my endpoint returns way too much data, rather than the only 3 props defined in my Token type. Here is how it goes:

util/api.ts

import axios from 'axios';
import console from 'console';


type Token = {
  contractAddress: string;
  tokenName: string;
  tokenSymbol: string;
};

async function getTokens(walletAddress: string) {
  const params = {
    action: 'tokentx',
    address: walletAddress,
    offset: 5,
    startblock: 0,
    endblock: 999999999,
    sort: 'asc',
    apikey: 'XXXXX'
  }

  try {
    const response = await axios.request<Token[]>({
      url: 'https://api.etherscan.io/api?module=account',
      params: params
    }).then((response) => {
      return response.data
    });

    return response
  } catch (error) {
    if (axios.isAxiosError(error)) {
      console.log('error message: ', error.message);
      return error.message;
    } else {
      console.log('unexpected error: ', error);
      return 'An unexpected error occurred';
    }
  }
}

export async function getWalletBalance(walletAddress: string) {
  let tokens = await getTokens(walletAddress)
  return tokens
}

pages/api/balances/[network]/[wallet.ts]

import { NextApiRequest, NextApiResponse } from "next";
import NextCors from "nextjs-cors";
import { getWalletBalance } from "../../../../util/api";

export default async (req: NextApiRequest, res: NextApiResponse) => {
  await NextCors(req, res, {
    methods: ["GET"],
    origin: "*",
    optionsSuccessStatus: 200,
  });

  const { wallet } = req.query as { wallet: string };

  try {
    const balance = await getWalletBalance(wallet);
    res.json({ balance });
  } catch (e) {
    res.status(400).json({ error: (e as Error).message });
  }
};

How can I make it so that getTokens() only returns an array of Token with only the contractAddress, tokenName, tokenSymbol props, in order for the endpoint to output only the JSON I need?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you're looking to reduce the data returned from the api.etherscan.io in your own proxy api you'd need to filter out only the props you need. you can achieve it like so:

.then((response) => {
      return response.data.map(x=>({
         contractAddress:x.contractAddress
         tokenName:x.tokenName
         tokenSymbol:x.tokenSymbol
    });
  })

I don't know much about the 3rd party endpoint but I assuming its a REST endpoint so you couldn't take advantage of Graphql's ability to reduce overfetching by specifying the properties of the type you're interested in.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda