Skip to content

Commit

Permalink
Typescriptify Axios request time interceptors
Browse files Browse the repository at this point in the history
  • Loading branch information
aasseman committed Jun 23, 2022
1 parent 691f486 commit ba8cda6
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions packages/indexer-service/src/queries.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import axios, { AxiosInstance, AxiosResponse } from 'axios'
import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios'

import { Logger, Metrics, Eventual } from '@graphprotocol/common-ts'
import {
Expand All @@ -20,6 +20,15 @@ export interface PaidQueryProcessorOptions {
receiptManager: ReceiptManager
}

interface AxiosRequestConfigWithTime extends AxiosRequestConfig {
meta?: { requestStartedAt?: number }
}

interface AxiosResponseWithTime extends AxiosResponse {
responseTime?: number
config: AxiosRequestConfigWithTime
}

export class QueryProcessor implements QueryProcessorInterface {
logger: Logger
metrics: Metrics
Expand Down Expand Up @@ -54,21 +63,25 @@ export class QueryProcessor implements QueryProcessorInterface {

// Set up Axios for request response time measurement
// https://sabljakovich.medium.com/axios-response-time-capture-and-log-8ff54a02275d
this.graphNode.interceptors.request.use(function (x: any) {
this.graphNode.interceptors.request.use(function (x: AxiosRequestConfigWithTime) {
// to avoid overwriting if another interceptor
// already defined the same object (meta)
x.meta = x.meta || {}
x.meta.requestStartedAt = new Date().getTime()
return x
})
this.graphNode.interceptors.response.use(
function (x: any) {
x.responseTime = new Date().getTime() - x.config.meta.requestStartedAt
function (x: AxiosResponseWithTime) {
if (x.config.meta?.requestStartedAt !== undefined) {
x.responseTime = new Date().getTime() - x.config.meta?.requestStartedAt
}
return x
},
// Handle 4xx & 5xx responses
function (x: any) {
x.responseTime = new Date().getTime() - x.config.meta.requestStartedAt
function (x: AxiosResponseWithTime) {
if (x.config.meta?.requestStartedAt !== undefined) {
x.responseTime = new Date().getTime() - x.config.meta.requestStartedAt
}
throw x
},
)
Expand Down Expand Up @@ -134,7 +147,7 @@ export class QueryProcessor implements QueryProcessorInterface {
deployment: subgraphDeploymentID.ipfsHash,
fees: parsedReceipt.fees.toBigInt().toString(),
query: query,
responseTime: (response as any).responseTime,
responseTime: (response as AxiosResponseWithTime).responseTime ?? null,
})

return {
Expand Down

0 comments on commit ba8cda6

Please sign in to comment.