app.ts
Overview
The `app.ts` file is the main entry point of the Proxy API Service. It initializes and configures an Express.js server that serves as a centralized API gateway. Its primary responsibilities include:
Setting up middleware for common request handling and error management.
Defining health check and documentation routes.
Registering application routes.
Integrating proxy handlers for external APIs: CoinGecko, Zerion, and 0x (Zrx).
Serving static assets and Swagger-based API documentation.
Starting the HTTP server on a configured port.
This file orchestrates the overall HTTP API server, delegating specific logic to imported classes and route modules.
Detailed Breakdown
Constants and Imports
PORT: Determines the port on which the Express server listens. Defaults to3000if not set in environment variables.Imports:
Express framework for HTTP server.
Path utilities for static asset resolution.
Swagger UI middleware for interactive API documentation.
Middleware utilities from
@shapeshiftoss/common-apifor standard middleware functions.Logger from
@shapeshiftoss/loggerto log server events.Route registration function and API proxy handler classes (
CoinGecko,Zerion,Zrx).
Logger Initialization
export const logger = new Logger({
namespace: ['unchained', 'proxy', 'api'],
level: process.env.LOG_LEVEL,
})
Purpose: Provides structured logging across the application with configurable log levels and namespaces for contextual filtering.
Usage: Used to log server startup and could be used elsewhere for info, warning, or error reporting.
Express App Setup
const app = express()
Creates an Express application instance that will handle incoming HTTP requests.
Middleware Registration
app.use(...middleware.common())
Applies a set of common middleware functions such as JSON parsing, CORS, request logging, and security headers as defined in the shared middleware utilities.
Ensures consistent request preprocessing.
Health Check Endpoint
app.get('/health', async (_, res) => res.json({ status: 'ok' }))
Provides a simple
/healthroute to verify server availability.Responds with JSON
{ status: 'ok' }.Useful for uptime monitoring and load balancers.
Swagger UI and Static Assets
const options: swaggerUi.SwaggerUiOptions = {
customCss: '.swagger-ui .topbar { display: none }',
customSiteTitle: 'ShapeShift Proxy API Docs',
customfavIcon: '/public/favi-blue.png',
swaggerUrl: '/swagger.json',
}
app.use('/public', express.static(join(__dirname, '../../../../../../coinstacks/common/api/public/')))
app.use('/swagger.json', express.static(join(__dirname, './swagger.json')))
app.use('/docs', swaggerUi.serve, swaggerUi.setup(undefined, options))
Serves static files under
/publicfor assets like favicon.Serves the OpenAPI spec JSON at
/swagger.json.Hosts the Swagger UI documentation at
/docswith customized branding.Provides interactive API documentation for developers.
Route Registration
RegisterRoutes(app)
Imports and registers all routes defined by the project’s route decorators or manual definitions.
Modularizes route management outside of this main file.
External API Proxy Handlers
const coingecko = new CoinGecko()
app.get('/api/v1/markets/*', coingecko.handler.bind(coingecko))
const zerion = new Zerion()
app.get('/api/v1/zerion/*', zerion.handler.bind(zerion))
const zrx = new Zrx()
app.get('/api/v1/zrx/*', zrx.handler.bind(zrx))
Instantiates proxy clients for external APIs:
CoinGecko for market data.
Zerion for portfolio/token data.
0x (Zrx) for liquidity and swap quotes.
Routes with matching path prefixes forward requests to the respective proxy handler methods.
bind()ensures the correctthiscontext in handlers.
Root Route Redirect
app.get('/', async (_, res) => {
res.redirect('/docs')
})
Redirects requests to the root URL
/to the API documentation page/docs.Improves developer experience by guiding users to API info.
Error Handling Middleware
app.use(middleware.errorHandler, middleware.notFoundHandler)
Registers middleware for:
Handling errors generated in the request pipeline.
Catching 404 Not Found for unmatched routes.
Ensures consistent error response formatting.
Server Startup
app.listen(PORT, () => logger.info('Server started'))
Starts the HTTP server and begins listening on the configured port.
Logs a message indicating successful server startup.
Classes and Functions
logger: Logger
An instance of the
Loggerclass for logging messages.Configured with namespaces and log levels.
Usage Example:
logger.info('Server started')
logger.error('An unexpected error occurred')
Express Routes and Handlers
All route handlers are defined as inline functions or bound methods from proxy classes.
Health Route Handler: Returns server status.
Proxy Handlers (
CoinGecko.handler,Zerion.handler,Zrx.handler): Handle API proxy requests.Root Handler: Redirects to documentation.
Error Handlers: Manage errors and 404s.
Important Implementation Details
Middleware Usage: Common middleware is applied globally for request parsing and security.
Proxy Handler Binding: Proxy handler methods are bound to instances to preserve
thiscontext, a common pitfall in Express.Static File Serving: Uses absolute paths resolved relative to
__dirnamefor serving public assets and Swagger specs.Swagger UI Customization: Custom CSS hides the default topbar; custom favicon and site title personalize the docs.
Fallback Routes: Unmatched root route redirects to docs, and 404 middleware handles unknown paths gracefully.
Interaction with Other Files
routes.ts:RegisterRoutes(app)imports and registers all application routes.Proxy Classes (
coingecko.ts,zerion.ts,zrx.ts): Handle forwarding, caching, and authentication for their respective external APIs.@shapeshiftoss/common-apiand@shapeshiftoss/logger: Provide shared middleware and logging utilities.Static assets and Swagger spec: Located outside this file but served through configured static routes.
`app.ts` acts as the central coordinator, tying together middleware, routes, API proxies, logging, and documentation into a cohesive HTTP service.
Usage Example
Start the server:
PORT=8080 LOG_LEVEL=info node dist/app.js
Check health:
curl http://localhost:8080/health
# Response: { "status": "ok" }
Access API documentation:
Open browser at http://localhost:8080/docs
Proxy a CoinGecko market request:
curl http://localhost:8080/api/v1/markets/coins/list
Mermaid Class Diagram
This diagram shows the structure of the main components instantiated and used in `app.ts` along with their key methods and properties.
classDiagram
class ExpressApp {
+use()
+get()
+listen()
}
class Logger {
+info(msg: string)
+error(msg: string)
}
class CoinGecko {
+handler(req, res)
}
class Zerion {
+handler(req, res)
}
class Zrx {
+handler(req, res)
}
ExpressApp o-- Logger : uses
ExpressApp o-- CoinGecko : uses
ExpressApp o-- Zerion : uses
ExpressApp o-- Zrx : uses
Summary
The `app.ts` file is the backbone of the Proxy API Service, setting up an Express server that unifies multiple external API proxies, health checks, documentation, and error handling into a single, manageable server. It leverages modular middleware and imported proxy classes to maintain clean separation of concerns while providing a consistent API surface for clients.