We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

API Config

It's frequently useful to have a way to store and access state in our handlers. For example, we might want to keep track of the number of requests we've received, or we may want to pass around credentials to an API.

Assignment

The product managers at Chirpy want to know how many requests are being made to serve our homepage - in essence, they want to know how many people are viewing the site!

They have asked for a simple HTTP endpoint they can hit to get the number of requests that have been processed. It will return the count as plain text in the response body.

For now, they just want the number of requests that have been processed since the last time the server was started, we don't need to worry about saving the data between restarts.

Steps

type APIConfig = {
  fileserverHits: number;
};

Use .js extensions when importing files. We're using a bare-bones setup without a bundler, so Node can't import .ts. For example: import './config.js'.

function middlewareMetricsInc(req: Request, res: Response, next: NextFunction) {
  // ...
}

Where Gophers have to worry about atomicity and multiple goroutines accessing a single object, JavaScript enjoyers get a perk from JavaScript being single-threaded.

Hits: x

Where x is the number of requests that have been processed. Just import the same config object and access the fileserverHits property.

It should follow the same design as the previous handlers.

Run and submit the CLI tests.