All files / controllers logger.js

0% Statements 0/20
0% Branches 0/16
0% Functions 0/5
0% Lines 0/20

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90                                                                                                                                                                                   
/* eslint-disable no-console */
import moment from 'moment-timezone';
import LoggerApiCreate from '../source/logger/loggerApi/create';
 
function getToken(req) {
  try {
    return (
      (!!req.body && req.body.token) ||
      (req.headers.authorization &&
        req.headers.authorization.includes('Bearer') &&
        req.headers.authorization.replace('Bearer', '').trim()) ||
      (req.headers.Authorization &&
        req.headers.Authorization.includes('Bearer') &&
        req.headers.Authorization.replace('Bearer', '').trim())
    );
  } catch (e) {
    console.log(e);
    return null;
  }
}
 
async function logApiRequest(req) {
  try {
    const time = moment().format();
    const dataLog = {
      userId: req.userId,
      token: getToken(req),
      ip:
        req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress,
      url: req.originalUrl,
      method: req.originalMethod,
      type: 'REQUEST',
      headers: JSON.stringify(req.headers),
      query: JSON.stringify(req.query),
      body: JSON.stringify(req.body),
      createdAt: time,
      updatedAt: time,
    };
 
    LoggerApiCreate.createLoggerApi(dataLog);
  } catch (err) {
    console.log(err);
  }
}
 
async function logApiResponse(data, req) {
  try {
    const time = moment().format();
    const dataLog = {
      userId: req.userId,
      token: getToken(req),
      ip:
        req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress,
      url: req.originalUrl,
      method: req.originalMethod,
      type: 'RESPONSE',
      headers: JSON.stringify(req.headers),
      query: JSON.stringify(req.query),
      body: JSON.stringify(data), // Response DATA
      createdAt: time,
      updatedAt: time,
    };
 
    LoggerApiCreate.createLoggerApi(dataLog);
  } catch (err) {
    console.log(err);
  }
}
 
async function logApiPost(req, res) {
  logApiRequest(req);
 
  const oldSend = res.send;
  res.send = function (data) {
    logApiResponse(data, req);
    res.send = oldSend;
    return res.send(data);
  };
}
 
export default {
  logApiPost,
};