Решил так:
import express from "express";
import logger from "morgan";
const app = express();
const Storage = {};
app.use(logger((tokens, req, res) => {
const averageCalc = (array) => {
const sum = array.reduce((a, b) => parseFloat(a) + parseFloat(b), 0);
return (sum / array.length) || 0;
};
const prepareStorageObjectMutate = (object, params) => {
const {url, method} = params;
object[url] = object[url] || {};
object[url][method] = object[url][method] || [];
return object;
};
const averageTimeHandler = (data) => {
const result = {};
Object.keys(data).forEach((url) => {
Object.keys(data[url]).forEach((method) => {
prepareStorageObjectMutate(result, {method, url});
const dataArray = data[url][method];
const average = averageCalc(dataArray);
result[url][method] = `${average} ms`;
});
});
return result;
};
try {
const {method: methodF, url: urlF, "response-time": responseTimeF} = tokens;
//Resolve data.
const method = methodF(req, res);
const url = urlF(req, res);
const responseTime = responseTimeF(req, res);
prepareStorageObjectMutate(Storage, {method, url});
//Push response time.
Storage[url][method].push(responseTime);
const averageObject = averageTimeHandler(Storage);
console.log(Storage);
return JSON.stringify(averageObject);
} catch (error) {
console.log("Logger error:");
console.log(error);
}
}));
Пример:
{"/api/users":{"GET":"6.098857142857144 ms"},"/api/news":{"GET":"2.579153846153846 ms"},"/api/users/login":{"POST":"183.39033333333336 ms"}}