Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number of requests until last reset

I'm creating a API and I need to create a Route like api/v1/status, to see the status of the server and returns me a json with the number of the requests executed to the API since it is active, but I don't know how to do that with NodeJS , any help?

I have that statusRoutes.js:

src/routes/statusRoutes.js

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

// Set default API response
router.get('/status', function (req, res) {
    //Here is the return number of requests
    res.json({
        status: 'API Its Working',
        message: 'Welcome to User-Register crafted with love!',
    });
});

module.exports = router

In my api I have some routes:

src/routes/userRoutes.js

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

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

// 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)

// Export userRoute
module.exports = router

my index.js is configured that way:

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);

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

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

const dbName = process.env.NODE_ENV === 'dev' ? 'database-test' : 'database';
// Connect to Mongoose and set connection variable
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);

var db = mongoose.connection;
// Setup server port
var port = process.env.PORT || 8080;

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();
});


// Send message for default URL
app.get('/', (req, res) => res.send('User-Register is Working!!'));

// Use Api routes in the App
app.use('/api/v1', statusRoutes);
app.use('/api/v1', userRoutes);

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

module.exports = app
like image 831
Jefferson Bruchado Avatar asked Jan 04 '19 17:01

Jefferson Bruchado


1 Answers

You can create a middleware that is run before every route:

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

Obviously, the count will reset when the server is closed or crashes, so, you can also think about adding a permanent storage like a Database. Databases like Redis are incredible at storing fast changing data.

And, as Ryan pointed out in comments, this method won't scale to multiple serves. Using an external storage that's common to all the servers is the only option in such cases.

like image 90
Faizuddin Mohammed Avatar answered Oct 02 '22 19:10

Faizuddin Mohammed