Andrea Franchini
Andrea Franchini

Reputation: 576

How does Fastify calculate responseTime?

Context: I'm interested in request and response timings.

The first approach to know when a request is managed by Fastify is to add a hook like:

fastify.addHook('onRequest', (request, reply, done) => {
  request.onRequestTimestamp = Date.now();
  done();
});

But the information is already there: enabling Fastify logs

fastify = fastify({ logger: true });

We can see for example

{
  "level": 30,
  "time": 1620659712059,
  "pid": 5673,
  "hostname": "myhostname",
  "reqId": "req-1",
  "res": { "statusCode": 200 },
  "responseTime": 14.528815001249313,
  "msg": "request completed"
}

So I suppose Fastify itself stores at least the information of when the request reached the HTTP server somewhere, but I can't find where.

Questions:

1- How does Fastify calculate the responseTime?

2- Does Fastify store (probably in the request object) the request timestamp?

Upvotes: 3

Views: 3249

Answers (1)

Manuel Spigolon
Manuel Spigolon

Reputation: 12900

You can access the information via the reply.getResponseTime() method and add an onResponse hook or trace macro-steps in your handler

const fastify = require('fastify')({ logger: true })

fastify.get('/', (request, reply) => {
  const timeOne = reply.getResponseTime()
  setTimeout(() => {
    const timeTwo = reply.getResponseTime()
    reply.send({
      timeOne, timeTwo
    })
  }, 1000)
})

fastify.listen('8080')

How fastify calculate the responseTime?

It hides the values in the reply object using private Symbols

Upvotes: 6

Related Questions