express-ext 0.1.10 → 0.1.14

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.
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.map = {
4
+ TRACE: -2,
5
+ DEBUG: -1,
6
+ INFO: 0,
7
+ WARN: 1,
8
+ ERROR: 2,
9
+ PANIC: 3,
10
+ FATAL: 4
11
+ };
12
+ var LogController = (function () {
13
+ function LogController(logger, mp) {
14
+ this.logger = logger;
15
+ this.map = (mp ? mp : exports.map);
16
+ this.config = this.config.bind(this);
17
+ }
18
+ LogController.prototype.config = function (req, res) {
19
+ var obj = req.body;
20
+ if (!obj || obj === '') {
21
+ return res.status(400).end('The request body cannot be empty');
22
+ }
23
+ if (!this.logger) {
24
+ return res.status(503).end('Logger is not available');
25
+ }
26
+ var changed = false;
27
+ if (typeof obj.level === 'string' && obj.level.length > 0) {
28
+ if (!this.map) {
29
+ return res.status(503).end('Map is not available');
30
+ }
31
+ var lv = this.map[obj.level.toUpperCase()];
32
+ if (lv !== undefined) {
33
+ this.logger.level = lv;
34
+ changed = true;
35
+ }
36
+ }
37
+ if (obj.map) {
38
+ if (typeof obj.map.level === 'string' && obj.map.level.length > 0) {
39
+ this.logger.map.level = obj.map.level;
40
+ changed = true;
41
+ }
42
+ if (typeof obj.map.time === 'string' && obj.map.time.length > 0) {
43
+ this.logger.map.time = obj.map.time;
44
+ changed = true;
45
+ }
46
+ if (typeof obj.map.msg === 'string' && obj.map.msg.length > 0) {
47
+ this.logger.map.msg = obj.map.msg;
48
+ changed = true;
49
+ }
50
+ }
51
+ if (obj.constants !== undefined && typeof obj.constants === 'object') {
52
+ this.logger.constants = obj.constants;
53
+ changed = true;
54
+ }
55
+ if (obj.name) {
56
+ if (typeof obj.name.trace === 'string'
57
+ && typeof obj.name.debug === 'string'
58
+ && typeof obj.name.info === 'string'
59
+ && typeof obj.name.warn === 'string'
60
+ && typeof obj.name.error === 'string'
61
+ && typeof obj.name.panic === 'string'
62
+ && typeof obj.name.fatal === 'string') {
63
+ this.logger.name = obj.name;
64
+ changed = true;
65
+ }
66
+ }
67
+ if (changed) {
68
+ return res.status(200).end('true');
69
+ }
70
+ else {
71
+ return res.status(204).end('false');
72
+ }
73
+ };
74
+ return LogController;
75
+ }());
76
+ exports.LogController = LogController;
package/lib/index.js CHANGED
@@ -1,2 +1 @@
1
- "use strict";function __export(m){for(var p in m)if(!exports.hasOwnProperty(p))exports[p]=m[p]}
2
- Object.defineProperty(exports,"__esModule",{value:!0});var GenericController_1=require("./GenericController");exports.GenericHandler=GenericController_1.GenericController;var GenericSearchController_1=require("./GenericSearchController");exports.GenericSearchHandler=GenericSearchController_1.GenericSearchController;var HealthController_1=require("./HealthController");exports.HealthHandler=HealthController_1.HealthController;var LoadController_1=require("./LoadController");exports.LoadHandler=LoadController_1.LoadController;exports.ViewHandler=LoadController_1.LoadController;exports.ViewController=LoadController_1.LoadController;var LoadSearchController_1=require("./LoadSearchController");exports.LoadSearchHandler=LoadSearchController_1.LoadSearchController;var LowCodeController_1=require("./LowCodeController");exports.LowCodeHandler=LowCodeController_1.LowCodeController;exports.Handler=LowCodeController_1.LowCodeController;exports.Controller=LowCodeController_1.LowCodeController;var SearchController_1=require("./SearchController");exports.SearchHandler=SearchController_1.SearchController;__export(require("./health"));__export(require("./HealthController"));__export(require("./http"));__export(require("./view"));__export(require("./LoadController"));__export(require("./search_func"));__export(require("./search"));__export(require("./SearchController"));__export(require("./LoadSearchController"));__export(require("./resources"));__export(require("./edit"));__export(require("./GenericController"));__export(require("./GenericSearchController"));__export(require("./LowCodeController"))
1
+ "use strict";function __export(r){for(var e in r)exports.hasOwnProperty(e)||(exports[e]=r[e])}Object.defineProperty(exports,"__esModule",{value:!0});var GenericController_1=require("./GenericController");exports.GenericHandler=GenericController_1.GenericController;var GenericSearchController_1=require("./GenericSearchController");exports.GenericSearchHandler=GenericSearchController_1.GenericSearchController;var HealthController_1=require("./HealthController");exports.HealthHandler=HealthController_1.HealthController;var LoadController_1=require("./LoadController");exports.LoadHandler=LoadController_1.LoadController,exports.ViewHandler=LoadController_1.LoadController,exports.ViewController=LoadController_1.LoadController;var LoadSearchController_1=require("./LoadSearchController");exports.LoadSearchHandler=LoadSearchController_1.LoadSearchController;var LogController_1=require("./LogController");exports.LogHandler=LogController_1.LogController;var LowCodeController_1=require("./LowCodeController");exports.LowCodeHandler=LowCodeController_1.LowCodeController,exports.Handler=LowCodeController_1.LowCodeController,exports.Controller=LowCodeController_1.LowCodeController;var SearchController_1=require("./SearchController");exports.SearchHandler=SearchController_1.SearchController,__export(require("./health")),__export(require("./HealthController")),__export(require("./LogController")),__export(require("./log")),__export(require("./http")),__export(require("./view")),__export(require("./LoadController")),__export(require("./search_func")),__export(require("./search")),__export(require("./SearchController")),__export(require("./LoadSearchController")),__export(require("./resources")),__export(require("./edit")),__export(require("./GenericController")),__export(require("./GenericSearchController")),__export(require("./LowCodeController"));
package/lib/log.js ADDED
@@ -0,0 +1,211 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ var stream_1 = require("stream");
4
+ function createConfig(c) {
5
+ if (!c) {
6
+ return { skips: [], duration: 'duration', request: '', response: '', status: '', size: '' };
7
+ }
8
+ var l = {
9
+ log: c.log,
10
+ separate: c.separate,
11
+ skips: c.skips ? c.skips.split(',') : [],
12
+ duration: c.duration ? c.duration : 'duration',
13
+ request: c.request ? c.request : '',
14
+ response: c.response ? c.response : '',
15
+ status: c.status ? c.status : '',
16
+ size: c.size ? c.size : ''
17
+ };
18
+ return l;
19
+ }
20
+ exports.createConfig = createConfig;
21
+ function skip(skips, url) {
22
+ if (skips.length === 0) {
23
+ return false;
24
+ }
25
+ var u = removeUrlParams(url);
26
+ for (var _i = 0, skips_1 = skips; _i < skips_1.length; _i++) {
27
+ var s = skips_1[_i];
28
+ if (u.endsWith(s)) {
29
+ return true;
30
+ }
31
+ }
32
+ return false;
33
+ }
34
+ exports.skip = skip;
35
+ function removeUrlParams(url) {
36
+ var startParams = url.indexOf('?');
37
+ return startParams !== -1 ? url.substring(0, startParams) : url;
38
+ }
39
+ exports.removeUrlParams = removeUrlParams;
40
+ var MiddlewareLogger = (function () {
41
+ function MiddlewareLogger(write, conf, build) {
42
+ this.write = write;
43
+ this.build = build;
44
+ this.log = this.log.bind(this);
45
+ this.conf = createConfig(conf);
46
+ }
47
+ MiddlewareLogger.prototype.log = function (req, res, next) {
48
+ var _this = this;
49
+ if (this.conf.log && !skip(this.conf.skips, req.originalUrl)) {
50
+ var start_1 = process.hrtime();
51
+ var m = req.method;
52
+ var x_1 = this.conf.request;
53
+ var r_1 = false;
54
+ if (m !== 'GET' && m !== 'DELETE') {
55
+ r_1 = true;
56
+ }
57
+ var msg_1 = m + " " + req.originalUrl;
58
+ if (this.conf.separate && r_1) {
59
+ if (this.conf.request.length > 0) {
60
+ var op = {};
61
+ op[x_1] = JSON.stringify(req.body);
62
+ if (this.build) {
63
+ var op2 = this.build(req, op);
64
+ this.write(msg_1, op2);
65
+ }
66
+ else {
67
+ this.write(msg_1, op);
68
+ }
69
+ }
70
+ }
71
+ var chunks_1 = [];
72
+ mapResponseBody(res, chunks_1);
73
+ res.on('finish', function () {
74
+ var duration = getDurationInMilliseconds(start_1);
75
+ var op = {};
76
+ if (r_1 && !_this.conf.separate && _this.conf.request.length > 0) {
77
+ op[x_1] = JSON.stringify(req.body);
78
+ }
79
+ if (_this.conf.response.length > 0) {
80
+ var rsBody = Buffer.concat(chunks_1).toString();
81
+ op[_this.conf.response] = rsBody;
82
+ }
83
+ if (_this.conf.status.length > 0) {
84
+ op[_this.conf.status] = res.statusCode;
85
+ }
86
+ if (_this.conf.size.length > 0) {
87
+ if ('_contentLength' in res) {
88
+ op[_this.conf.size] = res['_contentLength'];
89
+ }
90
+ else if (res.hasHeader('content-length')) {
91
+ var l = res.getHeader('content-length');
92
+ if (typeof l === 'number' || typeof l === 'string') {
93
+ op[_this.conf.size] = l;
94
+ }
95
+ }
96
+ }
97
+ op[_this.conf.duration] = duration;
98
+ if (_this.build) {
99
+ var op2 = _this.build(req, op);
100
+ _this.write(msg_1, op2);
101
+ }
102
+ else {
103
+ _this.write(msg_1, op);
104
+ }
105
+ });
106
+ next();
107
+ }
108
+ else {
109
+ next();
110
+ }
111
+ };
112
+ return MiddlewareLogger;
113
+ }());
114
+ exports.MiddlewareLogger = MiddlewareLogger;
115
+ var mapResponseBody = function (res, chunks) {
116
+ var defaultWrite = res.write.bind(res);
117
+ var defaultEnd = res.end.bind(res);
118
+ var ps = new stream_1.PassThrough();
119
+ ps.on('data', function (data) { return chunks.push(data); });
120
+ res.write = function () {
121
+ var _a;
122
+ var args = [];
123
+ for (var _i = 0; _i < arguments.length; _i++) {
124
+ args[_i] = arguments[_i];
125
+ }
126
+ (_a = ps).write.apply(_a, args);
127
+ defaultWrite.apply(void 0, args);
128
+ };
129
+ res.end = function () {
130
+ var args = [];
131
+ for (var _i = 0; _i < arguments.length; _i++) {
132
+ args[_i] = arguments[_i];
133
+ }
134
+ ps.end.apply(ps, args);
135
+ defaultEnd.apply(void 0, args);
136
+ };
137
+ };
138
+ var NS_PER_SEC = 1e9;
139
+ var NS_TO_MS = 1e6;
140
+ var getDurationInMilliseconds = function (start) {
141
+ var diff = process.hrtime(start);
142
+ return (diff[0] * NS_PER_SEC + diff[1]) / NS_TO_MS;
143
+ };
144
+ var MiddlewareController = (function () {
145
+ function MiddlewareController(logger) {
146
+ this.logger = logger;
147
+ this.config = this.config.bind(this);
148
+ }
149
+ MiddlewareController.prototype.config = function (req, res) {
150
+ var obj = req.body;
151
+ if (!obj || obj === '') {
152
+ return res.status(400).end('The request body cannot be empty');
153
+ }
154
+ if (!this.logger) {
155
+ return res.status(503).end('Logger is not available');
156
+ }
157
+ var changed = false;
158
+ if (obj.log !== undefined) {
159
+ this.logger.conf.log = obj.log;
160
+ changed = true;
161
+ }
162
+ if (obj.separate !== undefined) {
163
+ this.logger.conf.separate = obj.separate;
164
+ changed = true;
165
+ }
166
+ if (Array.isArray(obj.skips)) {
167
+ if (isValidSkips(obj.skips)) {
168
+ this.logger.conf.skips = obj.skips;
169
+ changed = true;
170
+ }
171
+ }
172
+ if (typeof obj.duration === 'string' && obj.duration.length > 0) {
173
+ this.logger.conf.duration = obj.duration;
174
+ changed = true;
175
+ }
176
+ if (typeof obj.request === 'string') {
177
+ this.logger.conf.request = obj.request;
178
+ changed = true;
179
+ }
180
+ if (typeof obj.response === 'string') {
181
+ this.logger.conf.response = obj.response;
182
+ changed = true;
183
+ }
184
+ if (typeof obj.status === 'string') {
185
+ this.logger.conf.status = obj.status;
186
+ changed = true;
187
+ }
188
+ if (typeof obj.size === 'string') {
189
+ this.logger.conf.size = obj.size;
190
+ changed = true;
191
+ }
192
+ if (changed) {
193
+ return res.status(200).end('true');
194
+ }
195
+ else {
196
+ return res.status(204).end('false');
197
+ }
198
+ };
199
+ return MiddlewareController;
200
+ }());
201
+ exports.MiddlewareController = MiddlewareController;
202
+ function isValidSkips(s) {
203
+ for (var _i = 0, s_1 = s; _i < s_1.length; _i++) {
204
+ var x = s_1[_i];
205
+ if (!(typeof x === 'string')) {
206
+ return false;
207
+ }
208
+ }
209
+ return true;
210
+ }
211
+ exports.isValidSkips = isValidSkips;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "express-ext",
3
- "version": "0.1.10",
3
+ "version": "0.1.14",
4
4
  "description": "express-ext",
5
5
  "main": "./lib/index.js",
6
6
  "types": "./src/index.ts",
@@ -1,6 +1,6 @@
1
1
  import {Request, Response} from 'express';
2
2
  import {checkId, create, initializeStatus, isTypeError, ResultInfo, StatusConfig, update} from './edit';
3
- import {handleError} from './http';
3
+ import {handleError, Log} from './http';
4
4
  import {LoadController} from './LoadController';
5
5
  import {Attribute, Attributes, ErrorMessage} from './metadata';
6
6
  import {resources} from './resources';
@@ -17,7 +17,7 @@ export interface GenericService<T, ID, R> {
17
17
  export class GenericController<T, ID> extends LoadController<T, ID> {
18
18
  status: StatusConfig;
19
19
  metadata?: Attributes;
20
- constructor(log: (msg: any, ctx?: any) => void, public service: GenericService<T, ID, number|ResultInfo<T>>, status?: StatusConfig, public validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>) {
20
+ constructor(log: Log, public service: GenericService<T, ID, number|ResultInfo<T>>, status?: StatusConfig, public validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>) {
21
21
  super(log, service);
22
22
  this.status = initializeStatus(status);
23
23
  if (service.metadata) {
@@ -67,7 +67,7 @@ export class GenericController<T, ID> extends LoadController<T, ID> {
67
67
  }
68
68
  }
69
69
  }
70
- export function validateAndCreate<T>(req: Request, res: Response, status: StatusConfig, save: (obj: T, ctx?: any) => Promise<number|ResultInfo<T>>, log: (msg: any, ctx?: any) => void, validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>): void {
70
+ export function validateAndCreate<T>(req: Request, res: Response, status: StatusConfig, save: (obj: T, ctx?: any) => Promise<number|ResultInfo<T>>, log: Log, validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>): void {
71
71
  const obj = req.body;
72
72
  if (!obj || obj === '') {
73
73
  return res.status(400).end('The request body cannot be empty.');
@@ -85,7 +85,7 @@ export function validateAndCreate<T>(req: Request, res: Response, status: Status
85
85
  create(res, status, obj, save, log);
86
86
  }
87
87
  }
88
- export function validateAndUpdate<T>(res: Response, status: StatusConfig, obj: T, isPatch: boolean, save: (obj: T, ctx?: any) => Promise<number|ResultInfo<T>>, log: (msg: any, ctx?: any) => void, validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>): void {
88
+ export function validateAndUpdate<T>(res: Response, status: StatusConfig, obj: T, isPatch: boolean, save: (obj: T, ctx?: any) => Promise<number|ResultInfo<T>>, log: Log, validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>): void {
89
89
  if (validate) {
90
90
  validate(obj, isPatch).then(errors => {
91
91
  if (errors && errors.length > 0) {
@@ -1,7 +1,7 @@
1
1
  import {Request, Response} from 'express';
2
2
  import {ResultInfo, StatusConfig} from './edit';
3
3
  import {GenericController, GenericService} from './GenericController';
4
- import {handleError} from './http';
4
+ import {handleError, Log} from './http';
5
5
  import {ErrorMessage} from './metadata';
6
6
  import {Filter, format, fromRequest, getParameters, initializeConfig, jsonResult, SearchConfig, SearchResult} from './search';
7
7
  import {getMetadataFunc} from './search_func';
@@ -15,7 +15,7 @@ export class GenericSearchController<T, ID, S extends Filter> extends GenericCon
15
15
  numbers?: string[];
16
16
  fields?: string;
17
17
  excluding?: string;
18
- constructor(log: (msg: any, ctx?: any) => void, public find: (s: S, limit?: number, skip?: number|string, fields?: string[]) => Promise<SearchResult<T>>, service: GenericService<T, ID, number|ResultInfo<T>>, config?: Config, validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>, dates?: string[], numbers?: string[]) {
18
+ constructor(log: Log, public find: (s: S, limit?: number, skip?: number|string, fields?: string[]) => Promise<SearchResult<T>>, service: GenericService<T, ID, number|ResultInfo<T>>, config?: Config, validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>, dates?: string[], numbers?: string[]) {
19
19
  super(log, service, config, validate);
20
20
  this.search = this.search.bind(this);
21
21
  this.config = initializeConfig(config);
@@ -1,5 +1,5 @@
1
1
  import {Request, Response} from 'express';
2
- import {attrs, handleError, respondModel} from './http';
2
+ import {attrs, handleError, Log, respondModel} from './http';
3
3
  import {Attribute, Attributes} from './metadata';
4
4
  import {buildAndCheckId, buildKeys} from './view';
5
5
 
@@ -39,7 +39,7 @@ function getKeysFunc<T, ID>(viewService: ViewService<T, ID> | ((id: ID, ctx?: an
39
39
  export class LoadController<T, ID> {
40
40
  protected keys?: Attribute[];
41
41
  protected view: (id: ID, ctx?: any) => Promise<T|null>;
42
- constructor(protected log: (msg: any, ctx?: any) => void, viewService: ViewService<T, ID> | ((id: ID, ctx?: any) => Promise<T|null>), keys?: Attributes|Attribute[]|string[]) {
42
+ constructor(protected log: Log, viewService: ViewService<T, ID> | ((id: ID, ctx?: any) => Promise<T|null>), keys?: Attributes|Attribute[]|string[]) {
43
43
  this.load = this.load.bind(this);
44
44
  this.view = getViewFunc(viewService);
45
45
  this.keys = getKeysFunc(viewService, keys);
@@ -1,5 +1,5 @@
1
1
  import {Request, Response} from 'express';
2
- import {handleError} from './http';
2
+ import {handleError, Log} from './http';
3
3
  import {LoadController, ViewService} from './LoadController';
4
4
  import {Attribute, Attributes} from './metadata';
5
5
  import {Filter, format, fromRequest, getParameters, initializeConfig, jsonResult, SearchConfig, SearchResult} from './search';
@@ -12,7 +12,7 @@ export class LoadSearchController<T, ID, S extends Filter> extends LoadControlle
12
12
  numbers?: string[];
13
13
  fields?: string;
14
14
  excluding?: string;
15
- constructor(log: (msg: any, ctx?: any) => void, public find: (s: S, limit?: number, skip?: number|string, fields?: string[]) => Promise<SearchResult<T>>, viewService: ViewService<T, ID> | ((id: ID, ctx?: any) => Promise<T>), keys?: Attributes|Attribute[]|string[], config?: SearchConfig|boolean, dates?: string[], numbers?: string[]) {
15
+ constructor(log: Log, public find: (s: S, limit?: number, skip?: number|string, fields?: string[]) => Promise<SearchResult<T>>, viewService: ViewService<T, ID> | ((id: ID, ctx?: any) => Promise<T>), keys?: Attributes|Attribute[]|string[], config?: SearchConfig|boolean, dates?: string[], numbers?: string[]) {
16
16
  super(log, viewService, keys);
17
17
  this.search = this.search.bind(this);
18
18
  if (config) {
@@ -0,0 +1,123 @@
1
+ import { Request, Response } from 'express';
2
+ import { SimpleMap } from './log';
3
+
4
+ export interface NumberMap {
5
+ [key: string]: number;
6
+ }
7
+ export interface LogConf {
8
+ level?: string;
9
+ map?: LogMapConfig;
10
+ constants?: SimpleMap;
11
+ name?: Name;
12
+ }
13
+ export interface LogMapConfig {
14
+ time?: string;
15
+ level?: string;
16
+ msg?: string;
17
+ }
18
+ export interface LogMap {
19
+ time: string;
20
+ level: string;
21
+ msg: string;
22
+ }
23
+ export interface Name {
24
+ trace: string;
25
+ debug: string;
26
+ info: string;
27
+ warn: string;
28
+ error: string;
29
+ panic: string;
30
+ fatal: string;
31
+ }
32
+ export interface Logger {
33
+ name: Name;
34
+ level: number;
35
+ map: LogMap;
36
+ constants?: SimpleMap;
37
+ trace(msg: string, m?: SimpleMap, ctx?: any): void;
38
+ debug(msg: string, m?: SimpleMap, ctx?: any): void;
39
+ info(msg: string, m?: SimpleMap, ctx?: any): void;
40
+ warn(msg: string, m?: SimpleMap, ctx?: any): void;
41
+ error(msg: string, m?: SimpleMap, ctx?: any): void;
42
+ panic(msg: string, m?: SimpleMap, ctx?: any): void;
43
+ fatal(msg: string, m?: SimpleMap, ctx?: any): void;
44
+ isLevelEnabled(level: number): boolean;
45
+ isTraceEnabled(): boolean;
46
+ isDebugEnabled(): boolean;
47
+ isInfoEnabled(): boolean;
48
+ isWarnEnabled(): boolean;
49
+ isErrorEnabled(): boolean;
50
+ isPanicEnabled(): boolean;
51
+ isFatalEnabled(): boolean;
52
+ }
53
+ export const map: NumberMap = {
54
+ TRACE: -2,
55
+ DEBUG: -1,
56
+ INFO: 0,
57
+ WARN: 1,
58
+ ERROR: 2,
59
+ PANIC: 3,
60
+ FATAL: 4
61
+ };
62
+ export class LogController {
63
+ map: NumberMap;
64
+ constructor(public logger: Logger, mp?: NumberMap) {
65
+ this.map = (mp ? mp : map);
66
+ this.config = this.config.bind(this);
67
+ }
68
+ config(req: Request, res: Response) {
69
+ const obj: LogConf = req.body;
70
+ if (!obj || obj === '') {
71
+ return res.status(400).end('The request body cannot be empty');
72
+ }
73
+ if (!this.logger) {
74
+ return res.status(503).end('Logger is not available');
75
+ }
76
+ let changed = false;
77
+ if (typeof obj.level === 'string' && obj.level.length > 0) {
78
+ if (!this.map) {
79
+ return res.status(503).end('Map is not available');
80
+ }
81
+ const lv = this.map[obj.level.toUpperCase()];
82
+ if (lv !== undefined) {
83
+ this.logger.level = lv;
84
+ changed = true;
85
+ }
86
+ }
87
+ if (obj.map) {
88
+ if (typeof obj.map.level === 'string' && obj.map.level.length > 0) {
89
+ this.logger.map.level = obj.map.level;
90
+ changed = true;
91
+ }
92
+ if (typeof obj.map.time === 'string' && obj.map.time.length > 0) {
93
+ this.logger.map.time = obj.map.time;
94
+ changed = true;
95
+ }
96
+ if (typeof obj.map.msg === 'string' && obj.map.msg.length > 0) {
97
+ this.logger.map.msg = obj.map.msg;
98
+ changed = true;
99
+ }
100
+ }
101
+ if (obj.constants !== undefined && typeof obj.constants === 'object') {
102
+ this.logger.constants = obj.constants;
103
+ changed = true;
104
+ }
105
+ if (obj.name) {
106
+ if (typeof obj.name.trace === 'string'
107
+ && typeof obj.name.debug === 'string'
108
+ && typeof obj.name.info === 'string'
109
+ && typeof obj.name.warn === 'string'
110
+ && typeof obj.name.error === 'string'
111
+ && typeof obj.name.panic === 'string'
112
+ && typeof obj.name.fatal === 'string') {
113
+ this.logger.name = obj.name;
114
+ changed = true;
115
+ }
116
+ }
117
+ if (changed) {
118
+ return res.status(200).end('true');
119
+ } else {
120
+ return res.status(204).end('false');
121
+ }
122
+ }
123
+ }
@@ -1,7 +1,7 @@
1
1
  import {Request, Response} from 'express';
2
2
  import {ResultInfo, StatusConfig} from './edit';
3
3
  import {GenericController, GenericService} from './GenericController';
4
- import {handleError} from './http';
4
+ import {handleError, Log} from './http';
5
5
  import {ErrorMessage} from './metadata';
6
6
  import {Filter, format, fromRequest, getParameters, initializeConfig, jsonResult, SearchConfig, SearchResult} from './search';
7
7
  import {getMetadataFunc} from './search_func';
@@ -18,7 +18,7 @@ export class LowCodeController<T, ID, S extends Filter> extends GenericControlle
18
18
  numbers?: string[];
19
19
  fields?: string;
20
20
  excluding?: string;
21
- constructor(log: (msg: any, ctx?: any) => void, public lowCodeService: Service<T, ID, number|ResultInfo<T>, S>, config?: LowCodeConfig, validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>, dates?: string[], numbers?: string[]) {
21
+ constructor(log: Log, public lowCodeService: Service<T, ID, number|ResultInfo<T>, S>, config?: LowCodeConfig, validate?: (obj: T, patch?: boolean) => Promise<ErrorMessage[]>, dates?: string[], numbers?: string[]) {
22
22
  super(log, lowCodeService, config, validate);
23
23
  this.search = this.search.bind(this);
24
24
  this.config = initializeConfig(config);
@@ -1,5 +1,5 @@
1
1
  import {Request, Response} from 'express';
2
- import {handleError} from './http';
2
+ import {handleError, Log} from './http';
3
3
  import {Filter, format, fromRequest, getParameters, initializeConfig, jsonResult, SearchConfig, SearchResult} from './search';
4
4
 
5
5
  export class SearchController<T, S extends Filter> {
@@ -7,7 +7,7 @@ export class SearchController<T, S extends Filter> {
7
7
  csv?: boolean;
8
8
  fields?: string;
9
9
  excluding?: string;
10
- constructor(protected log: (msg: any, ctx?: any) => void, public find: (s: S, limit?: number, skip?: number|string, fields?: string[]) => Promise<SearchResult<T>>, config?: SearchConfig|boolean, public dates?: string[], public numbers?: string[]) {
10
+ constructor(protected log: Log, public find: (s: S, limit?: number, skip?: number|string, fields?: string[]) => Promise<SearchResult<T>>, config?: SearchConfig|boolean, public dates?: string[], public numbers?: string[]) {
11
11
  this.search = this.search.bind(this);
12
12
  if (config) {
13
13
  if (typeof config === 'boolean') {
package/src/http.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import {Request, Response} from 'express';
2
2
  import {Attribute} from './metadata';
3
3
 
4
- export function handleError(err: any, res: Response, log?: (msg: any, ctx?: any) => void) {
4
+ export type Log = (msg: string) => void;
5
+ export type LogFunc = Log;
6
+ export function handleError(err: any, res: Response, log?: (msg: string) => void) {
5
7
  if (log) {
6
8
  log(toString(err));
7
9
  res.status(500).end('Internal Server Error');
package/src/index.ts CHANGED
@@ -3,11 +3,13 @@ import {GenericSearchController} from './GenericSearchController';
3
3
  import {HealthController} from './HealthController';
4
4
  import {LoadController} from './LoadController';
5
5
  import {LoadSearchController} from './LoadSearchController';
6
+ import {LogController} from './LogController';
6
7
  import {LowCodeController} from './LowCodeController';
7
8
  import {Service} from './LowCodeController';
8
9
  import {SearchController} from './SearchController';
9
10
 
10
11
  export {HealthController as HealthHandler};
12
+ export {LogController as LogHandler};
11
13
  export {LoadController as LoadHandler};
12
14
  export {LoadController as ViewHandler};
13
15
  export {LoadController as ViewController};
@@ -23,6 +25,8 @@ export {Service as LowCodeService};
23
25
 
24
26
  export * from './health';
25
27
  export * from './HealthController';
28
+ export * from './LogController';
29
+ export * from './log';
26
30
  export * from './http';
27
31
  export * from './metadata';
28
32
  export * from './view';
package/src/log.ts ADDED
@@ -0,0 +1,216 @@
1
+ import { NextFunction } from 'express';
2
+ import { ParamsDictionary, Request, Response } from 'express-serve-static-core';
3
+ import { ParsedQs } from 'qs';
4
+ import { PassThrough } from 'stream';
5
+
6
+ export interface LogConfig {
7
+ log?: boolean;
8
+ separate?: boolean;
9
+ skips?: string;
10
+ request?: string;
11
+ response?: string;
12
+ duration?: string;
13
+ status?: string;
14
+ size?: string;
15
+ }
16
+ export interface MiddleLog {
17
+ log?: boolean;
18
+ separate?: boolean;
19
+ skips: string[];
20
+ duration: string;
21
+ request: string;
22
+ response: string;
23
+ status: string;
24
+ size: string;
25
+ }
26
+ export interface SimpleMap {
27
+ [key: string]: string|number|boolean|Date;
28
+ }
29
+ export function createConfig(c?: LogConfig): MiddleLog {
30
+ if (!c) {
31
+ return {skips: [], duration: 'duration', request: '', response: '', status: '', size: ''};
32
+ }
33
+ const l: MiddleLog = {
34
+ log: c.log,
35
+ separate: c.separate,
36
+ skips: c.skips ? c.skips.split(',') : [],
37
+ duration: c.duration ? c.duration : 'duration',
38
+ request: c.request ? c.request : '',
39
+ response: c.response ? c.response : '',
40
+ status: c.status ? c.status : '',
41
+ size: c.size ? c.size : ''
42
+ };
43
+ return l;
44
+ }
45
+ export function skip(skips: string[], url: string): boolean {
46
+ if (skips.length === 0) {
47
+ return false;
48
+ }
49
+ const u = removeUrlParams(url);
50
+ for (const s of skips) {
51
+ if (u.endsWith(s)) {
52
+ return true;
53
+ }
54
+ }
55
+ return false;
56
+ }
57
+ export function removeUrlParams(url: string): string {
58
+ const startParams = url.indexOf('?');
59
+ return startParams !== -1 ? url.substring(0, startParams) : url;
60
+ }
61
+ export interface Middleware {
62
+ conf: MiddleLog;
63
+ }
64
+ export class MiddlewareLogger {
65
+ constructor(public write: (msg: string, m?: SimpleMap) => void, conf?: LogConfig, public build?: (req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, m: SimpleMap) => SimpleMap) {
66
+ this.log = this.log.bind(this);
67
+ this.conf = createConfig(conf);
68
+ }
69
+ conf: MiddleLog;
70
+ log(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>, number>, next: NextFunction) {
71
+ if (this.conf.log && !skip(this.conf.skips, req.originalUrl)) {
72
+ const start = process.hrtime();
73
+ const m = req.method;
74
+ const x = this.conf.request;
75
+ let r = false;
76
+ if (m !== 'GET' && m !== 'DELETE') {
77
+ r = true;
78
+ }
79
+ const msg = `${m} ${req.originalUrl}`;
80
+ if (this.conf.separate && r) {
81
+ if (this.conf.request.length > 0) {
82
+ const op: SimpleMap = {};
83
+ op[x] = JSON.stringify(req.body);
84
+ if (this.build) {
85
+ const op2 = this.build(req, op);
86
+ this.write(msg, op2);
87
+ } else {
88
+ this.write(msg, op);
89
+ }
90
+ }
91
+ }
92
+ const chunks: Uint8Array[] = [];
93
+ mapResponseBody(res, chunks);
94
+ res.on('finish', () => {
95
+ const duration = getDurationInMilliseconds(start);
96
+ const op: SimpleMap = {};
97
+ if (r && !this.conf.separate && this.conf.request.length > 0) {
98
+ op[x] = JSON.stringify(req.body);
99
+ }
100
+ if (this.conf.response.length > 0) {
101
+ const rsBody = Buffer.concat(chunks).toString();
102
+ op[this.conf.response] = rsBody;
103
+ }
104
+ if (this.conf.status.length > 0) {
105
+ op[this.conf.status] = res.statusCode;
106
+ }
107
+ if (this.conf.size.length > 0) {
108
+ if ('_contentLength' in res) {
109
+ op[this.conf.size] = (res as any)['_contentLength'];
110
+ } else if (res.hasHeader('content-length')) {
111
+ const l = res.getHeader('content-length');
112
+ if (typeof l === 'number' || typeof l === 'string') {
113
+ op[this.conf.size] = l;
114
+ }
115
+ }
116
+ }
117
+ op[this.conf.duration] = duration;
118
+ if (this.build) {
119
+ const op2 = this.build(req, op);
120
+ this.write(msg, op2);
121
+ } else {
122
+ this.write(msg, op);
123
+ }
124
+ });
125
+ next();
126
+ } else {
127
+ next();
128
+ }
129
+ }
130
+ }
131
+ const mapResponseBody = (res: Response<any, Record<string, any>, number>, chunks: Uint8Array[]) => {
132
+ const defaultWrite = res.write.bind(res);
133
+ const defaultEnd = res.end.bind(res);
134
+ const ps = new PassThrough();
135
+
136
+ ps.on('data', (data: any) => chunks.push(data));
137
+
138
+ (res as any).write = (...args: any) => {
139
+ (ps as any).write(...args);
140
+ (defaultWrite as any)(...args);
141
+ };
142
+
143
+ (res as any).end = (...args: any) => {
144
+ ps.end(...args);
145
+ defaultEnd(...args);
146
+ };
147
+ };
148
+ const NS_PER_SEC = 1e9;
149
+ const NS_TO_MS = 1e6;
150
+ const getDurationInMilliseconds = (start: [number, number] | undefined) => {
151
+ const diff = process.hrtime(start);
152
+ return (diff[0] * NS_PER_SEC + diff[1]) / NS_TO_MS;
153
+ };
154
+
155
+ export class MiddlewareController {
156
+ constructor(public logger: Middleware) {
157
+ this.config = this.config.bind(this);
158
+ }
159
+ config(req: Request, res: Response) {
160
+ const obj: MiddleLog = req.body;
161
+ if (!obj || (obj as any) === '') {
162
+ return res.status(400).end('The request body cannot be empty');
163
+ }
164
+ if (!this.logger) {
165
+ return res.status(503).end('Logger is not available');
166
+ }
167
+ let changed = false;
168
+ if (obj.log !== undefined) {
169
+ this.logger.conf.log = obj.log;
170
+ changed = true;
171
+ }
172
+ if (obj.separate !== undefined) {
173
+ this.logger.conf.separate = obj.separate;
174
+ changed = true;
175
+ }
176
+ if (Array.isArray(obj.skips)) {
177
+ if (isValidSkips(obj.skips)) {
178
+ this.logger.conf.skips = obj.skips;
179
+ changed = true;
180
+ }
181
+ }
182
+ if (typeof obj.duration === 'string' && obj.duration.length > 0) {
183
+ this.logger.conf.duration = obj.duration;
184
+ changed = true;
185
+ }
186
+ if (typeof obj.request === 'string') {
187
+ this.logger.conf.request = obj.request;
188
+ changed = true;
189
+ }
190
+ if (typeof obj.response === 'string') {
191
+ this.logger.conf.response = obj.response;
192
+ changed = true;
193
+ }
194
+ if (typeof obj.status === 'string') {
195
+ this.logger.conf.status = obj.status;
196
+ changed = true;
197
+ }
198
+ if (typeof obj.size === 'string') {
199
+ this.logger.conf.size = obj.size;
200
+ changed = true;
201
+ }
202
+ if (changed) {
203
+ return res.status(200).end('true');
204
+ } else {
205
+ return res.status(204).end('false');
206
+ }
207
+ }
208
+ }
209
+ export function isValidSkips(s: string[]): boolean {
210
+ for (const x of s) {
211
+ if (!(typeof x === 'string')) {
212
+ return false;
213
+ }
214
+ }
215
+ return true;
216
+ }