zerion.ts
Overview
The `zerion.ts` file implements a proxy client class named `Zerion` for interacting with the Zerion API. Its primary purpose is to forward incoming HTTP requests from the internal API layer to the Zerion external API while handling:
Authentication via an API key.
Response caching to reduce redundant external calls.
Transparent forwarding of response status codes and headers.
Graceful error handling.
This proxy enables clients to access Zerion portfolio and token-related data through a unified internal endpoint (`/api/v1/zerion/*`), abstracting away direct dependencies on Zerion's API structure and authentication.
Classes and Functions
class Zerion
A proxy client class for the Zerion API that manages request forwarding with authentication and caching.
Properties
private axiosInstance: Axios
An Axios HTTP client instance pre-configured with the Zerion API key for authenticated requests.private requestCache: RequestCache
An in-memory cache object storing recent Axios responses keyed by request URL to optimize performance.
Constants Used
ZERION_API_KEY(string)
API key loaded from environment variableZERION_API_KEY. Required for authentication with Zerion API.CACHE_TTL_MS(number)
Cache time-to-live in milliseconds (60,000 ms = 60 seconds). Cached responses expire after this duration.BASE_URL (string)
Base URL for Zerion API:'https://api.zerion.io/v1/'.
Constructor
constructor()
Initializes the `Zerion` instance by:
Validating that
ZERION_API_KEYis set (throws if missing).Creating an Axios instance with the
Authorizationheader set toBasic ${ZERION_API_KEY}.Initializing an empty request cache.
Methods
async handler(req: Request, res: Response): Promise<void>
Handles an incoming Express HTTP request and proxies it to the Zerion API with caching.
Parameters
req: Request
The Express request object representing the incoming HTTP request.res: Response
The Express response object used to send the proxied response back to the client.
Returns
Promise<void>
This asynchronous function sends the HTTP response directly; it does not return any value.
Description
Request URL Processing:
Extracts the sub-path to forward by removing the prefix/api/v1/zerion/from the incoming request URL.Cache Check:
Checks if a cached AxiosResponse exists for the full request URL.Cache Hit:
Sets all cached response headers on the Express response.
Adds the header
X-Cache: HITto indicate a cache hit.Returns the cached response status and data immediately.
Cache Miss:
Sets header
X-Cache: MISSto indicate no cached response.Forwards the request to Zerion API using the Axios instance.
Caches the received response keyed by the full request URL.
Copies all response headers from Zerion API to the Express response.
Sends the response status and data to the client.
Error Handling:
Catches Axios errors or generic errors and forwards appropriate HTTP status codes and error messages to the client. If the error is unknown, responds with HTTP 500 Internal Server Error.Cache Expiry:
UsessetIntervalto schedule deletion of the cache entry for the request URL after the TTL expires (CACHE_TTL_MS). Note that the current implementation callssetIntervalrepeatedly on each request, which may cause unintended repeated cache deletions.
Usage Example
import express from 'express'
import { Zerion } from './zerion'
const app = express()
const zerion = new Zerion()
// Bind the proxy handler to maintain `this` context
app.get('/api/v1/zerion/*', zerion.handler.bind(zerion))
Clients can then call internal endpoints like:
GET /api/v1/zerion/portfolio/0x1234567890abcdef
which will be forwarded to:
GET https://api.zerion.io/v1/portfolio/0x1234567890abcdef
with caching and authentication handled transparently.
Important Implementation Details
Authentication:
The Axios client sends theAuthorizationheader with the API key encoded as Basic Auth (Basic ${ZERION_API_KEY}) on every request.Caching Strategy:
Uses an in-memory object keyed by the full request URL.
Stores the entire AxiosResponse object, including headers, status, and data.
TTL is 60 seconds per cached entry.
Sets cache expiration via
setIntervalinside the handler method, which may unintentionally create multiple intervals for the same URL if requests repeat frequently. A more appropriate approach would besetTimeoutor a centralized cache eviction mechanism.
Error Handling:
Differentiates Axios errors (
isAxiosError) to extract HTTP status and response data.Falls back to generic 500 status on unexpected errors.
Sends error details to the client to maintain transparency.
Response Headers Preservation:
All headers from the Zerion API response are copied to the outgoing Express response to maintain API semantics.
Interaction with Other System Parts
Express App Routing:
TheZerionclass'shandlermethod is intended to be bound and used as an Express route handler for paths beginning with/api/v1/zerion/*.Environment Configuration:
Requires the environment variableZERION_API_KEYto be set prior to application startup.Caching Coordination:
Works alongside similar proxy classes for CoinGecko (coingecko.ts) and 0x (zrx.ts), which follow a similar pattern of request forwarding and caching.Proxy API Service Role:
Forms part of the broader Proxy API Service that unifies access to multiple external APIs with consistent authentication, caching, and error handling.
Visual Diagram: Class Diagram of Zerion
classDiagram
class Zerion {
-axiosInstance: Axios
-requestCache: RequestCache
+constructor()
+handler(req: Request, res: Response): Promise<void>
}
Summary
The `zerion.ts` file encapsulates the Zerion API proxying functionality in the `Zerion` class. It simplifies client interactions by:
Handling API key authentication internally.
Caching responses to improve performance and reduce external API calls.
Transparently forwarding request/response headers and status codes.
Providing a unified internal API endpoint under
/api/v1/zerion/*.
This design promotes modularity, security (by not exposing API keys), and scalability within the larger Proxy API Service architecture.