Monday, 12 June 2017

NodeJS, Express and JSON API Response Time

I have create a simple express api to handle JSON data on my webapp.

Even if the app is on the same server, the response times are always on 100ms range, the actual data fetching is under 5ms;

Here is the data fetching zone :

export function getData(params) {
  return new Promise((resolve, reject) => {
    if (!params.take || params.take > 30 && isBrowser) {
      params.take = 30;
    }
   console.time("API QUERY Execute");
       {Data Fetching Goes here}
    console.timeEnd("API QUERY Execute");
  });
}

That method takes under 5 ms to complete from console.time.

Here is the express route config

  app.route('/api/data').get((req, res) => {
    getData(req.query)
      .then((data) => {
        res.json(data);
      }).catch((err) => {
        res.status(400);
        res.send(err.message);
      });
  });

The actual Express App :

export default (parameters) => {
  const app = Express();
  const server = require('http').Server(app);
  let io;
  let redisCaching;
  if (process.env.ENABLE_API === 'true') {
    const Mongoose = require('mongoose');
    const Redis = require('socket.io-redis');
    Mongoose.connect(config.server.mongodb.url, config.server.mongodb.options);
    Mongoose.connection.on('connected', () => {
      console.log('==> Connected ', config.server.mongodb.url);
    });

    io = require('socket.io')(server);
    io.sockets.on('connection', (socket) => {
      console.log('==> Socket Connect', socket.handshake.headers.referer);
    });

    io.adapter(Redis({ host: 'localhost', port: 6379 }));

    redisCaching = require('../../redis/redisCaching').redisCaching;
    redisCaching.configure(6379, config.server.hostname);
  }

  if (process.env.CORS === 'true') {
    app.use((req, res, next) => {
      res.header('Access-Control-Allow-Origin', '*');
      res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
      next();
    });
  }

        app.route('/api/data').get((req, res) => {
        getArticles(req.query)
          .then((data) => {
            res.json(data);
          }).catch((err) => {
            res.status(400);
            res.send(err.message);
          });
      });


  app.listen(process.env.PORT, () => {
    console.log(`App listening on port ${process.env.PORT}`);
  });
};

When using tools like pingdom, it showcases 100MS



via Morphex

No comments:

Post a Comment