@apolitical/server 2.3.2-rc.static.1 → 2.4.0

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/CHANGELOG.md CHANGED
@@ -5,6 +5,16 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.4.0] - 2022-02-22
9
+ ### Added
10
+ - User slug to error logs as metadata
11
+ ### Changed
12
+ - Transition to new logger middleware format
13
+
14
+ ## [2.3.3] - 2022-02-21
15
+ ### Changed
16
+ - maging sure index.html is not considered as a static asset by the middleware loader
17
+
8
18
  ## [2.3.2] - 2022-02-21
9
19
  ### Changed
10
20
  - loading static files middleware after the app has been loaded
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apolitical/server",
3
- "version": "2.3.2-rc.static.1",
3
+ "version": "2.4.0",
4
4
  "description": "Node.js module to encapsulate Apolitical's express server setup",
5
5
  "author": "Apolitical Group Limited <engineering@apolitical.co>",
6
6
  "license": "MIT",
package/src/config.js CHANGED
@@ -3,7 +3,7 @@
3
3
  const { NODE_ENV, LOG_LEVEL } = process.env;
4
4
 
5
5
  const NAME = 'apolitical-server';
6
- const VERSION = 'v2.0.0';
6
+ const VERSION = '2.4.0';
7
7
  const ADMIN_ROLE = 'administrator';
8
8
 
9
9
  module.exports = {
package/src/container.js CHANGED
@@ -31,11 +31,11 @@ const serverError = require('./errors/server.error');
31
31
  const jwtDecodeHelper = require('./helpers/jwt/decode.helper');
32
32
  const jwtEncodeHelper = require('./helpers/jwt/encode.helper');
33
33
  const jwtPassportHelper = require('./helpers/jwt/passport.helper');
34
+ const loggerHelper = require('./helpers/logger.helper');
34
35
  // Loaders
35
36
  const documentationLoader = require('./loaders/documentation.loader');
36
37
  const loggerLoader = require('./loaders/logger.loader');
37
38
  const middlewaresLoader = require('./loaders/middlewares.loader');
38
- const staticLoader = require('./loaders/static.loader');
39
39
  const probesLoader = require('./loaders/probes.loader');
40
40
  const fallbackLoader = require('./loaders/fallback.loader');
41
41
  // Middleware
@@ -81,11 +81,11 @@ container.register({
81
81
  jwtDecodeHelper: asFunction(jwtDecodeHelper).singleton(),
82
82
  jwtEncodeHelper: asFunction(jwtEncodeHelper).singleton(),
83
83
  jwtPassportHelper: asFunction(jwtPassportHelper).singleton(),
84
+ loggerHelper: asFunction(loggerHelper).singleton(),
84
85
  // Loaders
85
86
  documentationLoader: asFunction(documentationLoader).singleton(),
86
87
  loggerLoader: asFunction(loggerLoader).singleton(),
87
88
  middlewaresLoader: asFunction(middlewaresLoader).singleton(),
88
- staticLoader: asFunction(staticLoader).singleton(),
89
89
  probesLoader: asFunction(probesLoader).singleton(),
90
90
  fallbackLoader: asFunction(fallbackLoader).singleton(),
91
91
  // Middlewares
@@ -0,0 +1,35 @@
1
+ 'use strict';
2
+
3
+ module.exports = ({ morgan, config, logger }) => {
4
+ const {
5
+ LOGGED_OUT_SLUG,
6
+ TOKENS: { USER_SLUG },
7
+ } = config.SERVER.MORGAN_OPTIONS;
8
+
9
+ function getUserSlug(req) {
10
+ return req.user && req.user.slug ? req.user.slug : LOGGED_OUT_SLUG;
11
+ }
12
+
13
+ function buildCustomFormat(tokens, req, res) {
14
+ return [
15
+ tokens.method(req, res),
16
+ tokens.url(req, res),
17
+ tokens.status(req, res),
18
+ tokens[USER_SLUG](req),
19
+ tokens['response-time'](req, res),
20
+ 'ms',
21
+ ].join(' ');
22
+ }
23
+
24
+ function buildMiddleware(labels) {
25
+ const childLogger = logger.where(__filename, 'load');
26
+ childLogger.debug('Started');
27
+ // Setup Morgan with custom format and Apolitical Logger stream
28
+ morgan.token(USER_SLUG, getUserSlug);
29
+ const morganMiddleware = morgan(buildCustomFormat, logger.where(__filename, 'morganMiddleware', labels));
30
+ childLogger.debug('Finished');
31
+ return morganMiddleware;
32
+ }
33
+
34
+ return { getUserSlug, buildMiddleware };
35
+ };
@@ -1,39 +1,19 @@
1
1
  'use strict';
2
2
 
3
- module.exports = ({ apoliticalLogger, morgan, config, logger }) => {
4
- const {
5
- LOGGED_OUT_SLUG,
6
- TOKENS: { USER_SLUG },
7
- } = config.SERVER.MORGAN_OPTIONS;
8
-
9
- function getUserSlug(req) {
10
- return req.user && req.user.slug ? req.user.slug : LOGGED_OUT_SLUG;
11
- }
12
-
13
- function buildCustomFormat(tokens, req, res) {
14
- return [
15
- tokens.method(req, res),
16
- tokens.url(req, res),
17
- tokens.status(req, res),
18
- tokens[USER_SLUG](req),
19
- tokens['response-time'](req, res),
20
- 'ms',
21
- ].join(' ');
22
- }
23
-
3
+ module.exports = ({ apoliticalLogger, config, logger, loggerHelper }) => {
24
4
  return async function load(app, { labels }) {
25
5
  const childLogger = logger.where(__filename, 'load');
26
6
  childLogger.debug('Started');
27
- // Setup Morgan with custom format and Apolitical Logger stream
28
- morgan.token(USER_SLUG, getUserSlug);
29
- const morganMiddleware = morgan(buildCustomFormat, logger.where(__filename, 'morganMiddleware', labels));
30
- app.use(morganMiddleware);
31
- // Setup Google Cloud with Apolitical Logger
32
7
  if (config.NODE_ENV === 'production') {
8
+ // Setup Google Cloud with Apolitical Logger
33
9
  const winstonMiddleware = await apoliticalLogger.loggerMiddleware(
34
10
  logger.where(__filename, 'winstonMiddleware', labels),
35
11
  );
36
12
  app.use(winstonMiddleware);
13
+ } else {
14
+ // Setup Morgan with custom format and Apolitical Logger stream
15
+ const morganMiddleware = loggerHelper.buildMiddleware(labels);
16
+ app.use(morganMiddleware);
37
17
  }
38
18
  childLogger.debug('Finished');
39
19
  };
@@ -1,12 +1,21 @@
1
1
  'use strict';
2
2
 
3
- module.exports = ({ bodyParser: { json, urlencoded }, compression, cors, cookieParser, prerender, config, logger }) => {
3
+ module.exports = ({
4
+ bodyParser: { json, urlencoded },
5
+ express,
6
+ compression,
7
+ cors,
8
+ cookieParser,
9
+ prerender,
10
+ config,
11
+ logger,
12
+ }) => {
4
13
  const {
5
14
  BODY_PARSER_OPTIONS: { JSON_OPTIONS, URL_ENCODED_OPTIONS },
6
15
  CORS_OPTIONS,
7
16
  } = config.SERVER;
8
17
 
9
- return function load(app, { corsOptions, prerenderToken }) {
18
+ return function load(app, { corsOptions, prerenderToken, staticFiles }) {
10
19
  const childLogger = logger.where(__filename, 'load');
11
20
  childLogger.debug('Started');
12
21
  // Load useful middlewares
@@ -18,6 +27,10 @@ module.exports = ({ bodyParser: { json, urlencoded }, compression, cors, cookieP
18
27
  if (prerenderToken) {
19
28
  app.use(prerender.set('prerenderToken', prerenderToken));
20
29
  }
30
+ if (staticFiles) {
31
+ const { baseUrl, folderPath } = staticFiles;
32
+ app.use(baseUrl, express.static(folderPath, { index: false }));
33
+ }
21
34
  childLogger.debug('Finished');
22
35
  };
23
36
  };
@@ -7,12 +7,10 @@ module.exports =
7
7
  JWT: { AUTH0 },
8
8
  },
9
9
  logger,
10
+ loggerHelper: { getUserSlug },
10
11
  serverError: { GeneralError },
11
12
  }) =>
12
13
  ({ labels, redirectURL, fallbackController }) => {
13
- // Apolitical Logger (with service metadata)
14
- const errorLogger = logger.where(__filename, 'errorMiddleware', labels);
15
-
16
14
  // eslint-disable-next-line no-unused-vars
17
15
  return function handler(err, req, res, next) {
18
16
  const childLogger = logger.where(__filename, 'handler');
@@ -38,21 +36,26 @@ module.exports =
38
36
  errors = ['unknown-error'];
39
37
  }
40
38
  }
39
+ // Log the error with all the relevent info
40
+ const userSlug = getUserSlug(req);
41
41
  if (req.log) {
42
- req.log.warn(message, { errors });
42
+ req.log.warn(message, { errors, userSlug });
43
43
  } else {
44
- errorLogger.warn(message, { errors });
44
+ const errorLogger = logger.where(__filename, 'handler', labels);
45
+ errorLogger.warn(message, { errors, userSlug });
45
46
  }
46
-
47
+ // Use the redirect URL to redirect the request
47
48
  if (redirectURL) {
48
49
  return res.redirect(TEMPORARY_REDIRECT, `${redirectURL}?errorMessage=${encodeURI(message)}`);
49
50
  }
51
+ // Use the fallback controller to handle the response
50
52
  if (fallbackController) {
51
53
  // more known error messages can be added here
52
54
  if (message === 'Unexpected error: Cannot read items') {
53
55
  return fallbackController(req, res);
54
56
  }
55
57
  }
58
+ // Use the info on the error to send the response
56
59
  return res.status(code).json({ message, errors });
57
60
  };
58
61
  };
@@ -10,7 +10,6 @@ module.exports = ({
10
10
  authorisationMiddleware,
11
11
  errorMiddleware,
12
12
  middlewaresLoader,
13
- staticLoader,
14
13
  probesLoader,
15
14
  fallbackLoader,
16
15
  jwtService,
@@ -51,8 +50,6 @@ module.exports = ({
51
50
  if (opts.appLoader) {
52
51
  await opts.appLoader(app);
53
52
  }
54
- // Load static files middleware
55
- staticLoader(app, opts);
56
53
  // Load documentation
57
54
  documentationLoader(app, opts);
58
55
  // Load fallback routing
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- module.exports = ({ express, logger }) => {
4
- return function load(app, { staticFiles }) {
5
- const childLogger = logger.where(__filename, 'load');
6
- childLogger.debug('Started');
7
-
8
- if (staticFiles) {
9
- const { baseUrl, folderPath } = staticFiles;
10
- app.use(baseUrl, express.static(folderPath));
11
- }
12
- childLogger.debug('Finished');
13
- };
14
- };