Return

All tests / src/pages/api xrp.ts

95.45% Statements 21/22
85.71% Branches 6/7
100% Functions 1/1
95.23% Lines 20/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55  1x 1x 1x               4x 4x   4x                     4x 1x     3x   3x 1x     2x 2x 2x 2x   2x 2x           2x     2x 2x      
import type { NextApiRequest, NextApiResponse } from 'next';
import console from '@/helpers/console';
import allowCors from '../../helpers/cors';
import { CACHE, fetchWithTimeout } from '@/helpers/http';
 
/**
 * @description Get the price of XRP in EUR using CoinGecko API
 *
 * @returns {Promise<{ price: string; todaySummary: string; todayPorcentage: string } | { error: string }>}
 * @example https://xabierlameiro.com/api/xrp
 */
export default allowCors(async function handler(_req: NextApiRequest, res: NextApiResponse) {
    try {
        // Using CoinGecko API which is more reliable than scraping Google
        const response = await fetchWithTimeout(
            'https://api.coingecko.com/api/v3/simple/price?ids=ripple&vs_currencies=eur&include_24hr_change=true',
            {
                method: 'GET',
                headers: {
                    Accept: 'application/json',
                    'User-Agent': 'xabierlameiro.com',
                },
            }
        );
 
        if (!response.ok) {
            throw new Error(`CoinGecko API error: ${response.status}`);
        }
 
        const data = await response.json();
 
        if (!data.ripple) {
            throw new Error('XRP data not found');
        }
 
        const price = parseFloat(data.ripple.eur.toFixed(4));
        const change24h = data.ripple.eur_24h_change;
        const todayPorcentage = `${change24h > 0 ? '+' : ''}${change24h.toFixed(2)}%`;
        const todaySummary = change24h > 0 ? 'Up' : 'Down';
 
        res.setHeader('Cache-Control', CACHE.price);
        res.status(200).json({
            price,
            todaySummary,
            todayPorcentage,
        });
    } catch (err) {
        Iif (process.env.NODE_ENV === 'development') {
            console.error('XRP API Error:', err);
        }
        res.setHeader('Cache-Control', CACHE.error);
        res.status(500).json({ error: 'Internal server error' });
    }
});