@sera4/essentia 1.0.9 → 1.0.11

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
@@ -5,4 +5,5 @@ A collection of small modules providing essential utilities for TWS services:
5
5
  * [Sequelize Paginator](paginator/README.md)
6
6
  * [Sequelize HAL Decorator](hal/README.md)
7
7
  * A logging tool
8
- * A small utility to dump the last commit of the project
8
+ * An HTTP response tool for consistenty formatting error responses
9
+ * A small utility to dump the last commit of the project
@@ -0,0 +1,80 @@
1
+ "use strict"
2
+
3
+ class FormatError extends Error {
4
+ constructor(m) {
5
+ super(m);
6
+ }
7
+ }
8
+
9
+ // helps to clean up response formats for services responding to rest requests
10
+ class S4Formatter {
11
+ constructor() {
12
+ this.defaults = {
13
+ status: 422,
14
+ errors: {}
15
+ };
16
+ }
17
+
18
+ _isArray (value) {
19
+ return value && typeof value === 'object' && value.constructor === Array;
20
+ }
21
+
22
+ _fromHash(error) {
23
+ let response = Object.assign({}, this.defaults);
24
+
25
+ if (error.status) {
26
+ let errorStatus = parseInt(error.status);
27
+
28
+ if ((errorStatus >= 200) && (errorStatus < 522)) {
29
+ response.status = errorStatus
30
+ }
31
+ }
32
+
33
+ if (error.error && (typeof(error.error) === "string")) {
34
+ response.errors["generic"] = { msg: error.error }
35
+ } else if (error.errors) {
36
+ if (this._isArray(error.errors)) {
37
+ // many legacy responses which are errors: ["error_name"]
38
+ error.errors.forEach(function(el, index) {
39
+ response.errors[`generic_${index}`] = { msg: el }
40
+ })
41
+ } else if (typeof(error.errors) === "object") {
42
+ response.errors = error.errors
43
+ }
44
+ }
45
+
46
+ return response;
47
+ }
48
+
49
+ /**
50
+ * Desired Response format
51
+ *{
52
+ * "error": {
53
+ * "status": 422,
54
+ * "errors": {
55
+ * "password": {
56
+ * "location": "body",
57
+ * "param": "password",
58
+ * "value": "mypassword",
59
+ * "msg": "weak"
60
+ * }
61
+ * }
62
+ * },
63
+ * "error_id": "a2ddf895-2aaf-4189-88a2-8e11f6843f91"
64
+ *}
65
+ */
66
+ formatError(error) {
67
+ let response;
68
+ if (error === null) {
69
+ response = this.defaults;
70
+ } else if (typeof(error) === "object") {
71
+ response = this._fromHash(error);
72
+ } else {
73
+ return new FormatError("invalid_error_format");
74
+ }
75
+
76
+ return response;
77
+ }
78
+ }
79
+
80
+ module.exports = new S4Formatter();
@@ -0,0 +1,111 @@
1
+ "use strict"
2
+
3
+ const pathHelper = require("path");
4
+ const logger = require("../logger/s4-logger");
5
+
6
+ class HealthCheckError extends Error {
7
+ constructor(m) {
8
+ super(m);
9
+ }
10
+ }
11
+
12
+ /* Health Checking router + controller for use in all of our modules
13
+ * Example use: Place the following code in your routes file
14
+ *
15
+ * const hc = require("@sera4/essentia").healthCheck;
16
+ * const router = require('express').Router();
17
+ *
18
+ * ....
19
+ * app.use(hc.defaultPath(serverConfigs.api_prefix), hc.routes(router));
20
+ *
21
+ */
22
+
23
+ class HealthCheck {
24
+ constructor() {
25
+ this.defaultResponse = {
26
+ status: 200,
27
+ errors: {}
28
+ };
29
+
30
+ this.defaultPathRoute = `health_check\(.*\)?`
31
+
32
+ this.healthChecks = [];
33
+ }
34
+
35
+ /* call this with an async function, must support wait capability
36
+ *
37
+ * const dbCheck = async () => {
38
+ * return { name: "db", "result": "success", critical: false };
39
+ * }
40
+ */
41
+ addCheck(fcn) {
42
+ this.healthChecks.push(fcn);
43
+ }
44
+
45
+ defaultPath(prefix = "") {
46
+ return `${prefix}/${this.defaultPathRoute}`
47
+ }
48
+
49
+ routes(router) {
50
+ if (!router) {
51
+ throw new HealthCheckError("missing_express_router");
52
+ }
53
+
54
+ /* definition of all routes, rooted at defaultPath */
55
+ router.get('/', (req, res) => {
56
+ this.checkHealth(req, res)
57
+ });
58
+
59
+ return router
60
+ }
61
+
62
+ /* performs health checks and returns 200 if true and 500 if not */
63
+ async checkHealth(req, res) {
64
+ const checkFormat = pathHelper.extname(req.baseUrl);
65
+
66
+ try {
67
+ const result = await Promise.all(this.healthChecks.map(async healthCallback => {
68
+ return await healthCallback();
69
+ }));
70
+
71
+ //let result = (result.reduce((e) => e.success, 200))
72
+ let status = this.defaultResponse.status;
73
+
74
+ result.some(e => {
75
+ if (e.result.match(/fail/)) {
76
+ status = 500;
77
+ return true; // break
78
+ }
79
+ })
80
+
81
+ if (checkFormat === ".json") {
82
+ if (status === 200) {
83
+ res.status(status).json({
84
+ "healthy":true,
85
+
86
+ "message":"success"
87
+ });
88
+ } else {
89
+ res.status(status).json({
90
+ "healthy": false,
91
+ "message": "fail",
92
+ "services": [result]
93
+ });
94
+ }
95
+ } else {
96
+ let status_message;
97
+ if (status === 200) {
98
+ status_message = "success"
99
+ } else {
100
+ status_message = "fail"
101
+ }
102
+
103
+ res.status(status).send(status_message);
104
+ }
105
+ } catch(error) {
106
+ res.status(500).send();
107
+ }
108
+ }
109
+ }
110
+
111
+ module.exports = HealthCheck;
package/index.js CHANGED
@@ -1,7 +1,12 @@
1
+ 'use strict';
2
+
1
3
  module.exports = {
2
4
  paginator : require("./paginator/s4-pagination"),
3
5
  sqlPaginator : require("./paginator/sql-pagination"),
4
6
  logger : require("./logger/s4-logger"),
5
7
  lastCommit : require("./last_commit"),
6
- halDecorator : require("./hal")
7
- }
8
+ halDecorator : require("./hal"),
9
+ formatter : require("./formatter"),
10
+ healthCheck: require("./health")
11
+ }
12
+ //console.log(module.exports.formatter.formatError({ status: 200, error: ["error1"] }));
@@ -11,7 +11,7 @@ logger.add(winston.transports.Console, {
11
11
 
12
12
  class S4Logger {
13
13
  setLevel(level) {
14
- if (level && ["debug", "info", "error"].indexOf(level.toLowerCase())) {
14
+ if (level && ["debug", "info", "error", "warn"].indexOf(level.toLowerCase())) {
15
15
  logger.transports[loggerName].level = level;
16
16
  }
17
17
  }
@@ -24,6 +24,9 @@ class S4Logger {
24
24
  debug(str, args) {
25
25
  logger.log("debug", str, args);
26
26
  }
27
+ warn(str, args) {
28
+ logger.log("warn", str, args);
29
+ }
27
30
  info(str, args) {
28
31
  logger.log("info", str, args);
29
32
  }
@@ -32,4 +35,4 @@ class S4Logger {
32
35
  }
33
36
  }
34
37
 
35
- module.exports = new S4Logger();
38
+ module.exports = new S4Logger();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sera4/essentia",
3
- "version": "1.0.9",
3
+ "version": "1.0.11",
4
4
  "description": "A library of utilities for Teleporte Web Services",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -16,6 +16,7 @@
16
16
  "license": "UNLICENSED",
17
17
  "devDependencies": {
18
18
  "chai": "^4.1.2",
19
+ "express": "^4.16.4",
19
20
  "mocha": "^5.1.1",
20
21
  "mocha-junit-reporter": "^1.17.0",
21
22
  "node-mocks-http": "^1.5.8",
package/package.tar.gz CHANGED
Binary file