sm-utility 1.4.2 → 1.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/logger/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /// <reference types="express" />
2
2
  /// <reference types="qs" />
3
- import winston from "winston";
3
+ import winston from 'winston';
4
4
  export declare const loggerMiddleware: import("express").Handler;
5
5
  export declare const logError: import("express").ErrorRequestHandler<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>;
6
6
  export declare const logger: winston.Logger;
package/logger/index.js CHANGED
@@ -10,17 +10,17 @@ const express_winston_1 = __importDefault(require("express-winston"));
10
10
  const ecs_winston_format_1 = __importDefault(require("@elastic/ecs-winston-format"));
11
11
  let configs;
12
12
  try {
13
- configs = require(process_1.cwd() + "/logger.config");
13
+ configs = require(process_1.cwd() + '/logger.config');
14
14
  }
15
15
  catch {
16
- throw Error('Logger configs could not be found on app root\'s directory.');
16
+ throw Error("Logger configs could not be found on app root's directory.");
17
17
  }
18
18
  function filterRequestHeaders(confidentialHeaders = []) {
19
19
  return (req, propName) => {
20
- if (propName !== "headers")
20
+ if (propName !== 'headers')
21
21
  return req[propName];
22
22
  const filteredHeaders = Object.keys(req.headers)
23
- .filter((key) => !confidentialHeaders.includes(key))
23
+ .filter(key => !confidentialHeaders.includes(key))
24
24
  .reduce((acc, key) => {
25
25
  acc[key] = req.headers[key];
26
26
  return acc;
@@ -30,25 +30,18 @@ function filterRequestHeaders(confidentialHeaders = []) {
30
30
  }
31
31
  const routeFilter = (req, res) => {
32
32
  const { url } = req;
33
- const shouldRouteBeFiltered = shouldFilterRoute(url);
33
+ const routesToBeFiltered = configs.ignoredRoutes || [];
34
+ const shouldRouteBeFiltered = shouldFilterRoute(url, routesToBeFiltered);
34
35
  return shouldRouteBeFiltered;
35
36
  };
36
- function shouldFilterRoute(url) {
37
- const routesToBeFiltered = configs.ignoredRoutes || [];
38
- const shouldRouteBeFiltered = routesToBeFiltered.some((route) => {
39
- const splitedRouteParts = getSplitedRouteParts(route);
40
- return splitedRouteParts.every(part => url.toLowerCase().indexOf(part) > -1);
37
+ function shouldFilterRoute(url, routesToBeFiltered) {
38
+ const shouldRouteBeFiltered = routesToBeFiltered.some(route => {
39
+ const regExp = generateRouteRegex(route);
40
+ const matches = new String(url).match(regExp);
41
+ return !!(matches === null || matches === void 0 ? void 0 : matches.length);
41
42
  });
42
43
  return shouldRouteBeFiltered;
43
44
  }
44
- function getSplitedRouteParts(route) {
45
- const routeParts = route.split('/');
46
- const filteredParts = routeParts.filter(part => {
47
- const firstChar = part === null || part === void 0 ? void 0 : part.charAt(0);
48
- return firstChar !== ":" && firstChar !== '';
49
- });
50
- return filteredParts;
51
- }
52
45
  function getTransports() {
53
46
  const transports = [];
54
47
  if (configs.console) {
@@ -59,15 +52,53 @@ function getTransports() {
59
52
  }
60
53
  return transports;
61
54
  }
55
+ function isRequestInfo(info) {
56
+ const metadata = info.meta;
57
+ return (metadata === null || metadata === void 0 ? void 0 : metadata.req) && (metadata === null || metadata === void 0 ? void 0 : metadata.res) ? true : false;
58
+ }
59
+ function generateRouteRegex(route) {
60
+ const splitedRoute = route.split('/').filter(i => i !== '');
61
+ const regexString = splitedRoute
62
+ .map(i => {
63
+ return (i === null || i === void 0 ? void 0 : i.charAt(0)) === ':' ? '(.)+' : i;
64
+ })
65
+ .join('/');
66
+ const regExp = new RegExp('^/' + regexString + '$', 'g');
67
+ return regExp;
68
+ }
69
+ function filterBlacklistedBodysByRoute(info) {
70
+ var _a;
71
+ const blacklistedRoutes = configs.responseBlacklistBodyRoutes || [];
72
+ const request = info.meta.req;
73
+ const shouldBeFiltered = blacklistedRoutes.some(({ route, method }) => {
74
+ const regExp = generateRouteRegex(route);
75
+ const matches = new String(request.url).match(regExp);
76
+ return ((matches === null || matches === void 0 ? void 0 : matches.length) && request.method.toLowerCase() === method.toLowerCase());
77
+ });
78
+ if (shouldBeFiltered) {
79
+ (_a = info.meta.res) === null || _a === void 0 ? true : delete _a.body;
80
+ }
81
+ return info;
82
+ }
83
+ function formatBlacklistedBody() {
84
+ return winston_1.default.format(info => {
85
+ const isRequest = isRequestInfo(info);
86
+ if (isRequest) {
87
+ const filteredInfo = filterBlacklistedBodysByRoute(info);
88
+ return filteredInfo;
89
+ }
90
+ return info;
91
+ })();
92
+ }
62
93
  function createLoggerMiddleware() {
63
- express_winston_1.default.requestWhitelist.push("body", ...configs.requestWhitelist || []);
64
- express_winston_1.default.responseWhitelist.push("body", ...configs.responseWhitelist || []);
94
+ express_winston_1.default.requestWhitelist.push('body', ...(configs.requestWhitelist || []));
95
+ express_winston_1.default.responseWhitelist.push('body', ...(configs.responseWhitelist || []));
65
96
  return express_winston_1.default.logger({
66
97
  statusLevels: true,
67
98
  transports: getTransports(),
68
99
  requestFilter: filterRequestHeaders(configs.confidentialHeaders || []),
69
100
  ignoreRoute: routeFilter,
70
- format: ecs_winston_format_1.default({ convertReqRes: true })
101
+ format: winston_1.default.format.combine(formatBlacklistedBody(), ecs_winston_format_1.default({ convertReqRes: true })),
71
102
  });
72
103
  }
73
104
  function createErrorLoggerMiddleware() {
package/logger/types.d.ts CHANGED
@@ -1,9 +1,52 @@
1
1
  import winston from "winston";
2
2
  export interface ILoggerConfigs {
3
- console: winston.transports.ConsoleTransportOptions;
4
- file: winston.transports.FileTransportOptions;
3
+ /**
4
+ * (Opcional)
5
+ * Configurações aplicadas aos logs que serão exibidos no console.
6
+ * Para mais detalhes, veja a documentação oficial do winston (https://github.com/winstonjs/winston/blob/master/docs/transports.md#console-transport).
7
+ * Caso não informado, a opção de logs pelo console será desativada.
8
+ */
9
+ console?: winston.transports.ConsoleTransportOptions;
10
+ /**
11
+ * (Opcional)
12
+ * Configurações aplicadas aos logs que serão gravadas em arquivos.
13
+ * Para mais detalhes, veja a documentação oficial do winston (https://github.com/winstonjs/winston/blob/master/docs/transports.md#file-transport).
14
+ * Caso não informado, a opção de logs em arquivos será desativada.
15
+ */
16
+ file?: winston.transports.FileTransportOptions;
17
+ /**
18
+ * (Opcional)
19
+ * Array de strings dos headers que serão removidos dos logs no objeto de requisição.
20
+ */
5
21
  confidentialHeaders?: string[];
22
+ /**
23
+ * (Opcional)
24
+ * Array de strings das rotas a serem removidas totalmento dos logs (tanto a requisição, quanto a resposta).
25
+ * Caso a rota possua algum parâmetro, é necessário informalo iniciando em :.
26
+ * Exemplo: [`/offers/:offerId/details`, `/offers/list`, `/users/:user_id`].
27
+ */
6
28
  ignoredRoutes?: string[];
29
+ /**
30
+ * (Opcional)
31
+ * Array de strings dos parâmetros do objeto de requisição a serem logados.
32
+ * Caso nenhum valor seja passado, somente o body será exibido por padrão.
33
+ */
7
34
  requestWhitelist?: string[];
35
+ /**
36
+ * (Opcional)
37
+ * Array de strings dos parâmetros do objeto de resposta a serem logados.
38
+ * Caso nenhum valor seja passado, somente o body será exibido por padrão.
39
+ */
8
40
  responseWhitelist?: string[];
41
+ /**
42
+ * (Opcional)
43
+ * Array de objetos contendo as rotas e métodos, referente as chamadas das quais
44
+ * o parâmetro body será omitido no objeto de resposta nos logs.
45
+ * Caso a rota possua algum parâmetro, é necessário informalo iniciando em :.
46
+ * Exemplo: [{ route: `offers/:offerId/details`, method: `POST` }]
47
+ */
48
+ responseBlacklistBodyRoutes?: Array<{
49
+ route: string;
50
+ method: string;
51
+ }>;
9
52
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sm-utility",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
4
4
  "description": "reusable utility codes for sm projects",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -1,2 +1,3 @@
1
- import { AxiosInstance, AxiosRequestConfig } from 'axios';
2
- export declare function createApi(axiosConfig?: AxiosRequestConfig): AxiosInstance;
1
+ import { AxiosInstance } from 'axios';
2
+ import { RequestConfig } from './types';
3
+ export declare function createApi(axiosConfig?: RequestConfig): AxiosInstance;
@@ -0,0 +1,5 @@
1
+ import { AxiosRequestConfig } from 'axios';
2
+ export interface RequestConfig extends AxiosRequestConfig {
3
+ meta?: Record<string, any>;
4
+ logRequests?: boolean;
5
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });