All files / spirit-common/lib/middleware log.js

100% Statements 26/26
100% Branches 7/7
100% Functions 7/7
100% Lines 25/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                          1x 1x   1x 6x 1x 1x       5x 5x 129x 129x 129x 129x   5x 5x     5x 5x   5x   5x   5x 3x 3x 3x   2x 2x 2x      
"use strict";
 
/*
 * A simple logger for reporting the time in milliseconds
 * the amount of time elapsed in responding to a request
 *
 * It is meant purely for development
 */
 
//const prefix_in = "⇢ "
//const prefix_out = "↩︎ "
//const prefix_err = "⚠︎ "
 
var prefix_in = "->";
var prefix_out = "<-";
 
module.exports = function (handler) {
  if (typeof process !== "undefined" && typeof process.env !== "undefined" && process.env.NODE_ENV === "production") {
    return function (request) {
      return handler(request);
    };
  }
 
  var reqtag = function reqtag(str) {
    var tag = str.split("").reduce(function (h, c) {
      var n = parseInt(c);
      if (isNaN(n)) n = c.charCodeAt();
      n += 1;
      return h * n;
    }, 0);
    var seed = Math.floor(Math.random() * 100000);
    return tag + seed;
  };
 
  return function (request) {
    var t = new Date();
 
    var tag = reqtag(t.getTime().toString() + request.method + request.url);
 
    console.log(prefix_in, tag, request.method, request.url);
 
    return handler(request).then(function (response) {
      var diff = new Date() - t;
      console.log(prefix_out, tag, response.status, diff + "ms");
      return response;
    }).catch(function (err) {
      var diff = new Date() - t;
      console.log(prefix_out, tag, "err", diff + "ms");
      throw err;
    });
  };
};