binhend 1.1.7 → 1.1.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "binhend",
3
- "version": "1.1.7",
3
+ "version": "1.1.9",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "author": "Nguyen Duc Binh",
package/src/api.js CHANGED
@@ -43,6 +43,7 @@ function APIs(rootpath) {
43
43
  const router = express.Router();
44
44
  router.use(express.urlencoded({ extended: false }));
45
45
  router.use(express.json());
46
+ router.use(parseAuthToken);
46
47
 
47
48
  setTimeout(function() {
48
49
  mapAPIs(rootpath, router);
@@ -51,6 +52,14 @@ function APIs(rootpath) {
51
52
  return router;
52
53
  }
53
54
 
55
+ function parseAuthToken(request, response, next) {
56
+ var authString = request.headers['authorization'];
57
+ if (typeof authString === 'string' && authString.startsWith('Bearer ')) {
58
+ request.token = authString.split('Bearer ')[1];
59
+ }
60
+ next();
61
+ }
62
+
54
63
  function Router(module) {
55
64
  var router = express.Router();
56
65
 
@@ -66,9 +75,32 @@ function Router(module) {
66
75
  module.exports = router;
67
76
  }
68
77
 
78
+ output.trycatch = trycatch;
79
+
69
80
  return output;
70
81
  }
71
82
 
83
+ function trycatch(callback, onerror) {
84
+ return async function(request, response, next) {
85
+ try {
86
+ return await callback(request, response, next);
87
+ }
88
+ catch (error) {
89
+ if (onerror instanceof Function) return onerror(error);
90
+ var message = error instanceof HttpError && error.message || 'Internal Server Error';
91
+ response.status(error.code || 500).json({ error: message });
92
+ }
93
+ }
94
+ }
95
+
96
+ class HttpError extends Error {
97
+ constructor(code, message) {
98
+ super(message);
99
+ this.name = 'HttpError';
100
+ this.code = code;
101
+ }
102
+ }
103
+
72
104
  module.exports = {
73
- APIs, Router
105
+ APIs, Router, HttpError
74
106
  };
@@ -3,7 +3,7 @@ const os = require('os');
3
3
  const cluster = require('cluster');
4
4
  const path = require('path');
5
5
  const { Server } = require('./server');
6
- const { APIs, Router } = require('./api');
6
+ const { APIs, Router, HttpError } = require('./api');
7
7
 
8
8
  const maxcpus = os.cpus().length;
9
9
 
@@ -15,6 +15,8 @@ function ServerApp(binh, Binh, configloader) {
15
15
  return Router(module);
16
16
  };
17
17
 
18
+ binh.HttpError = HttpError;
19
+
18
20
  Binh.api = function(apiPath) {
19
21
  pathAPI = path.join(rootpath, apiPath);
20
22
  return Binh;