track the usage of the api

This commit is contained in:
Hongbo Wu 2024-04-09 18:26:03 +08:00
parent cd6f3e6bbe
commit 67657773cf
2 changed files with 28 additions and 1 deletions

View file

@ -29,7 +29,10 @@ import { logger } from './utils/logger'
import { ReadingProgressDataSource } from './datasources/reading_progress_data_source'
import { createPrometheusExporterPlugin } from '@bmatei/apollo-prometheus-exporter'
import { ApolloServerPlugin } from 'apollo-server-plugin-base'
import { countDailyServiceUsage } from './services/service_usage'
import {
countDailyServiceUsage,
createServiceUsage,
} from './services/service_usage'
const signToken = promisify(jwt.sign)
const pubsub = createPubSubClient()
@ -135,6 +138,21 @@ export function makeApolloServer(app: Express): ApolloServer {
throw new Error('You have reached the daily email limit')
}
}
return {
// track usage of the API
async willSendResponse(requestContext) {
// if the request was successful, increment the user's email sent count
if (
userId &&
query?.includes(action) &&
!requestContext.response.errors &&
!requestContext.response.data?.replyToEmail?.errorCodes
) {
await createServiceUsage(userId, action)
}
},
}
},
}
}

View file

@ -20,3 +20,12 @@ export const countDailyServiceUsage = async (
})
)
}
export const createServiceUsage = async (userId: string, action: string) => {
return authTrx((tx) =>
tx.withRepository(repo).save({
user: { id: userId },
action,
})
)
}