Total number of requests made since the previous reset

I'm currently working on developing an API and I need to set up a route like api/v1/status in order to check the server status. This route should return a JSON response with the total number of requests made to the API since it became active. However, I am facing some challenges in implementing this functionality using NodeJS. Can anyone offer some guidance or assistance?

Here is the code snippet for my statusRoutes.js:

src/routes/statusRoutes.js

// Initializing express router
let router = require('express').Router();

// Setting default API response
router.get('/status', function (req, res) {
    // Returning the number of requests made
    res.json({
        status: 'API is Working',
        message: 'Welcome to User-Register built with love!',
    });
});

module.exports = router

In addition to the status route, I have several other routes defined in my API:

src/routes/userRoutes.js

const express = require('express')
const router = express.Router()

var userController = require('../controllers/userController')

// Defining user routes
router.route('/users/')
    .get(userController.index)
    .post(userController.new);

router.route('/users/:user_id')
    .get(userController.view)
    .patch(userController.update)
    .put(userController.update)
    .delete(userController.delete)

// Exporting userRoute
module.exports = router

Furthermore, here's how my index.js file is configured:

src/index.js

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressValidator = require('express-validator');

const app = express();
const http = require('http').Server(app);

// Importing routes
const statusRoutes = require("./routes/statusRoutes");
const userRoutes = require("./routes/userRoutes");

// Configuring bodyparser to handle POST requests
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(expressValidator());

// Connecting to MongoDB database based on environment
const dbName = process.env.NODE_ENV === 'dev' ? 'database-test' : 'database';
const url = `mongodb://${process.env.MONGO_INITDB_ROOT_USERNAME}:${process.env.MONGO_INITDB_ROOT_PASSWORD}@${dbName}:27017/?authMechanism=SCRAM-SHA-1&authSource=admin`;
mongoose.set('useCreateIndex', true);
mongoose.connect(url);

// Setting up server port
var port = process.env.PORT || 8080;

// Handling CORS
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE,PATCH');
    res.header("Access-Control-Allow-Headers", "Content-Type");
    next();
});

// Default URL response
app.get('/', (req, res) => res.send('User-Register is Working!!'));

// Using API routes in the application
app.use('/api/v1', statusRoutes);
app.use('/api/v1', userRoutes);

// Listening on specified port
app.listen(port, function () {
    console.log("Running User-Register on port " + port);
    app.emit('APP_STARTED');
});

module.exports = app

Answer №1

If you need a middleware to run before every route, you can create one like this:

let count = 0;
app.use('*', (req, res, next) => { count++; next(); });

However, keep in mind that the count will reset when the server is closed or crashes. To make it more persistent, consider using a permanent storage such as a Database. Redis is an excellent choice for storing fast-changing data.

It's important to note, as pointed out by Ryan in the comments, that this method may not scale well to multiple servers. In those cases, using an external storage that is common to all servers is the only viable option.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract all links from an external website

I'm attempting to extract all the URLs from a webpage using jQuery so that I can later use them with $.get(). If these URLs were located on the same page as the script, retrieving them would be easy by doing something like var links = document.getEle ...

Showcase Pictures from a Document

Is there a way to upload an image via an input field and display it? I want to showcase a profile picture that can be saved in a database. The process should be simple for the user, with the ability to easily upload and view the image. function Save() { ...

Setting up a hostname for the next/image component

Recently, I attempted to enhance my NextJS application by implementing <Image /> from next/image. The images I am using are stored remotely. To make remote images functional, it appears that I need to include my domain in the next.config.js. Below i ...

Discover the magic of Google Charts with the ability to showcase HTML source code within tooltips

I am attempting to show a Pie Chart using Google Charts with HTML in the tooltips, but I am encountering an issue where the HTML source is visible. I have tried setting html:true on the data column and tooltip.isHtml in the options, but I am unsure of what ...

Guide on incorporating one element into another with jquery

I am facing a challenge with the following code snippet: <p>Nuno</p> <p>Eimes</p> My goal is to transform it into this format: <p><a href="name/Nuno">Nuno</a></p> <p><a href="name/Eimes">Eimes& ...

The npm solc module encountered an assertion error stating "Invalid callback" during execution

AssertionError [ERR_ASSERTION]: An error occurred due to an invalid callback being specified. Please check the specified callback and try again. ...

What could be causing AngularJS to fail to send a POST request to my Express server?

I am currently running a Node Express server on localhost that serves a page with AngularJS code. Upon pressing a button on the page, an AngularJS controller is triggered to post a JSON back to the server. However, I am facing an issue where the post requ ...

Refreshing a PNG file without the need to refresh the entire page

Developed a captcha using imagestring imagestring($image, 5, 5, 30, $text, $text_color); imagepng($image,"captcha_image.png"); imagepng($image,"captcha_image.png"); The code snippet above shows part of the implementation. <img ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

Ways to display URL parameters on an HTML page without using PHP

I'm currently working on a website using HTML (without PHP) and I'm facing an issue with displaying URL parameters on an appointment confirmation page. The appointment details are being successfully passed through the URL parameters, but I'm ...

What are the drawbacks of using JavaScript to load a series of images?

Currently, I am facing an issue with the loading speed of a sequence of images on my website. The javascript code I have implemented to cycle through 50 images works perfectly fine locally but becomes slow and buggy when the site is live. Despite the image ...

The anchor tag fails to trigger the onClick function in React

I'm having trouble updating the component state in my React app when clicking on an anchor tag within the render method. I've attempted to bind the function in the constructor, but the console.log statement is still not being called. Here's ...

Executing a cloud function in Firebase from an Angular-Ionic application by making an HTTP request

I am a newcomer to GCP and app development, so please bear with me if this question seems mundane. Currently, I have an angular-ionic app that is connected to Firebase allowing me to interact with the Firestore database. Now, my challenge is to invoke a ht ...

Multi-object retrieval feature in Material Dialog

I am encountering an issue with Material Dialog when confirming the action to "remove row" in a table. Initially, removing from the dialog works fine and deletes a row. However, after closing the dialog and re-calling it for the second time, the removal ac ...

Effortlessly transferring images using Axios in Node.js: A guide

Previously, I utilized ApiSauce to send listings from my React Native application to a Node.js server with Multer. I made the switch to Axios, and everything went smoothly except for the image uploading component. export const add = (listing, onUploadPro ...

My Node.js application is encountering an issue when attempting to establish a connection with SQL Server - nothing appears on the console, even in the absence of any errors

The following code snippet is from the index.js file. Upon visiting the link "localhost:300/admins/", the code is supposed to establish a connection with SQL Server and retrieve the result on the console. I confirm that my Microsoft SQL Server Management ...

The API is returning a successful response code of 200 when the HEAD and OPTIONS methods are utilized

My API is up and running smoothly with a GET method in express. This is the code for my API: app.get('/healthcheck', (_req, res) => { res.status(200).send({ state: 'Healthy', timestamp: new Date(), uptime: process.upti ...

The jquery click event is not working as expected

Hey there, I've been working on creating a dropdown menu that can be activated by clicking for better usability on touch screens. $('a.dropsmall2').click(function() { $(this).next('ul').slideToggle(500,'easeInOutQuad'); ...

Is there a way to navigate to a newly created document?

Is there a way to automatically redirect a user to the show action of a document or post they have just created using express.js? Take a look at the following code snippet, which outlines how I am creating the document: app.post('/document/create&ap ...

What is the purpose of using double quotes within single quotes in JavaScript?

Could someone clarify the reason behind needing to nest double quotes inside single quotes in my Webpack configuration shown below? What is preventing using just double quotes? module.exports = merge(prodEnv, { NODE_ENV: '"development"', API ...