Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion modules/express/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@
"morgan": "^1.9.1",
"proxy-agent": "6.4.0",
"proxyquire": "^2.1.3",
"superagent": "^9.0.1"
"superagent": "^9.0.1",
"@api-ts/io-ts-http": "^3.2.1",
"@api-ts/typed-express-router": "^1.1.13"
},
"devDependencies": {
"@bitgo/public-types": "5.1.0",
Expand Down
35 changes: 31 additions & 4 deletions modules/express/src/clientRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,25 @@ import { handleUpdateLightningWalletCoinSpecific } from './lightning/lightningWa
import { ProxyAgent } from 'proxy-agent';
import { isLightningCoinName } from '@bitgo/abstract-lightning';
import { handleLightningWithdraw } from './lightning/lightningWithdrawRoutes';
import createExpressRouter from './typedRoutes';
import { ExpressApiRouteRequest } from './typedRoutes/api';
import { TypedRequestHandler, WrappedRequest, WrappedResponse } from '@api-ts/typed-express-router';

const { version } = require('bitgo/package.json');
const pjson = require('../package.json');
const debug = debugLib('bitgo:express');

const BITGOEXPRESS_USER_AGENT = `BitGoExpress/${pjson.version} BitGoJS/${version}`;

function handlePing(req: express.Request, res: express.Response, next: express.NextFunction) {
function handlePing(
req: ExpressApiRouteRequest<'express.ping', 'get'>,
res: express.Response,
next: express.NextFunction
) {
return req.bitgo.ping();
}

function handlePingExpress(req: express.Request) {
function handlePingExpress(req: ExpressApiRouteRequest<'express.pingExpress', 'get'>) {
return {
status: 'express server is ok!',
};
Expand Down Expand Up @@ -1358,6 +1365,23 @@ export function promiseWrapper(promiseRequestHandler: RequestHandler) {
};
}

export function typedPromiseWrapper(promiseRequestHandler: TypedRequestHandler) {
return async function (req: WrappedRequest, res: WrappedResponse, next: express.NextFunction) {
debug(`handle: ${req.method} ${req.originalUrl}`);
try {
const result = await promiseRequestHandler(req, res, next);
if (typeof result === 'object' && result !== null && 'body' in result && 'status' in result) {
const { status, body } = result as { status: number; body: unknown };
res.status(status).send(body);
} else {
res.status(200).send(result);
}
} catch (e) {
handleRequestHandlerError(res, e);
}
};
}

export function createCustomSigningFunction(externalSignerUrl: string): CustomSigningFunction {
return async function (params): Promise<SignedTransaction> {
const { body: signedTx } = await retryPromise(
Expand Down Expand Up @@ -1530,8 +1554,11 @@ export function setupAPIRoutes(app: express.Application, config: Config): void {
// ping
// /api/v[12]/pingexpress is the only exception to the rule above, as it explicitly checks the health of the
// express server without running into rate limiting with the BitGo server.
app.get('/api/v[12]/ping', prepareBitGo(config), promiseWrapper(handlePing));
app.get('/api/v[12]/pingexpress', promiseWrapper(handlePingExpress));
const router = createExpressRouter();
app.use(router);

router.get('express.ping', [prepareBitGo(config), typedPromiseWrapper(handlePing)]);
router.get('express.pingExpress', [typedPromiseWrapper(handlePingExpress)]);

// auth
app.post('/api/v[12]/user/login', parseBody, prepareBitGo(config), promiseWrapper(handleLogin));
Expand Down
18 changes: 18 additions & 0 deletions modules/express/src/typedRoutes/api/common/ping.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as t from 'io-ts';
import { httpRoute, httpRequest } from '@api-ts/io-ts-http';
import { BitgoExpressError } from '../../schemas/error';

/**
* Ping
*
* @operationId express.ping
*/
export const GetPing = httpRoute({
path: '/api/v[12]/ping',
method: 'GET',
request: httpRequest({}),
response: {
200: t.type({}),
404: BitgoExpressError,
},
});
18 changes: 18 additions & 0 deletions modules/express/src/typedRoutes/api/common/pingExpress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import * as t from 'io-ts';
import { httpRoute, httpRequest } from '@api-ts/io-ts-http';
import { BitgoExpressError } from '../../schemas/error';

/**
* Ping Express
*
* @operationId express.pingExpress
*/
export const GetPingExpress = httpRoute({
path: '/api/v[12]/pingexpress',
method: 'GET',
request: httpRequest({}),
response: {
200: t.type({ status: t.string }),
404: BitgoExpressError,
},
});
23 changes: 23 additions & 0 deletions modules/express/src/typedRoutes/api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as t from 'io-ts';
import { apiSpec } from '@api-ts/io-ts-http';
import * as express from 'express';

import { GetPing } from './common/ping';
import { GetPingExpress } from './common/pingExpress';

export const ExpressApi = apiSpec({
'express.ping': {
get: GetPing,
},
'express.pingExpress': {
get: GetPingExpress,
},
});

export type ExpressApi = typeof ExpressApi;

type ExtractDecoded<T> = T extends t.Type<any, infer O, any> ? O : never;
export type ExpressApiRouteRequest<
ApiName extends keyof ExpressApi,
Method extends keyof ExpressApi[ApiName]
> = ExpressApi[ApiName][Method] extends { request: infer R } ? express.Request & { decoded: ExtractDecoded<R> } : never;
8 changes: 8 additions & 0 deletions modules/express/src/typedRoutes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createRouter, WrappedRouter } from '@api-ts/typed-express-router';

import { ExpressApi } from './api';

export default function (): WrappedRouter<ExpressApi> {
const router: WrappedRouter<ExpressApi> = createRouter(ExpressApi);
return router;
}
8 changes: 8 additions & 0 deletions modules/express/src/typedRoutes/schemas/error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import * as t from 'io-ts';

export const BitgoExpressError = t.type({
message: t.string,
name: t.string,
bitgoJsVersion: t.string,
bitgoExpressVersion: t.string,
Comment on lines +4 to +7
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these values always present on the response? should some of these be optional?

Copy link
Contributor Author

@kaustubhbitgo kaustubhbitgo Aug 1, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have express error type in clientRoutes catch all handler.

  result = _.extend({}, result, {
    message: err.message,
    name: err.name || 'BitGoExpressError',
    bitgoJsVersion: version,
    bitgoExpressVersion: pjson.version,
  });

});
1 change: 1 addition & 0 deletions modules/express/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"compilerOptions": {
"outDir": "./dist",
"rootDir": ".",
"allowSyntheticDefaultImports": true,
"typeRoots": ["./types", "../../types", "./node_modules/@types", "../../node_modules/@types"]
},
"include": ["src/**/*", "test/**/*", "package.json"],
Expand Down
Loading