Skip to content

Commit

Permalink
feat: routes can define their cost
Browse files Browse the repository at this point in the history
  • Loading branch information
gowthamsundaresan committed Dec 16, 2024
1 parent 26d1863 commit f5526de
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 21 deletions.
19 changes: 19 additions & 0 deletions packages/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import cors from 'cors'
import apiRouter from './routes'
import { EigenExplorerApiError, handleAndReturnErrorResponse } from './schema/errors'
import { startUserRequestsSync } from './utils/userRequestsSync'
import { requestsStore } from './utils/authCache'

const PORT = process.env.PORT ? Number.parseInt(process.env.PORT) : 3002

Expand All @@ -23,6 +24,24 @@ app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())

// Route cost increment
app.use((req, res, next) => {
res.on('finish', () => {
try {
if (res.statusCode >= 200 && res.statusCode < 300) {
const apiToken = req.header('X-API-Token')
if (apiToken) {
const key = `apiToken:${apiToken}:newRequests`
const currentCalls: number = requestsStore.get(key) || 0
const cost = req.cost || 1
requestsStore.set(key, currentCalls + cost)
}
}
} catch {}
})
next()
})

// Routes
app.use('/', apiRouter)

Expand Down
21 changes: 0 additions & 21 deletions packages/api/src/utils/authMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,27 +151,6 @@ export const rateLimiter = (req: Request, res: Response, next: NextFunction) =>

// Apply rate limiting
const limiter = rateLimiters[accessLevel]

// Increment `requestsStore` for successful requests
const originalEnd = res.end

// biome-ignore lint/suspicious/noExplicitAny: <explanation>
res.end = function (chunk?: any, encoding?: any, cb?: any) {
try {
if (res.statusCode >= 200 && res.statusCode < 300) {
const apiToken = req.header('X-API-Token')
if (apiToken) {
const key = `apiToken:${apiToken}:newRequests`
const currentCalls: number = requestsStore.get(key) || 0
requestsStore.set(key, currentCalls + 1)
}
}
} catch {}

res.end = originalEnd
return originalEnd.call(this, chunk, encoding, cb)
}

return limiter(req, res, next)
}

Expand Down
1 change: 1 addition & 0 deletions packages/api/src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ declare global {
namespace Express {
interface Request {
accessLevel?: number
cost?: number
}
}
}
15 changes: 15 additions & 0 deletions packages/api/src/utils/routeCost.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { NextFunction, Request, Response } from 'express'

/**
* Middleware function to be used when defining API routes and pointing them to their internal functions
* If not set, cost calculator after route completion will consider cost as 1
*
* @param cost
* @returns
*/
export function setRouteCost(cost: number) {
return (req: Request, _res: Response, next: NextFunction) => {
req.cost = cost
next()
}
}

0 comments on commit f5526de

Please sign in to comment.