anote-server-libs 0.9.4 → 0.9.6

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.
@@ -1,65 +1,65 @@
1
- import {Request, Response} from 'express';
2
- import Ajv, {_} from 'ajv';
3
-
4
- export const ajv = new Ajv();
5
- ajv.addKeyword({
6
- keyword: 'maxDigits',
7
- type: 'number',
8
- schemaType: 'number',
9
- validate: (schema: number, data: any) => typeof data === 'number' && Math.round(data * 10 ** schema) / (10 ** schema) === data
10
- });
11
-
12
- export function WithBody(schema: any, collapseTopLevelNulls = true) {
13
- if(schema.type === 'object') {
14
- const required: string[] = [];
15
- const keys = Object.getOwnPropertyNames(schema.properties);
16
- keys.forEach(key => {
17
- if(schema.properties[key].required === true) {
18
- required.push(key);
19
- }
20
- if(schema.properties[key].required === true || schema.properties[key].required === false) {
21
- delete schema.properties[key].required;
22
- }
23
- });
24
- schema.required = required;
25
- }
26
- const validate = ajv.compile(schema);
27
- return function(_: any, __: string, descriptor: PropertyDescriptor) {
28
- if(typeof descriptor.value === 'function') {
29
- const previousMethod = descriptor.value;
30
- descriptor.value = function(this: any, req: Request, res: Response) {
31
- if(req.method.toUpperCase() !== 'POST' && req.method.toUpperCase() !== 'PUT') {
32
- return previousMethod.call(this, req, res);
33
- }
34
- if(!req.body) {
35
- res.status(400).json({
36
- error: {
37
- errorKey: 'client.body.missing',
38
- additionalInfo: 'client.extended.badPayload'
39
- }
40
- });
41
- } else {
42
- if(collapseTopLevelNulls) {
43
- Object.keys(req.body).forEach(k => {
44
- if(req.body[k] === null) delete req.body[k];
45
- });
46
- }
47
- const valid = validate(req.body);
48
- if(valid) {
49
- return previousMethod.call(this, req, res);
50
- } else {
51
- res.status(400).json({
52
- error: {
53
- errorKey: 'client.body.missing',
54
- additionalInfo: 'client.extended.badPayload',
55
- detailedInfo: validate.errors
56
- }
57
- });
58
- }
59
- }
60
- };
61
- return descriptor;
62
- }
63
- return undefined;
64
- };
65
- }
1
+ import {Request, Response} from 'express';
2
+ import Ajv, {_} from 'ajv';
3
+
4
+ export const ajv = new Ajv();
5
+ ajv.addKeyword({
6
+ keyword: 'maxDigits',
7
+ type: 'number',
8
+ schemaType: 'number',
9
+ validate: (schema: number, data: any) => typeof data === 'number' && Math.round(data * 10 ** schema) / (10 ** schema) === data
10
+ });
11
+
12
+ export function WithBody(schema: any, collapseTopLevelNulls = true) {
13
+ if(schema.type === 'object') {
14
+ const required: string[] = [];
15
+ const keys = Object.getOwnPropertyNames(schema.properties);
16
+ keys.forEach(key => {
17
+ if(schema.properties[key].required === true) {
18
+ required.push(key);
19
+ }
20
+ if(schema.properties[key].required === true || schema.properties[key].required === false) {
21
+ delete schema.properties[key].required;
22
+ }
23
+ });
24
+ schema.required = required;
25
+ }
26
+ const validate = ajv.compile(schema);
27
+ return function(_: any, __: string, descriptor: PropertyDescriptor) {
28
+ if(typeof descriptor.value === 'function') {
29
+ const previousMethod = descriptor.value;
30
+ descriptor.value = function(this: any, req: Request, res: Response) {
31
+ if(req.method.toUpperCase() !== 'POST' && req.method.toUpperCase() !== 'PUT') {
32
+ return previousMethod.call(this, req, res);
33
+ }
34
+ if(!req.body) {
35
+ res.status(400).json({
36
+ error: {
37
+ errorKey: 'client.body.missing',
38
+ additionalInfo: 'client.extended.badPayload'
39
+ }
40
+ });
41
+ } else {
42
+ if(collapseTopLevelNulls) {
43
+ Object.keys(req.body).forEach(k => {
44
+ if(req.body[k] === null) delete req.body[k];
45
+ });
46
+ }
47
+ const valid = validate(req.body);
48
+ if(valid) {
49
+ return previousMethod.call(this, req, res);
50
+ } else {
51
+ res.status(400).json({
52
+ error: {
53
+ errorKey: 'client.body.missing',
54
+ additionalInfo: 'client.extended.badPayload',
55
+ detailedInfo: validate.errors
56
+ }
57
+ });
58
+ }
59
+ }
60
+ };
61
+ return descriptor;
62
+ }
63
+ return undefined;
64
+ };
65
+ }
@@ -33,12 +33,13 @@ function withTransaction(repo, logger, previousMethod, lock, commitIfLost = true
33
33
  const dbClient = c1 || c2;
34
34
  clearTimeout(connectTimeoutHandler);
35
35
  utils_1.utils.logger = logger;
36
- if (exports.withTransactionConfig.logQueries) {
36
+ if (exports.withTransactionConfig.logQueries && !dbClient.queryPatched) {
37
37
  const originalQuery = dbClient.query.bind(dbClient);
38
38
  dbClient.query = (...args) => {
39
39
  logger.debug('SQL [Client %d] QUERY: %s', dbClient.processID, args[0]);
40
40
  return originalQuery(...args);
41
41
  };
42
+ dbClient.queryPatched = true;
42
43
  }
43
44
  dbClient.removeAllListeners('error');
44
45
  dbClient.on('error', (err) => utils_1.utils.clientErrorHandler(err, dbClient));
@@ -1,160 +1,161 @@
1
- import {NextFunction, Request, Response} from 'express';
2
- import {Logger} from 'winston';
3
- import {BaseModelRepository} from '../models/repository/BaseModelRepository';
4
- import {jsonStringify, utils} from './utils';
5
-
6
- export const enum SystemLock {
7
- CHECK_CROSSING = 1,
8
- FLUSH_CALLS = 2,
9
- TX_CHECK = 3
10
- }
11
-
12
- export const withTransactionConfig = {
13
- logQueries: false,
14
- timeoutMillis: 15000
15
- };
16
-
17
- export function withTransaction(repo: BaseModelRepository, logger: Logger, previousMethod: (req: Request, res: Response, next: NextFunction) => void, lock?: SystemLock, commitIfLost = true) {
18
- return function(req: Request, res: Response, next: NextFunction) {
19
- let commit = true;
20
- if(!commitIfLost) {
21
- res.once('close', () => commit = false);
22
- }
23
- const endTerminator = res.end.bind(res);
24
- const jsonTerminator = (obj: any) => {
25
- try { res.set('Content-Type', 'application/json'); } catch(_) {}
26
- res.write(jsonStringify(obj) || '{}');
27
- endTerminator();
28
- };
29
- const connectTimeoutHandler = setTimeout(() => {
30
- // Timed out getting a client, restart worker or process...
31
- logger.error('Error timed out getting a client, exiting...');
32
- process.exit(22);
33
- }, withTransactionConfig.timeoutMillis);
34
- Promise.all([
35
- repo.db ? repo.db.connect() : Promise.resolve(undefined),
36
- repo.dbMssql ? Promise.resolve(repo.dbMssql.transaction()) : Promise.resolve(undefined)
37
- ]).then(([c1, c2]) => {
38
- const dbClient = c1 || c2;
39
- clearTimeout(connectTimeoutHandler);
40
- // On error, will rollback...
41
- utils.logger = logger;
42
- if(withTransactionConfig.logQueries) {
43
- const originalQuery = dbClient.query.bind(dbClient);
44
- dbClient.query = (...args: any[]) => {
45
- logger.debug('SQL [Client %d] QUERY: %s', dbClient.processID, args[0]);
46
- return originalQuery(...args);
47
- };
48
- }
49
- dbClient.removeAllListeners('error');
50
- dbClient.on('error', (err: any) => utils.clientErrorHandler(err, dbClient));
51
-
52
- res.locals.dbClient = dbClient;
53
- res.locals.dbClientCommited = false;
54
- res.locals.dbClientCommit = (cb: (err: any) => any) => {
55
- if(!res.locals.dbClientCommited) {
56
- res.locals.dbClientCommited = true;
57
- (commit ? (repo.db ? dbClient.query('COMMIT') : dbClient.commit()) : Promise.reject(new Error('Client lost'))).catch((err: any) => err).then((err: any) => {
58
- if(repo.db) dbClient.release();
59
- if(!(err instanceof Error)) {
60
- for(let i = 0; i < res.locals.dbClientOnCommit.length; i++) {
61
- res.locals.dbClientOnCommit[i]();
62
- }
63
- }
64
- cb(err instanceof Error ? err : undefined);
65
- });
66
- } else {
67
- cb(undefined);
68
- }
69
- };
70
- res.locals.dbClientOnCommit = [];
71
- return (repo.db ? dbClient.query('BEGIN') : dbClient.begin()).then(() => {
72
- const finish = () => {
73
- res.send = () => {
74
- throw new Error('res.send() should not be used within transactions. Use res.json() instead.');
75
- };
76
- res.json = (obj: any) => {
77
- if(res.statusCode > 303 && res.statusCode !== 412) {
78
- if(logger) {
79
- if(res.statusCode > 499) {
80
- logger.error('Uncaught 500: %j', obj?.error?.additionalInfo);
81
- } else {
82
- logger.warn('Client error 4XX: %j', obj?.error);
83
- }
84
- }
85
- (repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((err: any) => obj && obj.error && (obj.error.additionalInfo2 = {message: err.message})).then(() => {
86
- if(repo.db) dbClient.release();
87
- jsonTerminator(obj);
88
- });
89
- } else {
90
- res.locals.dbClientCommit((err: any) => {
91
- if(err && commitIfLost) {
92
- res.status(500);
93
- jsonTerminator({
94
- error: {
95
- errorKey: 'internal.db',
96
- additionalInfo: {message: err.message}
97
- }
98
- });
99
- } else jsonTerminator(obj);
100
- });
101
- }
102
- return res;
103
- };
104
- res.end = () => {
105
- if(res.statusCode > 303 && res.statusCode !== 412) {
106
- if(logger && res.statusCode > 499) {
107
- logger.error('Uncaught 500 with no details...');
108
- }
109
- (repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((): any => undefined).then(() => {
110
- if(repo.db) dbClient.release();
111
- endTerminator();
112
- });
113
- } else {
114
- res.locals.dbClientCommit((err: any) => {
115
- if(err && commitIfLost) {
116
- res.status(500);
117
- jsonTerminator({
118
- error: {
119
- errorKey: 'internal.db',
120
- additionalInfo: {message: err.message}
121
- }
122
- });
123
- } else endTerminator();
124
- });
125
- }
126
- return res;
127
- };
128
- return previousMethod.call(this, req, res, next);
129
- };
130
-
131
- if(lock) {
132
- dbClient.query('SELECT pg_advisory_xact_lock(' + lock + ')').then(() => finish()).catch((err: any) => {
133
- res.status(500).json({
134
- error: {
135
- errorKey: 'internal.db',
136
- additionalInfo: {message: err.message}
137
- }
138
- });
139
- dbClient.release(); // Lock acquisition failed, release will also rollback
140
- });
141
- } else {
142
- finish();
143
- }
144
- }).catch((err: any) => {
145
- // Error beginning transaction
146
- dbClient.release();
147
- throw err;
148
- });
149
- }).catch(err => {
150
- // Error connecting to database for other reason than timeout or beginning transaction
151
- clearTimeout(connectTimeoutHandler);
152
- res.status(500).json({
153
- error: {
154
- errorKey: 'internal.db',
155
- additionalInfo: {message: err.message}
156
- }
157
- });
158
- });
159
- };
160
- }
1
+ import {NextFunction, Request, Response} from 'express';
2
+ import {Logger} from 'winston';
3
+ import {BaseModelRepository} from '../models/repository/BaseModelRepository';
4
+ import {jsonStringify, utils} from './utils';
5
+
6
+ export const enum SystemLock {
7
+ CHECK_CROSSING = 1,
8
+ FLUSH_CALLS = 2,
9
+ TX_CHECK = 3
10
+ }
11
+
12
+ export const withTransactionConfig = {
13
+ logQueries: false,
14
+ timeoutMillis: 15000
15
+ };
16
+
17
+ export function withTransaction(repo: BaseModelRepository, logger: Logger, previousMethod: (req: Request, res: Response, next: NextFunction) => void, lock?: SystemLock, commitIfLost = true) {
18
+ return function(req: Request, res: Response, next: NextFunction) {
19
+ let commit = true;
20
+ if(!commitIfLost) {
21
+ res.once('close', () => commit = false);
22
+ }
23
+ const endTerminator = res.end.bind(res);
24
+ const jsonTerminator = (obj: any) => {
25
+ try { res.set('Content-Type', 'application/json'); } catch(_) {}
26
+ res.write(jsonStringify(obj) || '{}');
27
+ endTerminator();
28
+ };
29
+ const connectTimeoutHandler = setTimeout(() => {
30
+ // Timed out getting a client, restart worker or process...
31
+ logger.error('Error timed out getting a client, exiting...');
32
+ process.exit(22);
33
+ }, withTransactionConfig.timeoutMillis);
34
+ Promise.all([
35
+ repo.db ? repo.db.connect() : Promise.resolve(undefined),
36
+ repo.dbMssql ? Promise.resolve(repo.dbMssql.transaction()) : Promise.resolve(undefined)
37
+ ]).then(([c1, c2]) => {
38
+ const dbClient = c1 || c2;
39
+ clearTimeout(connectTimeoutHandler);
40
+ // On error, will rollback...
41
+ utils.logger = logger;
42
+ if(withTransactionConfig.logQueries && !dbClient.queryPatched) {
43
+ const originalQuery = dbClient.query.bind(dbClient);
44
+ dbClient.query = (...args: any[]) => {
45
+ logger.debug('SQL [Client %d] QUERY: %s', dbClient.processID, args[0]);
46
+ return originalQuery(...args);
47
+ };
48
+ dbClient.queryPatched = true;
49
+ }
50
+ dbClient.removeAllListeners('error');
51
+ dbClient.on('error', (err: any) => utils.clientErrorHandler(err, dbClient));
52
+
53
+ res.locals.dbClient = dbClient;
54
+ res.locals.dbClientCommited = false;
55
+ res.locals.dbClientCommit = (cb: (err: any) => any) => {
56
+ if(!res.locals.dbClientCommited) {
57
+ res.locals.dbClientCommited = true;
58
+ (commit ? (repo.db ? dbClient.query('COMMIT') : dbClient.commit()) : Promise.reject(new Error('Client lost'))).catch((err: any) => err).then((err: any) => {
59
+ if(repo.db) dbClient.release();
60
+ if(!(err instanceof Error)) {
61
+ for(let i = 0; i < res.locals.dbClientOnCommit.length; i++) {
62
+ res.locals.dbClientOnCommit[i]();
63
+ }
64
+ }
65
+ cb(err instanceof Error ? err : undefined);
66
+ });
67
+ } else {
68
+ cb(undefined);
69
+ }
70
+ };
71
+ res.locals.dbClientOnCommit = [];
72
+ return (repo.db ? dbClient.query('BEGIN') : dbClient.begin()).then(() => {
73
+ const finish = () => {
74
+ res.send = () => {
75
+ throw new Error('res.send() should not be used within transactions. Use res.json() instead.');
76
+ };
77
+ res.json = (obj: any) => {
78
+ if(res.statusCode > 303 && res.statusCode !== 412) {
79
+ if(logger) {
80
+ if(res.statusCode > 499) {
81
+ logger.error('Uncaught 500: %j', obj?.error?.additionalInfo);
82
+ } else {
83
+ logger.warn('Client error 4XX: %j', obj?.error);
84
+ }
85
+ }
86
+ (repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((err: any) => obj && obj.error && (obj.error.additionalInfo2 = {message: err.message})).then(() => {
87
+ if(repo.db) dbClient.release();
88
+ jsonTerminator(obj);
89
+ });
90
+ } else {
91
+ res.locals.dbClientCommit((err: any) => {
92
+ if(err && commitIfLost) {
93
+ res.status(500);
94
+ jsonTerminator({
95
+ error: {
96
+ errorKey: 'internal.db',
97
+ additionalInfo: {message: err.message}
98
+ }
99
+ });
100
+ } else jsonTerminator(obj);
101
+ });
102
+ }
103
+ return res;
104
+ };
105
+ res.end = () => {
106
+ if(res.statusCode > 303 && res.statusCode !== 412) {
107
+ if(logger && res.statusCode > 499) {
108
+ logger.error('Uncaught 500 with no details...');
109
+ }
110
+ (repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((): any => undefined).then(() => {
111
+ if(repo.db) dbClient.release();
112
+ endTerminator();
113
+ });
114
+ } else {
115
+ res.locals.dbClientCommit((err: any) => {
116
+ if(err && commitIfLost) {
117
+ res.status(500);
118
+ jsonTerminator({
119
+ error: {
120
+ errorKey: 'internal.db',
121
+ additionalInfo: {message: err.message}
122
+ }
123
+ });
124
+ } else endTerminator();
125
+ });
126
+ }
127
+ return res;
128
+ };
129
+ return previousMethod.call(this, req, res, next);
130
+ };
131
+
132
+ if(lock) {
133
+ dbClient.query('SELECT pg_advisory_xact_lock(' + lock + ')').then(() => finish()).catch((err: any) => {
134
+ res.status(500).json({
135
+ error: {
136
+ errorKey: 'internal.db',
137
+ additionalInfo: {message: err.message}
138
+ }
139
+ });
140
+ dbClient.release(); // Lock acquisition failed, release will also rollback
141
+ });
142
+ } else {
143
+ finish();
144
+ }
145
+ }).catch((err: any) => {
146
+ // Error beginning transaction
147
+ dbClient.release();
148
+ throw err;
149
+ });
150
+ }).catch(err => {
151
+ // Error connecting to database for other reason than timeout or beginning transaction
152
+ clearTimeout(connectTimeoutHandler);
153
+ res.status(500).json({
154
+ error: {
155
+ errorKey: 'internal.db',
156
+ additionalInfo: {message: err.message}
157
+ }
158
+ });
159
+ });
160
+ };
161
+ }
package/services/utils.js CHANGED
@@ -143,22 +143,22 @@ function idempotent(repo, debug, logger) {
143
143
  };
144
144
  }
145
145
  function sendSelfPostableMessage(res, code, messageType, err) {
146
- res.type('text/html').status(code).write(`
147
- <!DOCTYPE HTML>
148
- <html>
149
- <head>
150
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
151
- </head>
152
- <body>
153
- <script type="text/javascript">
154
- window.parent.postMessage({
155
- type: '${messageType}',
156
- confirm: ${!err},
157
- error: JSON.parse('${JSON.stringify(err) || 'null'}')
158
- }, '*');
159
- </script>
160
- </body>
161
- </html>
146
+ res.type('text/html').status(code).write(`
147
+ <!DOCTYPE HTML>
148
+ <html>
149
+ <head>
150
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
151
+ </head>
152
+ <body>
153
+ <script type="text/javascript">
154
+ window.parent.postMessage({
155
+ type: '${messageType}',
156
+ confirm: ${!err},
157
+ error: JSON.parse('${JSON.stringify(err) || 'null'}')
158
+ }, '*');
159
+ </script>
160
+ </body>
161
+ </html>
162
162
  `);
163
163
  res.end();
164
164
  }