@@ -2,13 +2,14 @@ import { FastifyInstance, FastifyPluginOptions } from 'fastify';
2
2
import fp from 'fastify-plugin' ;
3
3
import appInsights from 'applicationinsights' ;
4
4
5
- // based on https://github.com/microsoft/ApplicationInsights-node.js/issues/627#issuecomment-2194527018
6
5
declare module 'fastify' {
7
6
export interface FastifyRequest {
7
+ // here we augment FastifyRequest interface as advised here: https://fastify.dev/docs/latest/Reference/Hooks/#using-hooks-to-inject-custom-properties
8
8
app : { start : number } ;
9
9
}
10
10
}
11
11
12
+ // based on https://github.com/microsoft/ApplicationInsights-node.js/issues/627#issuecomment-2194527018
12
13
export const appInsightsPlugin = fp ( async ( fastify : FastifyInstance , options : FastifyPluginOptions ) => {
13
14
if ( ! options . client ) {
14
15
console . log ( 'App Insights not configured' ) ;
@@ -18,12 +19,15 @@ export const appInsightsPlugin = fp(async (fastify: FastifyInstance, options: Fa
18
19
const client : appInsights . TelemetryClient = options . client ;
19
20
const urlsToIgnore = options . urlsToIgnore || [ ] ;
20
21
21
- fastify . addHook ( 'onRequest' , async ( request , _reply ) => {
22
+ fastify . addHook ( 'onRequest' , async function ( this : FastifyInstance , request , _reply ) {
23
+ // const same = fastify === this;
24
+
25
+ // store the start time of the request
22
26
const start = Date . now ( ) ;
23
27
request . app = { start } ;
24
28
} ) ;
25
29
26
- fastify . addHook ( 'onResponse' , async ( request , reply ) => {
30
+ fastify . addHook ( 'onResponse' , async function ( this : FastifyInstance , request , reply ) {
27
31
if ( urlsToIgnore . includes ( request . raw . url ) ) return ;
28
32
29
33
const duration = Date . now ( ) - request . app . start ;
0 commit comments