Server
Plugins

Plugins

The feTS Server includes an extension system, offering the ability to interact with the request/response process.

  • onRequest - Invoked prior to the router handling the request.
    • It features an endResponse function that takes a Response object to preemptively conclude the request.
  • onResponse - Invoked following the router's handling of the request.
    • It offers the ability to alter the response before it's delivered to the client.

How do middlewares differ from plugins?

Middlewares are capable of managing the request before the response.

To deal with particular scenarios, such as logging responses, adding additional headers to the response for CORS or cookies, and so forth, we require plugins that can intercept the final response before it is received by the client.

It can also be employed for tracing and monitoring purposes.

Recording the Response Delay

We'll develop an extension that determines the response delay and logs it in the console.

import { RouterPlugin } from 'fets'
 
export function useLogDelay(): RouterPlugin {
  const initialTimePerRequest = new WeakMap<Request, number>()
  return {
    onRequest({ request }) {
      initialTimePerRequest.set(request, Date.now())
    },
    onResponse({ request, response }) {
      const initialTime = initialTimePerRequest.get(request)
      if (initialTime) {
        const delay = Date.now() - initialTime
        console.log(`Response delay: ${delay}ms`)
      }
    }
  }
}