anote-server-libs 0.2.6 → 0.2.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.
@@ -1,56 +1,56 @@
1
- import {Request, Response} from 'express';
2
- import {SchemaError, Validator} from 'jsonschema';
3
-
4
- export function WithBody(schema: any) {
5
- const validator = new Validator();
6
- validator.attributes.maxDigits = (instance, sc: any) => {
7
- if(typeof instance !== 'number') return undefined;
8
- if(typeof sc.maxDigits !== 'number' || Math.floor(sc.maxDigits) !== sc.maxDigits) {
9
- throw new SchemaError('"maxDigits" expects an integer', sc);
10
- }
11
- if(Math.round(instance * 10 ** sc.maxDigits) / (10 ** sc.maxDigits) !== instance) {
12
- return 'has more precision than ' + sc.maxDigits + ' digits';
13
- }
14
- return undefined;
15
- };
16
-
17
- return function(_: any, __: string, descriptor: PropertyDescriptor) {
18
- if(typeof descriptor.value === 'function') {
19
- const previousMethod = descriptor.value;
20
- descriptor.value = function(this: any, req: Request, res: Response) {
21
- const keys = Object.getOwnPropertyNames(schema.properties);
22
- keys.forEach(key => {
23
- if(typeof schema.properties[key] === 'string') {
24
- schema.properties[key] = this.config.app.endpointsSchemas[schema.properties[key]];
25
- }
26
- });
27
- if(req.method.toUpperCase() !== 'POST' && req.method.toUpperCase() !== 'PUT') {
28
- return previousMethod.call(this, req, res);
29
- }
30
- if(!req.body) {
31
- res.status(400).json({
32
- error: {
33
- errorKey: 'client.body.missing',
34
- additionalInfo: 'client.extended.badPayload'
35
- }
36
- });
37
- } else {
38
- const result = validator.validate(req.body, schema);
39
- if(result.valid) {
40
- return previousMethod.call(this, req, res);
41
- } else {
42
- res.status(400).json({
43
- error: {
44
- errorKey: 'client.body.missing',
45
- additionalInfo: 'client.extended.badPayload',
46
- detailedInfo: result.errors
47
- }
48
- });
49
- }
50
- }
51
- };
52
- return descriptor;
53
- }
54
- return undefined;
55
- };
56
- }
1
+ import {Request, Response} from 'express';
2
+ import {SchemaError, Validator} from 'jsonschema';
3
+
4
+ export function WithBody(schema: any) {
5
+ const validator = new Validator();
6
+ validator.attributes.maxDigits = (instance, sc: any) => {
7
+ if(typeof instance !== 'number') return undefined;
8
+ if(typeof sc.maxDigits !== 'number' || Math.floor(sc.maxDigits) !== sc.maxDigits) {
9
+ throw new SchemaError('"maxDigits" expects an integer', sc);
10
+ }
11
+ if(Math.round(instance * 10 ** sc.maxDigits) / (10 ** sc.maxDigits) !== instance) {
12
+ return 'has more precision than ' + sc.maxDigits + ' digits';
13
+ }
14
+ return undefined;
15
+ };
16
+
17
+ return function(_: any, __: string, descriptor: PropertyDescriptor) {
18
+ if(typeof descriptor.value === 'function') {
19
+ const previousMethod = descriptor.value;
20
+ descriptor.value = function(this: any, req: Request, res: Response) {
21
+ const keys = Object.getOwnPropertyNames(schema.properties);
22
+ keys.forEach(key => {
23
+ if(typeof schema.properties[key] === 'string') {
24
+ schema.properties[key] = this.config.app.endpointsSchemas[schema.properties[key]];
25
+ }
26
+ });
27
+ if(req.method.toUpperCase() !== 'POST' && req.method.toUpperCase() !== 'PUT') {
28
+ return previousMethod.call(this, req, res);
29
+ }
30
+ if(!req.body) {
31
+ res.status(400).json({
32
+ error: {
33
+ errorKey: 'client.body.missing',
34
+ additionalInfo: 'client.extended.badPayload'
35
+ }
36
+ });
37
+ } else {
38
+ const result = validator.validate(req.body, schema);
39
+ if(result.valid) {
40
+ return previousMethod.call(this, req, res);
41
+ } else {
42
+ res.status(400).json({
43
+ error: {
44
+ errorKey: 'client.body.missing',
45
+ additionalInfo: 'client.extended.badPayload',
46
+ detailedInfo: result.errors
47
+ }
48
+ });
49
+ }
50
+ }
51
+ };
52
+ return descriptor;
53
+ }
54
+ return undefined;
55
+ };
56
+ }
@@ -117,12 +117,6 @@ function withTransaction(repo, logger, previousMethod, lock) {
117
117
  else {
118
118
  finish();
119
119
  }
120
- }).catch((err) => {
121
- if (repo.db)
122
- dbClient.release();
123
- else
124
- dbClient.rollback();
125
- throw err;
126
120
  });
127
121
  }).catch(err => {
128
122
  res.status(500).json({
@@ -1,134 +1,130 @@
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
- }
10
-
11
- export function withTransaction(repo: BaseModelRepository, logger: Logger, previousMethod: (req: Request, res: Response, next: NextFunction) => void, lock?: SystemLock) {
12
- return function(req: Request, res: Response, next: NextFunction) {
13
- const endTerminator = res.end.bind(res);
14
- const jsonTerminator = (obj: any) => {
15
- res.write(jsonStringify(obj) || '{}');
16
- endTerminator();
17
- };
18
- const connectTimeoutHandler = setTimeout(() => {
19
- // Timed out getting a client, restart worker or process...
20
- logger.error('Error timed out getting a client, exiting...');
21
- process.exit(22);
22
- }, 3000);
23
- Promise.all([
24
- repo.db ? repo.db.connect() : Promise.resolve(undefined),
25
- repo.dbMssql ? Promise.resolve(repo.dbMssql.transaction()) : Promise.resolve(undefined)
26
- ]).then(([c1, c2]) => {
27
- const dbClient = c1 || c2;
28
- clearTimeout(connectTimeoutHandler);
29
- // On error, will rollback...
30
- utils.logger = logger;
31
- dbClient.removeListener('error', utils.clientErrorHandler);
32
- dbClient.on('error', utils.clientErrorHandler);
33
-
34
- res.locals.dbClient = dbClient;
35
- res.locals.dbClientCommited = false;
36
- res.locals.dbClientCommit = (cb: (err: any) => any) => {
37
- if(!res.locals.dbClientCommited) {
38
- res.locals.dbClientCommited = true;
39
- (repo.db ? dbClient.query('COMMIT') : dbClient.commit()).catch((err: any) => err).then((err: any) => {
40
- if(repo.db) dbClient.release();
41
- if(!(err instanceof Error)) {
42
- for(let i = 0; i < res.locals.dbClientOnCommit.length; i++) {
43
- res.locals.dbClientOnCommit[i]();
44
- }
45
- }
46
- cb(err instanceof Error ? err : undefined);
47
- });
48
- } else {
49
- cb(undefined);
50
- }
51
- };
52
- res.locals.dbClientOnCommit = [];
53
- return (repo.db ? dbClient.query('BEGIN') : dbClient.begin()).then(() => {
54
- const finish = () => {
55
- res.json = (obj: any) => {
56
- if(res.statusCode > 303 && res.statusCode !== 412) {
57
- if(logger && res.statusCode > 499) {
58
- logger.error('Uncaught 500: %j', obj.error.additionalInfo);
59
- }
60
- (repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((err: any) => obj.error.additionalInfo2 = {message: err.message}).then(() => {
61
- if(repo.db) dbClient.release();
62
- jsonTerminator(obj);
63
- });
64
- } else {
65
- res.locals.dbClientCommit((err: any) => {
66
- if(err) {
67
- res.status(500);
68
- jsonTerminator({
69
- error: {
70
- errorKey: 'internal.db',
71
- additionalInfo: {message: err.message}
72
- }
73
- });
74
- } else jsonTerminator(obj);
75
- });
76
- }
77
- return res;
78
- };
79
- res.end = () => {
80
- if(res.statusCode > 303 && res.statusCode !== 412) {
81
- if(logger && res.statusCode > 499) {
82
- logger.error('Uncaught 500 with no details...');
83
- }
84
- (repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((): any => undefined).then(() => {
85
- if(repo.db) dbClient.release();
86
- endTerminator();
87
- });
88
- } else {
89
- res.locals.dbClientCommit((err: any) => {
90
- if(err) {
91
- res.status(500);
92
- jsonTerminator({
93
- error: {
94
- errorKey: 'internal.db',
95
- additionalInfo: {message: err.message}
96
- }
97
- });
98
- } else endTerminator();
99
- });
100
- }
101
- return res;
102
- };
103
- return previousMethod.call(this, req, res, next);
104
- };
105
-
106
- if(lock) {
107
- dbClient.query('SELECT pg_advisory_xact_lock(' + lock + ')').then(() => finish()).catch((err: any) => {
108
- res.status(500).json({
109
- error: {
110
- errorKey: 'internal.db',
111
- additionalInfo: {message: err.message}
112
- }
113
- });
114
- dbClient.release();
115
- });
116
- } else {
117
- finish();
118
- }
119
- }).catch((err: any) => {
120
- if(repo.db) dbClient.release();
121
- else dbClient.rollback();
122
- throw err;
123
- });
124
- }).catch(err => {
125
- // Error connecting to database, restarting worker after the timeout as well...
126
- res.status(500).json({
127
- error: {
128
- errorKey: 'internal.db',
129
- additionalInfo: {message: err.message}
130
- }
131
- });
132
- });
133
- };
134
- }
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
+ }
10
+
11
+ export function withTransaction(repo: BaseModelRepository, logger: Logger, previousMethod: (req: Request, res: Response, next: NextFunction) => void, lock?: SystemLock) {
12
+ return function(req: Request, res: Response, next: NextFunction) {
13
+ const endTerminator = res.end.bind(res);
14
+ const jsonTerminator = (obj: any) => {
15
+ res.write(jsonStringify(obj) || '{}');
16
+ endTerminator();
17
+ };
18
+ const connectTimeoutHandler = setTimeout(() => {
19
+ // Timed out getting a client, restart worker or process...
20
+ logger.error('Error timed out getting a client, exiting...');
21
+ process.exit(22);
22
+ }, 3000);
23
+ Promise.all([
24
+ repo.db ? repo.db.connect() : Promise.resolve(undefined),
25
+ repo.dbMssql ? Promise.resolve(repo.dbMssql.transaction()) : Promise.resolve(undefined)
26
+ ]).then(([c1, c2]) => {
27
+ const dbClient = c1 || c2;
28
+ clearTimeout(connectTimeoutHandler);
29
+ // On error, will rollback...
30
+ utils.logger = logger;
31
+ dbClient.removeListener('error', utils.clientErrorHandler);
32
+ dbClient.on('error', utils.clientErrorHandler);
33
+
34
+ res.locals.dbClient = dbClient;
35
+ res.locals.dbClientCommited = false;
36
+ res.locals.dbClientCommit = (cb: (err: any) => any) => {
37
+ if(!res.locals.dbClientCommited) {
38
+ res.locals.dbClientCommited = true;
39
+ (repo.db ? dbClient.query('COMMIT') : dbClient.commit()).catch((err: any) => err).then((err: any) => {
40
+ if(repo.db) dbClient.release();
41
+ if(!(err instanceof Error)) {
42
+ for(let i = 0; i < res.locals.dbClientOnCommit.length; i++) {
43
+ res.locals.dbClientOnCommit[i]();
44
+ }
45
+ }
46
+ cb(err instanceof Error ? err : undefined);
47
+ });
48
+ } else {
49
+ cb(undefined);
50
+ }
51
+ };
52
+ res.locals.dbClientOnCommit = [];
53
+ return (repo.db ? dbClient.query('BEGIN') : dbClient.begin()).then(() => {
54
+ const finish = () => {
55
+ res.json = (obj: any) => {
56
+ if(res.statusCode > 303 && res.statusCode !== 412) {
57
+ if(logger && res.statusCode > 499) {
58
+ logger.error('Uncaught 500: %j', obj.error.additionalInfo);
59
+ }
60
+ (repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((err: any) => obj.error.additionalInfo2 = {message: err.message}).then(() => {
61
+ if(repo.db) dbClient.release();
62
+ jsonTerminator(obj);
63
+ });
64
+ } else {
65
+ res.locals.dbClientCommit((err: any) => {
66
+ if(err) {
67
+ res.status(500);
68
+ jsonTerminator({
69
+ error: {
70
+ errorKey: 'internal.db',
71
+ additionalInfo: {message: err.message}
72
+ }
73
+ });
74
+ } else jsonTerminator(obj);
75
+ });
76
+ }
77
+ return res;
78
+ };
79
+ res.end = () => {
80
+ if(res.statusCode > 303 && res.statusCode !== 412) {
81
+ if(logger && res.statusCode > 499) {
82
+ logger.error('Uncaught 500 with no details...');
83
+ }
84
+ (repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((): any => undefined).then(() => {
85
+ if(repo.db) dbClient.release();
86
+ endTerminator();
87
+ });
88
+ } else {
89
+ res.locals.dbClientCommit((err: any) => {
90
+ if(err) {
91
+ res.status(500);
92
+ jsonTerminator({
93
+ error: {
94
+ errorKey: 'internal.db',
95
+ additionalInfo: {message: err.message}
96
+ }
97
+ });
98
+ } else endTerminator();
99
+ });
100
+ }
101
+ return res;
102
+ };
103
+ return previousMethod.call(this, req, res, next);
104
+ };
105
+
106
+ if(lock) {
107
+ dbClient.query('SELECT pg_advisory_xact_lock(' + lock + ')').then(() => finish()).catch((err: any) => {
108
+ res.status(500).json({
109
+ error: {
110
+ errorKey: 'internal.db',
111
+ additionalInfo: {message: err.message}
112
+ }
113
+ });
114
+ dbClient.release();
115
+ });
116
+ } else {
117
+ finish();
118
+ }
119
+ });
120
+ }).catch(err => {
121
+ // Error connecting to database or acquiring transaction, restarting worker after the timeout as well...
122
+ res.status(500).json({
123
+ error: {
124
+ errorKey: 'internal.db',
125
+ additionalInfo: {message: err.message}
126
+ }
127
+ });
128
+ });
129
+ };
130
+ }
package/services/utils.js CHANGED
@@ -140,22 +140,22 @@ function idempotent(repo, debug, logger) {
140
140
  }
141
141
  exports.idempotent = idempotent;
142
142
  function sendSelfPostableMessage(res, code, messageType, err) {
143
- res.type('text/html').status(code).write(`
144
- <!DOCTYPE HTML>
145
- <html>
146
- <head>
147
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
148
- </head>
149
- <body>
150
- <script type="text/javascript">
151
- window.parent.postMessage({
152
- type: '${messageType}',
153
- confirm: ${!err},
154
- error: JSON.parse('${JSON.stringify(err) || 'null'}')
155
- }, '*');
156
- </script>
157
- </body>
158
- </html>
143
+ res.type('text/html').status(code).write(`
144
+ <!DOCTYPE HTML>
145
+ <html>
146
+ <head>
147
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
148
+ </head>
149
+ <body>
150
+ <script type="text/javascript">
151
+ window.parent.postMessage({
152
+ type: '${messageType}',
153
+ confirm: ${!err},
154
+ error: JSON.parse('${JSON.stringify(err) || 'null'}')
155
+ }, '*');
156
+ </script>
157
+ </body>
158
+ </html>
159
159
  `);
160
160
  res.end();
161
161
  }