Skip to content

Commit

Permalink
feat(rest-api): Adds winston logger [SLT-271] (#3216)
Browse files Browse the repository at this point in the history
* Adds winston logger
* Adds req.query to logs
* Adds route logging
  • Loading branch information
abtestingalpha authored Oct 3, 2024
1 parent 9c1dc5b commit b1049e8
Show file tree
Hide file tree
Showing 16 changed files with 339 additions and 21 deletions.
2 changes: 2 additions & 0 deletions packages/rest-api/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ module.exports = {
rules: {
'guard-for-in': 'off',
'jsdoc/check-indentation': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-unused-vars': 'off',
},
},
],
Expand Down
3 changes: 2 additions & 1 deletion packages/rest-api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
"jest": "^29.7.0",
"lodash": "^4.17.21",
"supertest": "^6.3.3",
"typescript": "^4.8.3"
"typescript": "^4.8.3",
"winston": "^3.14.2"
},
"description": "A node.js project exposing a rest api for synapse sdk quotes",
"devDependencies": {
Expand Down
46 changes: 44 additions & 2 deletions packages/rest-api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,44 @@ import swaggerUi from 'swagger-ui-express'

import { specs } from './swagger'
import routes from './routes'
import { logger } from './middleware/logger'

const app = express()
const port = process.env.PORT || 3000

app.use(express.json())

app.use((req, res, next) => {
logger.info('Incoming request', {
method: req.method,
path: req.path,
query: req.query,
body: req.method === 'POST' || req.method === 'PUT' ? req.body : undefined,
})

const originalPath = req.path

const originalJson = res.json
res.json = function (body) {
logger.info('Outgoing response', {
method: req.method,
path: originalPath,
statusCode: res.statusCode,
body:
originalPath === '/' || originalPath.toLowerCase() === '/tokenlist'
? '[truncated for size]'
: body,
})
return originalJson.call(this, body)
}

next()
})

app.listen(port, () => {
logger.info(`Server is listening on port ${port}`)
})

app.use(
'/api-docs',
(_req, res, next) => {
Expand All @@ -27,6 +59,16 @@ app.use(

app.use('/', routes)

export const server = app.listen(port, () => {
console.log(`Server listening at ${port}`)
app.use((err, _req, res, _next) => {
logger.error(`Express error: ${err.message}`, { stack: err.stack })
res.status(500).json({ error: 'Something went wrong', details: err.message })
})

process.on('uncaughtException', (err) => {
logger.error(`Uncaught Exception: ${err.message}`, { stack: err.stack })
process.exit(1)
})

process.on('unhandledRejection', (reason, promise) => {
logger.error('Unhandled Rejection at:', promise, 'reason:', reason)
})
11 changes: 11 additions & 0 deletions packages/rest-api/src/controllers/bridgeController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { parseUnits } from '@ethersproject/units'
import { formatBNToString } from '../utils/formatBNToString'
import { Synapse } from '../services/synapseService'
import { tokenAddressToToken } from '../utils/tokenAddressToToken'
import { logger } from '../middleware/logger'

export const bridgeController = async (req, res) => {
const errors = validationResult(req)
Expand Down Expand Up @@ -53,8 +54,18 @@ export const bridgeController = async (req, res) => {
),
}
})

logger.info(`Successful bridgeController response`, {
payload,
query: req.query,
})
res.json(payload)
} catch (err) {
logger.error(`Error in bridgeController`, {
query: req.query,
error: err.message,
stack: err.stack,
})
res.status(500).json({
error: 'An unexpected error occurred in /bridge. Please try again later.',
details: err.message,
Expand Down
14 changes: 13 additions & 1 deletion packages/rest-api/src/controllers/bridgeLimitsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { parseUnits } from '@ethersproject/units'
import { Synapse } from '../services/synapseService'
import { tokenAddressToToken } from '../utils/tokenAddressToToken'
import { formatBNToString } from '../utils/formatBNToString'
import { logger } from '../middleware/logger'

export const bridgeLimitsController = async (req, res) => {
const errors = validationResult(req)
Expand Down Expand Up @@ -94,11 +95,22 @@ export const bridgeLimitsController = async (req, res) => {
minAmountOriginQueryTokenOutInfo.decimals
)

return res.json({
const payload = {
maxOriginAmount,
minOriginAmount,
}

logger.info(`Succesful bridgeLimitsController response`, {
query: req.query,
payload,
})
return res.json(payload)
} catch (err) {
logger.error(`Error in bridgeLimitsController`, {
query: req.query,
error: err.message,
stack: err.stack,
})
res.status(500).json({
error:
'An unexpected error occurred in /bridgeLimits. Please try again later.',
Expand Down
11 changes: 11 additions & 0 deletions packages/rest-api/src/controllers/bridgeTxInfoController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { parseUnits } from '@ethersproject/units'

import { Synapse } from '../services/synapseService'
import { tokenAddressToToken } from '../utils/tokenAddressToToken'
import { logger } from '../middleware/logger'

export const bridgeTxInfoController = async (req, res) => {
const errors = validationResult(req)
Expand Down Expand Up @@ -51,8 +52,18 @@ export const bridgeTxInfoController = async (req, res) => {
return txInfo
})
)

logger.info(`Successful bridgeTxInfoController response`, {
query: req.query,
txInfoArray,
})
res.json(txInfoArray)
} catch (err) {
logger.error(`Error in bridgeTxInfoController`, {
query: req.query,
error: err.message,
stack: err.stack,
})
res.status(500).json({
error:
'An unexpected error occurred in /bridgeTxInfo. Please try again later.',
Expand Down
33 changes: 30 additions & 3 deletions packages/rest-api/src/controllers/bridgeTxStatusController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ethers } from 'ethers'

import { Synapse } from '../services/synapseService'
import { getTokenDecimals } from '../utils/getTokenDecimals'
import { logger } from '../middleware/logger'

export const bridgeTxStatusController = async (req, res) => {
const errors = validationResult(req)
Expand Down Expand Up @@ -56,20 +57,46 @@ export const bridgeTxStatusController = async (req, res) => {
const tokenDecimals = getTokenDecimals(toInfo.chainID, tokenAddress)
const formattedValue = ethers.utils.formatUnits(value, tokenDecimals)

res.json({
const payload = {
status,
toInfo: {
...restToInfo,
formattedValue: `${formattedValue}`,
},
}

logger.info(`Successful bridgeTxStatusController response`, {
query: req.query,
payload,
})
res.json(payload)
} else {
res.json({ status, toInfo: null })
const payload = {
status,
toInfo: null,
}

logger.info(`Successful bridgeTxStatusController response`, {
query: req.query,
payload,
})
res.json(payload)
}
} else {
res.json({ status })
const payload = { status }

logger.info(`Successful bridgeTxStatusController response`, {
query: req.query,
payload,
})
res.json(payload)
}
} catch (err) {
logger.error(`Error in bridgeTxStatusController`, {
query: req.query,
error: err.message,
stack: err.stack,
})
res.status(500).json({
error:
'An unexpected error occurred in /bridgeTxStatus. Please try again later.',
Expand Down
15 changes: 13 additions & 2 deletions packages/rest-api/src/controllers/destinationTokensController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { validationResult } from 'express-validator'

import { tokenAddressToToken } from '../utils/tokenAddressToToken'
import { BRIDGE_ROUTE_MAPPING } from '../utils/bridgeRouteMapping'
import { logger } from '../middleware/logger'

export const destinationTokensController = async (req, res) => {
const errors = validationResult(req)
Expand All @@ -16,10 +17,20 @@ export const destinationTokensController = async (req, res) => {

const constructedKey = `${fromTokenInfo.symbol}-${fromChain}`

const options = BRIDGE_ROUTE_MAPPING[constructedKey]
const payload = BRIDGE_ROUTE_MAPPING[constructedKey]

res.json(options)
logger.info(`Successful destinationTokensController response`, {
query: req.query,
payload,
})

res.json(payload)
} catch (err) {
logger.error(`Error in destinationTokensController`, {
query: req.query,
error: err.message,
stack: err.stack,
})
res.status(500).json({
error:
'An unexpected error occurred in /destinationTokens. Please try again later.',
Expand Down
25 changes: 23 additions & 2 deletions packages/rest-api/src/controllers/destinationTxController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ethers } from 'ethers'

import { getTokenDecimals } from '../utils/getTokenDecimals'
import { tokenAddressToToken } from '../utils/tokenAddressToToken'
import { logger } from '../middleware/logger'

export const destinationTxController = async (req, res) => {
const errors = validationResult(req)
Expand Down Expand Up @@ -54,19 +55,39 @@ export const destinationTxController = async (req, res) => {
const tokenDecimals = getTokenDecimals(chainID, tokenAddress)
const formattedValue = ethers.utils.formatUnits(value, tokenDecimals)

res.json({
const payload = {
status: 'completed',
toInfo: {
chainID,
...restToInfo,
tokenSymbol: tokenInfo ? tokenInfo?.symbol : null,
formattedValue: `${formattedValue}`,
},
}

logger.info(`Successful destinationTxController response`, {
query: req.query,
payload,
})
res.json(payload)
} else {
res.json({ status: 'pending', toInfo: null })
const payload = {
status: 'pending',
toInfo: null,
}

logger.info(`Successful destinationTxController response`, {
query: req.query,
payload,
})
res.json(payload)
}
} catch (err) {
logger.error(`Error in destinationTxController`, {
query: req.query,
error: err.message,
stack: err.stack,
})
res.status(500).json({
error:
'An unexpected error occurred in /destinationTx. Please try again later.',
Expand Down
15 changes: 12 additions & 3 deletions packages/rest-api/src/controllers/indexController.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import * as tokensList from '../constants/bridgeable'
import { CHAINS_ARRAY } from '../constants/chains'
import { logger } from '../middleware/logger'

export const indexController = async (_req, res) => {
export const indexController = async (req, res) => {
try {
const tokensWithChains = Object.values(tokensList).map((token: any) => ({
symbol: token.symbol,
Expand All @@ -13,15 +14,23 @@ export const indexController = async (_req, res) => {
),
}))

res.json({
const payload = {
message: 'Welcome to the Synapse REST API for swap and bridge quotes',
availableChains: CHAINS_ARRAY.map((chain) => ({
name: chain.name,
id: chain.id,
})),
availableTokens: tokensWithChains,
})
}

logger.info(`Successful indexController response`, { query: req.query })
res.json(payload)
} catch (err) {
logger.error(`Error in indexController`, {
query: req.query,
error: err.message,
stack: err.stack,
})
res.status(500).json({
error: 'An unexpected error occurred in /. Please try again later.',
details: err.message,
Expand Down
14 changes: 13 additions & 1 deletion packages/rest-api/src/controllers/swapController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { BigNumber } from '@ethersproject/bignumber'

import { Synapse } from '../services/synapseService'
import { tokenAddressToToken } from '../utils/tokenAddressToToken'
import { logger } from '../middleware/logger'

export const swapController = async (req, res) => {
const errors = validationResult(req)
Expand All @@ -29,11 +30,22 @@ export const swapController = async (req, res) => {
toTokenInfo.decimals
)

res.json({
const payload = {
...quote,
maxAmountOut: formattedMaxAmountOut,
}

logger.info(`Successful swapController response`, {
query: req.query,
payload,
})
res.json(payload)
} catch (err) {
logger.error(`Error in swapController`, {
query: req.query,
error: err.message,
stack: err.stack,
})
res.status(500).json({
error: 'An unexpected error occurred in /swap. Please try again later.',
details: err.message,
Expand Down
Loading

0 comments on commit b1049e8

Please sign in to comment.