Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda