@cley_faye/boilerplate 3.6.0 → 3.7.2

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/README.md CHANGED
@@ -318,6 +318,7 @@ It supports the following properties:
318
318
  - route: log all route called. Can be either a boolean or an express-winston configuration.
319
319
  In the later case, all properties are accepted except the winston instance, which is set
320
320
  separately.
321
+ More details in the "custom logging" section below.
321
322
  - error: log all errors. Accept a boolean, or an object with the "collapseNodeModules" boolean
322
323
  property.
323
324
  - logger: an instance of a winston logger.
@@ -366,6 +367,40 @@ root of the service, or an object with the following properties:
366
367
  - options: The options to pass to express static handler
367
368
  - route: The route under which the static files will be served
368
369
 
370
+ ### Custom logging
371
+ The default configuration (by setting `options.log.route: true`) allows some level of customization
372
+ of the actual logged data.
373
+ If a custom object is passed instead of `true`, the following will not automatically apply.
374
+
375
+ By default, all body content is logged.
376
+ To finely tune what body elements are logged on each route the `bodyLogger()` middleware can be
377
+ used.
378
+ It takes two parameters, the first one is an array of properties that *should* be logged, the second
379
+ one can be a custom object or a function returning a custom object with extra properties to log.
380
+
381
+ For example, for a login route, you might want to hide the provided password but still get some info
382
+ (note: this is an example, in practice you probably shouldn't care about this)
383
+
384
+ ```JavaScript
385
+ router.post(
386
+ "/login",
387
+ bodyLogger(
388
+ ["login"],
389
+ req => ({
390
+ passwordLength: req.body.password.length,
391
+ }),
392
+ ),
393
+ processLogin,
394
+ );
395
+ ```
396
+
397
+ In addition to excluding properties from the body of a request and adding custom properties, it can
398
+ be useful to always identify a request coming from a logged-in user.
399
+
400
+ You can provide a `userFromReq` property to the `options.log` configuration.
401
+ It should be a function that receive `req` as its argument and returns a string identifying the
402
+ logged-in user.
403
+
369
404
  ### Configuring global aspects of an Express App
370
405
 
371
406
  #### Configuring the template engine
@@ -1,11 +1,22 @@
1
- import expressWinston from "express-winston";
2
- import { Router } from "express";
3
- import { LogOptions } from "./pipelinebuilder.js";
1
+ import expressWinston, { BaseLoggerOptions } from "express-winston";
2
+ import { Request, Router } from "express";
3
+ import { LogOptions, UserFromReqFunc } from "./pipelinebuilder.js";
4
4
  export declare type LoggerOptions = expressWinston.LoggerOptions | boolean;
5
5
  interface ErrorLoggerConfiguration {
6
6
  collapseNodeModules?: boolean;
7
7
  }
8
8
  export declare type ErrorLoggerOptions = ErrorLoggerConfiguration | boolean;
9
+ export interface LoggingData {
10
+ extraLoggingData?: Record<string, unknown>;
11
+ }
12
+ export interface RequestWithLoggingData extends Request {
13
+ _cleyfayeLogging?: LoggingData;
14
+ _routeWhitelists?: {
15
+ body?: Array<string>;
16
+ };
17
+ }
18
+ /** Return the default value for route logger is it is set as `true` */
19
+ export declare const defaultRouteLoggerConfig: (userFromReq?: UserFromReqFunc | undefined) => BaseLoggerOptions;
9
20
  export declare const registerRouteLogger: (app: Router, logOptions?: LogOptions | undefined) => void;
10
21
  export declare const registerErrorLogger: (app: Router, logOptions?: LogOptions | undefined) => void;
11
22
  export {};
@@ -29,7 +29,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
29
29
  return (mod && mod.__esModule) ? mod : { "default": mod };
30
30
  };
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
- exports.registerErrorLogger = exports.registerRouteLogger = void 0;
32
+ exports.registerErrorLogger = exports.registerRouteLogger = exports.defaultRouteLoggerConfig = void 0;
33
33
  const winston_1 = __importDefault(require("winston"));
34
34
  const express_winston_1 = __importDefault(require("express-winston"));
35
35
  const winston_js_1 = require("../winston.js");
@@ -56,11 +56,25 @@ const customRouteFormat = (outputTimestamp) => winston_1.default.format.printf((
56
56
  const finalMessage = `${info.message} ${metaString === "{}" ? "" : metaString}`;
57
57
  return (0, winston_js_1.prefixOutput)(info.level, finalMessage, outputTimestamp);
58
58
  });
59
+ /** Return the default value for route logger is it is set as `true` */
60
+ const defaultRouteLoggerConfig = (userFromReq) => ({
61
+ meta: true,
62
+ requestWhitelist: ["body"],
63
+ responseWhitelist: [],
64
+ dynamicMeta: (req) => {
65
+ const castReq = req;
66
+ const data = { ...castReq._cleyfayeLogging?.extraLoggingData };
67
+ if (userFromReq)
68
+ data.user = userFromReq(req) ?? null;
69
+ return data;
70
+ },
71
+ });
72
+ exports.defaultRouteLoggerConfig = defaultRouteLoggerConfig;
59
73
  const registerRouteLogger = (app, logOptions) => {
60
- const { route, logger, timestamp } = logOptions ?? {};
74
+ const { route, timestamp, userFromReq } = logOptions ?? {};
61
75
  let extraConfig;
62
76
  if (typeof route === "boolean") {
63
- extraConfig = {};
77
+ extraConfig = (0, exports.defaultRouteLoggerConfig)(userFromReq);
64
78
  }
65
79
  else {
66
80
  extraConfig = { ...route };
@@ -78,20 +92,11 @@ const registerRouteLogger = (app, logOptions) => {
78
92
  colorize: true,
79
93
  msg: "{{req.method}} {{req.url}} {{res.statusCode}} {{res.responseTime}}ms",
80
94
  };
81
- if (logger) {
82
- app.use(express_winston_1.default.logger({
83
- transports: winston_js_1.transports,
84
- ...baseConfig,
85
- ...extraConfig,
86
- }));
87
- }
88
- else {
89
- app.use(express_winston_1.default.logger({
90
- transports: winston_js_1.transports,
91
- ...baseConfig,
92
- ...extraConfig,
93
- }));
94
- }
95
+ app.use(express_winston_1.default.logger({
96
+ transports: winston_js_1.transports,
97
+ ...baseConfig,
98
+ ...extraConfig,
99
+ }));
95
100
  };
96
101
  exports.registerRouteLogger = registerRouteLogger;
97
102
  const customErrorFormat = (outputTimestamp, config) => {
@@ -0,0 +1,9 @@
1
+ import { NextFunction, Request, Response } from "express";
2
+ export declare type ExtraLoggingDataType = Record<string, unknown> | undefined;
3
+ export declare type ExtraLoggingDataFunc = (req: Request) => Promise<ExtraLoggingDataType> | ExtraLoggingDataType;
4
+ export declare type ExtraLoggingData = ExtraLoggingDataFunc | Record<string, unknown>;
5
+ export interface ExtraLoggingOptions {
6
+ /** Do not expose the "hidden" body props */
7
+ noHiddenBodyProps?: boolean;
8
+ }
9
+ export declare const bodyLogger: (bodyProps?: string[] | undefined, extraLoggingData?: ExtraLoggingData | undefined, options?: ExtraLoggingOptions) => (req: Request, res: Response, next: NextFunction) => void;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @license
3
+ * @preserve
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2021 Gabriel Paul "Cley Faye" Risterucci
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ */
27
+ "use strict";
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.bodyLogger = void 0;
30
+ const setLogInfoInReq = (req, body, extraData) => {
31
+ const castReq = req;
32
+ if (body) {
33
+ if (!castReq._routeWhitelists)
34
+ castReq._routeWhitelists = {};
35
+ castReq._routeWhitelists.body = body;
36
+ }
37
+ if (extraData) {
38
+ castReq._cleyfayeLogging = { extraLoggingData: extraData };
39
+ }
40
+ };
41
+ const getPropType = (value) => {
42
+ if (typeof value === "string")
43
+ return `string(${value.length})`;
44
+ if (typeof value === "number")
45
+ return "number";
46
+ if (typeof value === "boolean")
47
+ return "boolean";
48
+ if (typeof value === "undefined")
49
+ return "undefined";
50
+ if (Array.isArray(value))
51
+ return `Array(${value.length})`;
52
+ return "object";
53
+ };
54
+ const getHiddenBodyProps = (req, ignoreKeys = []) => {
55
+ if (typeof req.body !== "object")
56
+ return;
57
+ const body = req.body;
58
+ const res = {};
59
+ for (const key of Object.keys(body)) {
60
+ if (ignoreKeys.includes(key))
61
+ continue;
62
+ res[key] = getPropType(body[key]);
63
+ }
64
+ if (Object.keys(res).length === 0)
65
+ return;
66
+ return res;
67
+ };
68
+ const bodyLogger = (bodyProps, extraLoggingData, options = {}) => (req, res, next) => {
69
+ const asyncFunc = async () => {
70
+ const allExtraData = {};
71
+ if (!options.noHiddenBodyProps) {
72
+ const redactedBody = getHiddenBodyProps(req, bodyProps);
73
+ if (redactedBody)
74
+ Object.assign(allExtraData, { redactedBody });
75
+ }
76
+ const extraLogData = typeof extraLoggingData === "function"
77
+ ? await extraLoggingData(req)
78
+ : extraLoggingData;
79
+ Object.assign(allExtraData, extraLogData);
80
+ setLogInfoInReq(req, bodyProps, allExtraData);
81
+ };
82
+ asyncFunc()
83
+ .then(() => {
84
+ next();
85
+ })
86
+ .catch((error) => {
87
+ next(error);
88
+ });
89
+ };
90
+ exports.bodyLogger = bodyLogger;
@@ -1,4 +1,4 @@
1
- import express from "express";
1
+ import express, { Request } from "express";
2
2
  import { OptionsJson, OptionsUrlencoded, OptionsText, Options as OptionsRaw } from "body-parser";
3
3
  import winston from "winston";
4
4
  import { LoggerOptions, ErrorLoggerOptions } from "./logger.js";
@@ -24,11 +24,13 @@ export interface ComplexStaticDefinition {
24
24
  route?: string;
25
25
  }
26
26
  export declare type StaticDefinition = ComplexStaticDefinition | string;
27
+ export declare type UserFromReqFunc = (req: Request) => string | undefined;
27
28
  export interface LogOptions {
28
29
  route?: LoggerOptions;
29
30
  error?: ErrorLoggerOptions;
30
31
  logger?: winston.Logger;
31
32
  timestamp?: boolean;
33
+ userFromReq?: UserFromReqFunc;
32
34
  }
33
35
  export interface DefaultErrorHandlerConfig {
34
36
  /** Set to true to allow server errors without a code to be sent as-is in the response */
@@ -49,7 +49,7 @@ var HandlerType;
49
49
  HandlerType["COPY"] = "copy";
50
50
  })(HandlerType = exports.HandlerType || (exports.HandlerType = {}));
51
51
  const gatherTasks = (handlers, gruntConfig, targetName, options) => Object.keys(handlers)
52
- .reduce((acc, cur) => acc.concat((options?.[cur] && (options[cur] ?? {}).disabled)
52
+ .reduce((acc, cur) => acc.concat((options?.[cur] && options[cur]?.disabled)
53
53
  ? []
54
54
  : handlers[cur](gruntConfig, targetName, (options?.[cur]) ?? {})), []);
55
55
  const mergeResults = (tasksResults) => tasksResults.reduce((acc, cur) => {
@@ -184,7 +184,8 @@ const reactApp = (gruntConfig, targetName = "reactApp", options) => {
184
184
  };
185
185
  const tasksResults = gatherTasks(handlers, gruntConfig, targetName, options);
186
186
  const mergedResults = mergeResults(tasksResults);
187
- createCopyTask(gruntConfig, targetName, mergedResults, options);
187
+ if (!options?.copy?.disabled)
188
+ createCopyTask(gruntConfig, targetName, mergedResults, options);
188
189
  // Add grunt-contrib-watch task
189
190
  createWatchTasks(gruntConfig, mergedResults, options?.watch);
190
191
  return mergedResults.requiredTasks;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cley_faye/boilerplate",
3
- "version": "3.6.0",
3
+ "version": "3.7.2",
4
4
  "description": "Boilerplate code generator for generic projects",
5
5
  "repository": {
6
6
  "type": "git",