anote-server-libs 0.0.5 → 0.0.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.
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApiCallRepository = void 0;
4
+ const ModelDao_1 = require("./repository/ModelDao");
5
+ class ApiCallRepository extends ModelDao_1.ModelDao {
6
+ constructor(pool, logger) {
7
+ super(pool, logger, 'api_call', 5, 'id=$1,"updatedOn"=$2,"responseCode"=$3,"responseJson"=$4,"expiresAt"=$5');
8
+ this.pool = pool;
9
+ this.logger = logger;
10
+ }
11
+ buildObject(q) {
12
+ if (!q)
13
+ return undefined;
14
+ q.id = q.id.trim();
15
+ q.updatedOn = q.updatedOn && new Date(q.updatedOn);
16
+ q.responseCode = parseInt(q.responseCode, 10);
17
+ q.expiresAt = q.expiresAt && new Date(q.expiresAt);
18
+ return q;
19
+ }
20
+ serialize(instance) {
21
+ return [instance.id, instance.updatedOn, instance.responseCode, instance.responseJson, instance.expiresAt];
22
+ }
23
+ }
24
+ exports.ApiCallRepository = ApiCallRepository;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MigrationRepository = void 0;
4
+ const ModelDao_1 = require("./repository/ModelDao");
5
+ class MigrationRepository extends ModelDao_1.ModelDao {
6
+ constructor(pool, logger) {
7
+ super(pool, logger, 'migration', 5, 'id=$1,hash=$2,"sqlUp"=$3,"sqlDown"=$4,state=$5');
8
+ this.pool = pool;
9
+ this.logger = logger;
10
+ }
11
+ buildObject(q) {
12
+ if (!q)
13
+ return undefined;
14
+ q.id = parseInt(q.id, 10);
15
+ q.hash = q.hash.trim();
16
+ q.state = parseInt(q.state, 10);
17
+ return q;
18
+ }
19
+ serialize(instance) {
20
+ return [instance.id, instance.hash, instance.sqlUp, instance.sqlDown, instance.state];
21
+ }
22
+ }
23
+ exports.MigrationRepository = MigrationRepository;
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseModelRepository = void 0;
4
+ const fs = require("fs");
5
+ const node_forge_1 = require("node-forge");
6
+ const ApiCall_1 = require("../ApiCall");
7
+ const Migration_1 = require("../Migration");
8
+ class BaseModelRepository {
9
+ constructor(db, dbSpare, logger, cache) {
10
+ this.db = db;
11
+ this.dbSpare = dbSpare;
12
+ this.logger = logger;
13
+ this.cache = cache;
14
+ const dbQuery = db.query.bind(db);
15
+ db.query = (function (text, values, cb) {
16
+ if ((this.idleCount + this.waitingCount) >= this.totalCount && this.totalCount === this.options.max)
17
+ return dbSpare.query(text, values, cb);
18
+ return dbQuery(text, values, cb);
19
+ }).bind(db);
20
+ this.Migration = new Migration_1.MigrationRepository(db, logger);
21
+ this.ApiCall = new ApiCall_1.ApiCallRepository(db, logger);
22
+ }
23
+ migrate(migrationsPath, callback) {
24
+ this.db.query('CREATE TABLE IF NOT EXISTS migration (' +
25
+ 'id integer PRIMARY KEY,' +
26
+ 'hash text NOT NULL,' +
27
+ '"sqlUp" text NOT NULL,' +
28
+ '"sqlDown" text NOT NULL,' +
29
+ 'state integer NOT NULL' +
30
+ ')').then(() => {
31
+ this.Migration.getAllBy('id').then((migrations) => {
32
+ if (migrations.find(migration => migration.state !== 0))
33
+ process.exit(4);
34
+ fs.readdir(migrationsPath, (_, files) => {
35
+ const migrationsAvailable = files
36
+ .filter(file => /[0-9]+\.sql/.test(file))
37
+ .map(file => parseInt(file.split('.sql')[0], 10))
38
+ .filter(file => file > 0)
39
+ .sort((a, b) => a - b)
40
+ .map(file => {
41
+ const content = fs.readFileSync(migrationsPath + file + '.sql', 'utf-8');
42
+ return {
43
+ id: file,
44
+ content: content,
45
+ hash: node_forge_1.md.sha256.create().update(content).digest().toHex()
46
+ };
47
+ });
48
+ if (migrationsAvailable.length === 0
49
+ || migrationsAvailable.length
50
+ !== migrationsAvailable[migrationsAvailable.length - 1].id)
51
+ process.exit(5);
52
+ let highestCommon = 0;
53
+ while (highestCommon < migrations.length && highestCommon < migrationsAvailable.length
54
+ && migrations[highestCommon].hash === migrationsAvailable[highestCommon].hash)
55
+ highestCommon++;
56
+ this.applyDownUntil(migrations, migrations.length, highestCommon).then(() => {
57
+ this.applyUpUntil(migrationsAvailable, highestCommon, migrationsAvailable.length).then(callback, process.exit);
58
+ }, process.exit);
59
+ });
60
+ }, () => process.exit(3));
61
+ }, () => process.exit(2));
62
+ }
63
+ lockTables(tables, client) {
64
+ return Promise.all(tables.map(t => client.query('LOCK TABLE ' + t.table + ' IN EXCLUSIVE MODE')));
65
+ }
66
+ applyUpUntil(migrations, current, until) {
67
+ if (current < until)
68
+ return this.applyUp(migrations[current]).then(() => this.applyUpUntil(migrations, current + 1, until));
69
+ return Promise.resolve();
70
+ }
71
+ applyUp(migration) {
72
+ return new Promise((resolve, reject) => {
73
+ const sqlParts = migration.content.split('----');
74
+ this.Migration.create({
75
+ id: migration.id,
76
+ hash: migration.hash,
77
+ sqlUp: sqlParts[0],
78
+ sqlDown: sqlParts[1],
79
+ state: 2
80
+ }).then(() => {
81
+ this.db.query(sqlParts[0], (err) => {
82
+ if (err) {
83
+ console.error(err);
84
+ reject(10);
85
+ }
86
+ else {
87
+ this.db.query('UPDATE "migration" SET "state"=0 WHERE "id"=' + migration.id, (err2) => {
88
+ if (err2)
89
+ reject(11);
90
+ else
91
+ resolve();
92
+ });
93
+ }
94
+ });
95
+ }, () => process.exit(9));
96
+ });
97
+ }
98
+ applyDownUntil(migrations, current, until) {
99
+ if (current > until) {
100
+ current--;
101
+ return this.applyDown(migrations[current]).then(() => this.applyDownUntil(migrations, current, until));
102
+ }
103
+ return Promise.resolve();
104
+ }
105
+ applyDown(migration) {
106
+ return new Promise((resolve, reject) => {
107
+ this.db.query('UPDATE "migration" SET "state"=1 WHERE "id"=' + migration.id, (err) => {
108
+ if (err)
109
+ reject(6);
110
+ else
111
+ this.db.query(migration.sqlDown, (err2) => {
112
+ if (err2) {
113
+ console.error(err2);
114
+ reject(7);
115
+ }
116
+ else
117
+ this.db.query('DELETE FROM "migration" WHERE "id"=' + migration.id, (err3) => {
118
+ if (err3 && migration.id !== 1)
119
+ reject(8);
120
+ else {
121
+ if (migration.id === 1) {
122
+ this.db.query('CREATE TABLE IF NOT EXISTS migration (' +
123
+ 'id integer PRIMARY KEY,' +
124
+ 'hash text NOT NULL,' +
125
+ '"sqlUp" text NOT NULL,' +
126
+ '"sqlDown" text NOT NULL,' +
127
+ 'state integer NOT NULL' +
128
+ ')').then(() => resolve(), reject);
129
+ }
130
+ else
131
+ resolve();
132
+ }
133
+ });
134
+ });
135
+ });
136
+ });
137
+ }
138
+ }
139
+ exports.BaseModelRepository = BaseModelRepository;
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MemoryCache = void 0;
4
+ class MemoryCache {
5
+ constructor(localKey, cache) {
6
+ this.localKey = localKey;
7
+ this.cache = cache;
8
+ this.localCache = {};
9
+ }
10
+ list() {
11
+ if (this.cache)
12
+ return new Promise(resolve => {
13
+ let pending = true;
14
+ setTimeout(() => {
15
+ if (pending) {
16
+ pending = false;
17
+ resolve([]);
18
+ }
19
+ }, 250);
20
+ this.cache.items((_, data) => {
21
+ if (pending) {
22
+ pending = false;
23
+ resolve(data.map(s => {
24
+ const value = s[Object.getOwnPropertyNames(s).find(sname => sname.startsWith(this.localKey))];
25
+ return value && JSON.parse(value);
26
+ }).filter(x => x));
27
+ }
28
+ });
29
+ });
30
+ else
31
+ return Promise.resolve(Object.getOwnPropertyNames(this.localCache).map(key => this.localCache[key]));
32
+ }
33
+ get(key) {
34
+ if (this.cache)
35
+ return new Promise(resolve => {
36
+ let pending = true;
37
+ setTimeout(() => {
38
+ if (pending) {
39
+ pending = false;
40
+ resolve(undefined);
41
+ }
42
+ }, 250);
43
+ this.cache.get(this.localKey + key, (_, data) => {
44
+ if (pending) {
45
+ pending = false;
46
+ resolve(data && JSON.parse(data));
47
+ }
48
+ });
49
+ });
50
+ else
51
+ return Promise.resolve(this.localCache[key]);
52
+ }
53
+ set(key, val) {
54
+ if (this.cache)
55
+ return new Promise(resolve => this.cache.add(this.localKey + key, JSON.stringify(val), 15 * 60, resolve));
56
+ else {
57
+ this.localCache[key] = val;
58
+ return Promise.resolve();
59
+ }
60
+ }
61
+ delete(key) {
62
+ if (this.cache) {
63
+ return new Promise(resolve => {
64
+ let fired = false;
65
+ const handler = setTimeout(() => {
66
+ fired = true;
67
+ resolve();
68
+ }, 50);
69
+ this.cache.del(this.localKey + key, () => {
70
+ if (!fired) {
71
+ clearTimeout(handler);
72
+ resolve();
73
+ }
74
+ });
75
+ });
76
+ }
77
+ else {
78
+ this.localCache[key] = undefined;
79
+ return Promise.resolve();
80
+ }
81
+ }
82
+ clear() {
83
+ if (this.cache) {
84
+ this.localKey = this.localKey + '_';
85
+ if (this.localKey.length > 40)
86
+ this.localKey = this.localKey.replace(/_+$/, '');
87
+ }
88
+ else
89
+ this.localCache = {};
90
+ }
91
+ }
92
+ exports.MemoryCache = MemoryCache;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ModelDao = void 0;
4
+ class Dao {
5
+ constructor(pool, logger, table, nFields, updateDefinition) {
6
+ this.pool = pool;
7
+ this.logger = logger;
8
+ this.table = table;
9
+ this.nFields = nFields;
10
+ this.updateDefinition = updateDefinition;
11
+ }
12
+ groupResultSet(q, key) {
13
+ const storage = {};
14
+ for (let i = 0; i < q.length; i++) {
15
+ storage[key(q[i])] = storage[key(q[i])] || [];
16
+ storage[key(q[i])].push(q[i]);
17
+ }
18
+ return Object.getOwnPropertyNames(storage).map(k => storage[k]);
19
+ }
20
+ update(instance, client) {
21
+ instance.updatedOn = new Date();
22
+ const props = this.serialize(instance);
23
+ props.push(instance.id);
24
+ return client.query('UPDATE ' + this.table + ' SET ' + this.updateDefinition + ' WHERE id=$' + (this.nFields + 1), props).then(() => instance.id);
25
+ }
26
+ create(instance, client) {
27
+ instance.updatedOn = new Date();
28
+ const props = this.serialize(instance);
29
+ return (client || this.pool).query('INSERT INTO ' + this.table + '(' + this.updateDefinition.replace(/=\$\d+/g, '') + ')'
30
+ + ' VALUES(' + new Array(this.nFields).fill(undefined).map((_, i) => '$' + (i + 1)).join(',') + ') RETURNING id', props).then(q => {
31
+ const idNum = parseInt(q.rows[0].id, 10);
32
+ if (String(idNum) !== q.rows[0].id)
33
+ return q.rows[0].id;
34
+ return idNum;
35
+ });
36
+ }
37
+ createSeveral(instances, client) {
38
+ if (!instances.length)
39
+ return Promise.resolve([]);
40
+ const now = new Date();
41
+ instances.forEach(instance => instance.updatedOn = now);
42
+ const props = [].concat.apply([], instances.map(instance => this.serialize(instance)));
43
+ return (client || this.pool).query('INSERT INTO ' + this.table + '(' + this.updateDefinition.replace(/=\$\d+/g, '') + ')'
44
+ + ' VALUES' + instances.map((_, j) => ('(' + new Array(this.nFields).fill(undefined).map((__, i) => '$' + (j * this.nFields + i + 1)).join(', ') + ')')).join(',') + ' RETURNING id', props).then(q => q.rows.map(r => {
45
+ const idNum = parseInt(r.id, 10);
46
+ if (String(idNum) !== q.rows[0].id)
47
+ return r.id;
48
+ return idNum;
49
+ }));
50
+ }
51
+ }
52
+ class ModelDao extends Dao {
53
+ get(id, client, lock = true) {
54
+ return (client || this.pool).query('SELECT * FROM ' + this.table + ' WHERE id=$1' + ((client && lock) ? ' FOR UPDATE' : ''), [id]).then(q => this.buildObject(q.rows[0]));
55
+ }
56
+ count(where, inputs = [], client) {
57
+ return (client || this.pool).query('SELECT count(*) AS cnt FROM ' + this.table + (where ? (' WHERE ' + where) : ''), inputs).then(q => parseInt(q.rows[0].cnt, 10));
58
+ }
59
+ getList(ids, client, lock = true) {
60
+ return (client || this.pool).query('SELECT * FROM ' + this.table + ' WHERE id=ANY($1)' + ((client && lock) ? ' FOR UPDATE' : ''), [ids])
61
+ .then(q => q.rows.map(r => this.buildObject(r)));
62
+ }
63
+ getAllBy(order, offset, limit, where, inputs = [], client, lock = true) {
64
+ return (client || this.pool).query('SELECT * FROM ' + this.table + (where ? (' WHERE ' + where) : '') + (order ? (' ORDER BY ' + order) : '')
65
+ + (offset ? (' OFFSET ' + offset) : '') + (limit !== undefined ? (' LIMIT ' + limit) : '') + ((client && lock) ? ' FOR UPDATE' : ''), inputs)
66
+ .then(q => q.rows.map(r => this.buildObject(r)));
67
+ }
68
+ getViewCountBy(order, offset, limit, where, inputs = [], client, lock = true) {
69
+ return (client || this.pool).query('SELECT *, COUNT(*) OVER() AS cnt FROM ' + this.table + (where ? (' WHERE ' + where) : '') + (order ? (' ORDER BY ' + order) : '')
70
+ + (offset ? (' OFFSET ' + offset) : '') + (limit !== undefined ? (' LIMIT ' + limit) : '') + ((client && lock) ? ' FOR UPDATE' : ''), inputs)
71
+ .then(q => ({
72
+ views: q.rows.map(r => this.buildObject(r)),
73
+ count: q.rows.length ? parseInt(q.rows[0].cnt, 10) : 0
74
+ }));
75
+ }
76
+ delete(id, client) {
77
+ return client.query('DELETE FROM ' + this.table + ' WHERE id=$1', [id]);
78
+ }
79
+ }
80
+ exports.ModelDao = ModelDao;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anote-server-libs",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "description": "Helpers for express-TS servers",
5
5
  "scripts": {
6
6
  "test": "echo \"Error: no test specified\" && exit 1"
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WithBody = void 0;
4
+ const jsonschema_1 = require("jsonschema");
5
+ function WithBody(schema) {
6
+ const validator = new jsonschema_1.Validator();
7
+ validator.attributes.maxDigits = (instance, sc) => {
8
+ if (typeof instance !== 'number')
9
+ return undefined;
10
+ if (typeof sc.maxDigits !== 'number' || Math.floor(sc.maxDigits) !== sc.maxDigits) {
11
+ throw new jsonschema_1.SchemaError('"maxDigits" expects an integer', sc);
12
+ }
13
+ if (Math.round(instance * 10 ** sc.maxDigits) / (10 ** sc.maxDigits) !== instance) {
14
+ return 'has more precision than ' + sc.maxDigits + ' digits';
15
+ }
16
+ return undefined;
17
+ };
18
+ return function (_, __, descriptor) {
19
+ if (typeof descriptor.value === 'function') {
20
+ const previousMethod = descriptor.value;
21
+ descriptor.value = function (req, res) {
22
+ const keys = Object.getOwnPropertyNames(schema.properties);
23
+ keys.forEach(key => {
24
+ if (typeof schema.properties[key] === 'string') {
25
+ schema.properties[key] = this.config.app.endpointsSchemas[schema.properties[key]];
26
+ }
27
+ });
28
+ if (req.method.toUpperCase() !== 'POST' && req.method.toUpperCase() !== 'PUT') {
29
+ return previousMethod.call(this, req, res);
30
+ }
31
+ if (!req.body) {
32
+ res.status(400).json({
33
+ error: {
34
+ errorKey: 'client.body.missing',
35
+ additionalInfo: 'client.extended.badPayload'
36
+ }
37
+ });
38
+ }
39
+ else {
40
+ const result = validator.validate(req.body, schema);
41
+ if (result.valid) {
42
+ return previousMethod.call(this, req, res);
43
+ }
44
+ else {
45
+ res.status(400).json({
46
+ error: {
47
+ errorKey: 'client.body.missing',
48
+ additionalInfo: 'client.extended.badPayload',
49
+ detailedInfo: result.errors
50
+ }
51
+ });
52
+ }
53
+ }
54
+ };
55
+ return descriptor;
56
+ }
57
+ return undefined;
58
+ };
59
+ }
60
+ exports.WithBody = WithBody;
@@ -0,0 +1,144 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withTransaction = void 0;
4
+ const utils_1 = require("./utils");
5
+ function jsonStringify(obj) {
6
+ const cache = {};
7
+ return JSON.stringify(obj, function (_, value) {
8
+ if (typeof value === 'object' && value !== null) {
9
+ if (cache[value] !== -1) {
10
+ try {
11
+ return JSON.parse(JSON.stringify(value));
12
+ }
13
+ catch (error) {
14
+ return;
15
+ }
16
+ }
17
+ cache[value] = true;
18
+ }
19
+ return value;
20
+ });
21
+ }
22
+ function withTransaction(repo, logger, previousMethod, lock) {
23
+ return function (req, res, next) {
24
+ const endTerminator = res.end.bind(res);
25
+ const jsonTerminator = (obj) => {
26
+ res.write(jsonStringify(obj) || '{}');
27
+ endTerminator();
28
+ };
29
+ const connectTimeoutHandler = setTimeout(() => {
30
+ logger.error('Error timed out getting a client, exiting...');
31
+ process.exit(22);
32
+ }, 3000);
33
+ repo.db.connect().then(dbClient => {
34
+ clearTimeout(connectTimeoutHandler);
35
+ utils_1.utils.logger = logger;
36
+ dbClient.removeListener('error', utils_1.utils.clientErrorHandler);
37
+ dbClient.on('error', utils_1.utils.clientErrorHandler);
38
+ res.locals.dbClient = dbClient;
39
+ res.locals.dbClientCommited = false;
40
+ res.locals.dbClientCommit = (cb) => {
41
+ if (!res.locals.dbClientCommited) {
42
+ res.locals.dbClientCommited = true;
43
+ dbClient.query('COMMIT').catch(err => err).then((err) => {
44
+ dbClient.release();
45
+ if (!(err instanceof Error)) {
46
+ for (let i = 0; i < res.locals.dbClientOnCommit.length; i++) {
47
+ res.locals.dbClientOnCommit[i]();
48
+ }
49
+ }
50
+ cb(err instanceof Error ? err : undefined);
51
+ });
52
+ }
53
+ else {
54
+ cb(undefined);
55
+ }
56
+ };
57
+ res.locals.dbClientOnCommit = [];
58
+ return dbClient.query('BEGIN').then(() => {
59
+ const finish = () => {
60
+ res.json = (obj) => {
61
+ if (res.statusCode > 303 && res.statusCode !== 412) {
62
+ if (logger && res.statusCode > 499) {
63
+ logger.error('Uncaught 500: %j', obj.error.additionalInfo);
64
+ }
65
+ dbClient.query('ROLLBACK').catch(err => obj.error.additionalInfo2 = { message: err.message }).then(() => {
66
+ dbClient.release();
67
+ jsonTerminator(obj);
68
+ });
69
+ }
70
+ else {
71
+ res.locals.dbClientCommit((err) => {
72
+ if (err) {
73
+ res.status(500);
74
+ jsonTerminator({
75
+ error: {
76
+ errorKey: 'internal.db',
77
+ additionalInfo: { message: err.message }
78
+ }
79
+ });
80
+ }
81
+ else
82
+ jsonTerminator(obj);
83
+ });
84
+ }
85
+ return res;
86
+ };
87
+ res.end = () => {
88
+ if (res.statusCode > 303 && res.statusCode !== 412) {
89
+ if (logger && res.statusCode > 499) {
90
+ logger.error('Uncaught 500 with no details...');
91
+ }
92
+ dbClient.query('ROLLBACK').catch(() => undefined).then(() => {
93
+ dbClient.release();
94
+ endTerminator();
95
+ });
96
+ }
97
+ else {
98
+ res.locals.dbClientCommit((err) => {
99
+ if (err) {
100
+ res.status(500);
101
+ jsonTerminator({
102
+ error: {
103
+ errorKey: 'internal.db',
104
+ additionalInfo: { message: err.message }
105
+ }
106
+ });
107
+ }
108
+ else
109
+ endTerminator();
110
+ });
111
+ }
112
+ return res;
113
+ };
114
+ return previousMethod.call(this, req, res, next);
115
+ };
116
+ if (lock) {
117
+ dbClient.query('SELECT pg_advisory_xact_lock(' + lock + ')').then(() => finish()).catch(err => {
118
+ res.status(500).json({
119
+ error: {
120
+ errorKey: 'internal.db',
121
+ additionalInfo: { message: err.message }
122
+ }
123
+ });
124
+ dbClient.release();
125
+ });
126
+ }
127
+ else {
128
+ finish();
129
+ }
130
+ }).catch(err => {
131
+ dbClient.release();
132
+ throw err;
133
+ });
134
+ }).catch(err => {
135
+ res.status(500).json({
136
+ error: {
137
+ errorKey: 'internal.db',
138
+ additionalInfo: { message: err.message }
139
+ }
140
+ });
141
+ });
142
+ };
143
+ }
144
+ exports.withTransaction = withTransaction;
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.digitize = exports.fpEuros = exports.sendSelfPostableMessage = exports.idempotent = exports.lcm = exports.gcd = exports.utils = exports.clientErrorHandle = exports.btoa = exports.atob = void 0;
4
+ function atob(str) {
5
+ return Buffer.from(str, 'base64').toString('binary');
6
+ }
7
+ exports.atob = atob;
8
+ function btoa(str) {
9
+ return Buffer.from(str).toString('base64');
10
+ }
11
+ exports.btoa = btoa;
12
+ function clientErrorHandle(err) {
13
+ this.error('Error on DB client: %j', err);
14
+ }
15
+ exports.clientErrorHandle = clientErrorHandle;
16
+ exports.utils = {
17
+ clientErrorHandler: undefined
18
+ };
19
+ function gcdTwo(a, b) {
20
+ if (a === 0)
21
+ return b;
22
+ return gcdTwo(b % a, a);
23
+ }
24
+ function gcd(values) {
25
+ let result = values[0];
26
+ for (let i = 1; i < values.length; i++)
27
+ result = gcdTwo(values[i], result);
28
+ return result;
29
+ }
30
+ exports.gcd = gcd;
31
+ function lcm(values) {
32
+ let l = 1, divisor = 2;
33
+ while (true) {
34
+ let counter = 0;
35
+ let divisible = false;
36
+ for (let i = 0; i < values.length; i++) {
37
+ if (values[i] === 0) {
38
+ return 0;
39
+ }
40
+ else if (values[i] < 0) {
41
+ values[i] = values[i] * (-1);
42
+ }
43
+ if (values[i] === 1) {
44
+ counter++;
45
+ }
46
+ if (values[i] % divisor === 0) {
47
+ divisible = true;
48
+ values[i] = values[i] / divisor;
49
+ }
50
+ }
51
+ if (divisible) {
52
+ l = l * divisor;
53
+ }
54
+ else {
55
+ divisor++;
56
+ }
57
+ if (counter === values.length) {
58
+ return l;
59
+ }
60
+ }
61
+ }
62
+ exports.lcm = lcm;
63
+ function idempotent(repo, debug, logger) {
64
+ return function (req, res, next) {
65
+ let idempotenceKey = req.header('x-idempotent-key');
66
+ if (idempotenceKey) {
67
+ idempotenceKey = idempotenceKey.substring(0, 40);
68
+ repo.ApiCall.get(idempotenceKey).then(call => {
69
+ if (!call) {
70
+ const jsonTerminator = res.json;
71
+ const endTerminator = res.end;
72
+ res.json = (function (obj) {
73
+ repo.ApiCall.create({
74
+ id: idempotenceKey,
75
+ responseCode: res.statusCode,
76
+ responseJson: JSON.stringify(obj),
77
+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000)
78
+ }).then(() => jsonTerminator(obj), err => {
79
+ if (err)
80
+ logger.warn('Cannot save idempotent key: %j', err);
81
+ jsonTerminator(obj);
82
+ });
83
+ }).bind(res);
84
+ res.end = (function () {
85
+ repo.ApiCall.create({
86
+ id: idempotenceKey,
87
+ responseCode: res.statusCode,
88
+ responseJson: undefined,
89
+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000)
90
+ }).then(() => endTerminator(), err => {
91
+ if (err)
92
+ logger.warn('Cannot save idempotent key: %j', err);
93
+ endTerminator();
94
+ });
95
+ }).bind(res);
96
+ next();
97
+ }
98
+ else
99
+ res.status(417).json({
100
+ responseCode: call.responseCode,
101
+ responseBody: JSON.parse(call.responseJson)
102
+ });
103
+ }, err => res.status(500).json({
104
+ error: {
105
+ errorKey: 'internal.db',
106
+ additionalInfo: { message: err.message, stack: debug && err.stack }
107
+ }
108
+ }));
109
+ }
110
+ else
111
+ next();
112
+ };
113
+ }
114
+ exports.idempotent = idempotent;
115
+ function sendSelfPostableMessage(res, code, messageType, err) {
116
+ res.type('text/html').status(code).write(`
117
+ <!DOCTYPE HTML>
118
+ <html>
119
+ <head>
120
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
121
+ </head>
122
+ <body>
123
+ <script type="text/javascript">
124
+ window.parent.postMessage({
125
+ type: '${messageType}',
126
+ confirm: ${!err},
127
+ error: JSON.parse('${JSON.stringify(err) || 'null'}')
128
+ }, '*');
129
+ </script>
130
+ </body>
131
+ </html>
132
+ `);
133
+ res.end();
134
+ }
135
+ exports.sendSelfPostableMessage = sendSelfPostableMessage;
136
+ function fpEuros(n) {
137
+ return Math.round(n * 100) / 100;
138
+ }
139
+ exports.fpEuros = fpEuros;
140
+ function digitize(value, opts) {
141
+ if (value === undefined || value === null)
142
+ return 'undefined';
143
+ if (typeof value === 'number') {
144
+ if (isNaN(value))
145
+ return '-';
146
+ if (!isFinite(value))
147
+ return 'Infinite';
148
+ value = String(value);
149
+ }
150
+ else if (typeof value === 'string')
151
+ return value;
152
+ const parts = value.split('.');
153
+ const initialLength = parts[0].length;
154
+ for (let i = initialLength - 3; i > 0; i -= 3) {
155
+ parts[0] = parts[0].slice(0, i) + ',' + parts[0].slice(i);
156
+ }
157
+ if (parts[0].startsWith('-,'))
158
+ parts[0] = '-' + parts[0].slice(2);
159
+ if (parts[1]) {
160
+ const expDecimals = parts[1].split(/[eE]-/);
161
+ if (expDecimals.length > 1 && parseInt(expDecimals[1], 10) > 2)
162
+ return '0.00';
163
+ let decimals = fpEuros(parseFloat('0.' + parts[1])).toString().substr(2, 2);
164
+ if (decimals.length === 1)
165
+ decimals += '0';
166
+ return parts[0] + '.' + decimals;
167
+ }
168
+ return (opts && opts.currency) ? (parts[0] + '.00') : parts[0];
169
+ }
170
+ exports.digitize = digitize;