coingecko.ts


Overview

The `coingecko.ts` file implements a proxy client for the CoinGecko API, designed to forward incoming HTTP requests from an Express server to the CoinGecko Pro API. It manages API authentication using an API key, caches responses in-memory to reduce redundant external API calls, and gracefully handles errors. This proxy functionality enables clients to access CoinGecko market data securely and efficiently through an internal unified API endpoint, while abstracting away direct interaction with CoinGecko's external API.


Classes and Types

type RequestCache

type RequestCache = Partial<Record<string, AxiosResponse>>

class CoinGecko

Description

Encapsulates the logic for proxying requests to the CoinGecko Pro API. It maintains an Axios HTTP client instance configured with the required API key and an in-memory cache of recent responses keyed by request URLs. The class exposes a single asynchronous method `handler` intended to be used as an Express route handler.

Properties

Property

Type

Description

`axiosInstance`

`Axios`

Axios HTTP client configured with CoinGecko API key.

`requestCache`

`RequestCache`

In-memory cache mapping request URLs to Axios responses.

Constructor

constructor()

Methods

async handler(req: Request, res: Response): Promise<void>
import express from 'express'
import { CoinGecko } from './coingecko'

const app = express()
const coingecko = new CoinGecko()

// Route proxying CoinGecko API market data requests
app.get('/api/v1/markets/*', coingecko.handler.bind(coingecko))

app.listen(3000, () => console.log('Server running on port 3000'))

Important Implementation Details


Interaction with Other System Components


Visual Diagram

classDiagram
    class CoinGecko {
        -axiosInstance: Axios
        -requestCache: RequestCache
        +constructor()
        +handler(req: Request, res: Response): Promise<void>
    }

Summary

`coingecko.ts` provides a robust and efficient proxy mechanism for CoinGecko’s Pro API within a larger Proxy API Service. It abstracts API key management and network requests, implements caching to improve performance and reduce external calls, and exposes a consistent interface for clients. The file's design aligns with the system's goals of modularity, security, and scalability in handling multiple third-party blockchain data providers.


Appendix: Key Code Snippet from handler Method

async handler(req: Request, res: Response): Promise<void> {
  const url = req.url.substring('/api/v1/markets/'.length)

  const cachedResponse = this.requestCache[req.url]
  if (cachedResponse) {
    Object.entries(cachedResponse.headers).forEach(([k, v]) => res.set(k, v))
    res.set('X-Cache', 'HIT').status(cachedResponse.status).send(cachedResponse.data)
    return
  }

  res.set('X-Cache', 'MISS')

  try {
    const response = await this.axiosInstance.get(`${BASE_URL}${url}`)
    this.requestCache[req.url] = response
    Object.entries(response.headers).forEach(([k, v]) => res.set(k, v))
    res.status(response.status).send(response.data)
  } catch (err) {
    if (isAxiosError(err)) {
      res.status(err.response?.status ?? 500).send(err.response?.data || 'Internal Server Error')
    } else if (err instanceof Error) {
      res.status(500).send(err.message || 'Internal Server Error')
    } else {
      res.status(500).send('Internal Server Error')
    }
  } finally {
    setInterval(() => delete this.requestCache[req.url], CACHE_TTL_MS)
  }
}

This concludes the comprehensive documentation for the `coingecko.ts` file.