V
V
vlad3221112021-10-27 21:03:27
typescript
vlad322111, 2021-10-27 21:03:27

Is it possible to write code like this?

The task is to accept an array with data, on the basis of which you need to make asynchronous requests, an error may occur, as a result, you need to return the results of successful requests. The main question is whether my types are correctly arranged, what is the best way to implement typescript here?

import { Idividend, ImainStock } from "~/types/stocks/mainStock";
import { ItinkoffAPITickers } from "~/types/stocks/tinkoffAPITickers";

export default async function(tickers: Array<ItinkoffAPITickers>): Promise<Array<ImainStock>> {
  console.log("[API fetchHistoricalDiv.js]");

  const currentDate: number = Math.floor(Date.now() / 1000);
  const twoPrevYears: number =
    new Date(new Date().getFullYear() - 2, 0).getTime() / 1000;

  let parsedStocks = await Promise.all(
    tickers.map(async (e: ItinkoffAPITickers): Promise<ImainStock | null> => {
      let ticker: string = '';
      
      if (e.currency === "USD") {
        ticker = e.ticker;
      } else if (e.currency === "RUB") {
        ticker = e.ticker + ".ME";
      } else if (e.currency === "EUR") {
        ticker = e.ticker.replace("@", ".");
      }

      try {
        const responsePriceAndDividendsByTicker = await fetch(
          `https://query1.finance.yahoo.com/v8/finance/chart/${ticker}?period1=${twoPrevYears}&period2=${currentDate}&interval=1mo&includePrePost=true&events=div%7Csplit`
        );
        const dataPriceAndDividendsByTicker = await responsePriceAndDividendsByTicker.json();

        const price =  dataPriceAndDividendsByTicker.chart.result[0].meta.regularMarketPrice;
        const dividends: Array<Idividend> = Object.values(dataPriceAndDividendsByTicker.chart.result[0].events.dividends)

        return {
          text: `[${e.ticker}] - ${e.name}`,
          value: {
            ...e,
            price,
            dividends
          }
        };
      } catch (error) {
        console.log("error", error);
        return null
      }
    })
  )

  const resulStocks = parsedStocks.filter((e): boolean => !!e ) as Array<ImainStock>
  
  return resulStocks;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-29
@Aetae

Any details are a matter of taste, the dangers were pointed out to you in the comments, as well as the main problem:

const dataPriceAndDividendsByTicker = await responsePriceAndDividendsByTicker.json();

However, here it is worth stopping in more detail.
Even if you "typify" the return from the server directly, there is no guarantee that exactly what is needed will come there. In this case, you're just "banning" TypeScript. For everything coming from the server, it is worth writing at least a minimal type guard .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question