-
Notifications
You must be signed in to change notification settings - Fork 0
Typescript Example Code
MMDRZA edited this page Oct 18, 2024
·
1 revision
import fetch from 'node-fetch';
interface Coin {
symbol: string;
lastPrice: string;
highPrice24h: string;
lowPrice24h: string;
changeRate: string;
lastUpdated: string;
}
const rawUrl = 'https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json';
async function fetchCryptoData(): Promise<Coin[]> {
const response = await fetch(rawUrl);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const result: Coin[] = await response.json();
return result;
}
function displayCryptoData(coins: Coin[]): void {
coins.forEach(coin => {
console.log(
`Symbol: ${coin.symbol} : LAST: ${coin.lastPrice} : HIGH: ${coin.highPrice24h} : ` +
`LOW: ${coin.lowPrice24h} : CHANGE: ${coin.changeRate} : UPDATED: ${coin.lastUpdated}`
);
});
}
(async () => {
try {
const coins = await fetchCryptoData();
displayCryptoData(coins);
} catch (error) {
console.error('Error fetching data:', error);
}
})();
-
fetch: This is used to perform the HTTP request. In Node.js,
node-fetch
is a common library for making HTTP requests similar to thefetch
function in browsers. -
interface Coin: This defines the structure of the
Coin
object, providing type safety in TypeScript. - async/await: Asynchronous functions ensure that network operations are non-blocking and handled efficiently.
-
fetchCryptoData: This asynchronous function sends an HTTP request to fetch the JSON data and parses it into an array of
Coin
objects. -
displayCryptoData: This function loops through the list of
Coin
objects and prints the relevant information to the console in a readable format. - Error handling: The script handles errors that may occur during the fetch process and logs them to the console.
-
Install dependencies: In your project directory, install
node-fetch
and TypeScript:
npm install node-fetch@2
npm install --save-dev typescript @types/node-fetch
👨💻 Programmer : PyMmdrza 🌍 Official Website Mmdrza.Com 📧 Email : Pymmdrza@gmail.com
📧 first@programmer.net