@e-mc/db 0.0.1

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/LICENSE ADDED
@@ -0,0 +1,11 @@
1
+ Copyright 2023 An Pham
2
+
3
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
4
+
5
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
6
+
7
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
8
+
9
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
10
+
11
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ ### @e-mc/db
2
+
3
+ ### LICENSE
4
+
5
+ BSD 3-Clause
package/index.d.ts ADDED
@@ -0,0 +1,5 @@
1
+ import type { DbConstructor } from '../types/lib';
2
+
3
+ declare const Db: DbConstructor;
4
+
5
+ export = Db;
package/index.js ADDED
@@ -0,0 +1,288 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const path = require("path");
4
+ const types_1 = require("../types");
5
+ const core_1 = require("../core");
6
+ const request_1 = require("../request");
7
+ const util_1 = require("./util");
8
+ const DB_CLIENT = {};
9
+ const POOL_CONFIG = {};
10
+ function sanitizePoolConfig(value) {
11
+ value.min ?? (value.min = -1);
12
+ value.max ?? (value.max = -1);
13
+ value.idle ?? (value.idle = -1);
14
+ value.queue_max ?? (value.queue_max = -1);
15
+ value.queue_idle ?? (value.queue_idle = -1);
16
+ value.purge ?? (value.purge = 0);
17
+ return value;
18
+ }
19
+ function setCert(items, cache) {
20
+ if (Array.isArray(items)) {
21
+ return items.map(cert => (0, types_1.isString)(cert) ? this.readTLSCert(cert, cache) : Buffer.isBuffer(cert) ? cert : null).filter(cert => cert);
22
+ }
23
+ if ((0, types_1.isString)(items)) {
24
+ return this.readTLSCert(items, cache);
25
+ }
26
+ }
27
+ class Db extends core_1.ClientDb {
28
+ constructor() {
29
+ super(...arguments);
30
+ this._moduleName = 'db';
31
+ this._threadable = true;
32
+ }
33
+ static async purgeMemory(percent = 1, limit = 0, parent) {
34
+ let result = 0;
35
+ if (percent > 0 && percent <= 1) {
36
+ for (const name in DB_CLIENT) {
37
+ const client = DB_CLIENT[name];
38
+ const { purge } = POOL_CONFIG[name];
39
+ if (purge > 0) {
40
+ const checkTimeout = client.checkTimeout?.bind(client);
41
+ if (checkTimeout) {
42
+ try {
43
+ result += await checkTimeout(purge, limit);
44
+ }
45
+ catch {
46
+ }
47
+ }
48
+ }
49
+ }
50
+ }
51
+ return result + (parent ? await super.purgeMemory(typeof parent === 'number' && parent > 0 ? parent : percent, 0, true) : 0);
52
+ }
53
+ static setPoolConfig(value) {
54
+ for (const name in value) {
55
+ const source = value[name];
56
+ if ((0, types_1.isPlainObject)(source)) {
57
+ POOL_CONFIG[name] = sanitizePoolConfig(source);
58
+ }
59
+ }
60
+ }
61
+ static getPoolConfig(source) {
62
+ return POOL_CONFIG[source];
63
+ }
64
+ setCredential(item) {
65
+ try {
66
+ return this.getClient(item.source).setCredential.call(this, item);
67
+ }
68
+ catch (err) {
69
+ return Promise.reject(err instanceof Error ? err : new Error(Db.asString(err) || "Invalid credentials" /* ERR_DB.CREDENTIALS */));
70
+ }
71
+ }
72
+ getCredential(item) {
73
+ let credential = item.credential, stored;
74
+ if (typeof credential === 'string') {
75
+ credential = this.module[item.source]?.[credential];
76
+ stored = true;
77
+ }
78
+ if ((0, types_1.isPlainObject)(credential)) {
79
+ if (this.settingsOf(item.source, 'coerce', 'credential') === true) {
80
+ (0, types_1.coerceObject)(credential, stored);
81
+ }
82
+ return stored ? item.credential = { ...credential } : credential;
83
+ }
84
+ return item.credential = undefined;
85
+ }
86
+ hasSource(source, ...type) {
87
+ try {
88
+ const client = this.getClient(source);
89
+ return type.length === 0 || type.every(value => (client.DB_SOURCE_TYPE & value) === value);
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ executeQuery(item, options) {
96
+ if (this.aborted) {
97
+ return Promise.reject((0, types_1.createAbortError)());
98
+ }
99
+ try {
100
+ return this.getClient(item.source).executeQuery.call(this, item, options);
101
+ }
102
+ catch (err) {
103
+ return Promise.reject(err);
104
+ }
105
+ }
106
+ executeBatchQuery(batch, options, outResult) {
107
+ if (this.aborted) {
108
+ return Promise.reject((0, types_1.createAbortError)());
109
+ }
110
+ try {
111
+ return this.getClient(batch[0].source).executeBatchQuery.call(this, batch, options, outResult);
112
+ }
113
+ catch (err) {
114
+ return Promise.reject(err);
115
+ }
116
+ }
117
+ processRows(batch, tasks, parallel, outResult) {
118
+ let disconnect;
119
+ if ((0, types_1.isObject)(parallel)) {
120
+ ({ disconnect, parallel } = parallel);
121
+ }
122
+ const terminate = () => {
123
+ this.applyState(batch, 8 /* TRANSACTION.TERMINATE */);
124
+ if (typeof disconnect === 'function') {
125
+ try {
126
+ disconnect();
127
+ }
128
+ catch {
129
+ }
130
+ }
131
+ };
132
+ const cleanup = () => {
133
+ this.applyState(batch, 16 /* TRANSACTION.ABORT */);
134
+ terminate();
135
+ if (outResult) {
136
+ for (let i = 0, length = outResult.length; i < length; ++i) {
137
+ outResult[i] = null;
138
+ }
139
+ return outResult;
140
+ }
141
+ return [];
142
+ };
143
+ if (tasks.length === 0) {
144
+ return Promise.resolve(cleanup());
145
+ }
146
+ if (!parallel && outResult) {
147
+ terminate();
148
+ return Promise.resolve(outResult);
149
+ }
150
+ return Promise.all(tasks)
151
+ .then(result => {
152
+ terminate();
153
+ if (outResult) {
154
+ for (let i = 0, length = outResult.length; i < length; ++i) {
155
+ outResult[i] = result[i] || null;
156
+ }
157
+ return outResult;
158
+ }
159
+ return result;
160
+ })
161
+ .catch(() => cleanup());
162
+ }
163
+ handleFail(err, item, options) {
164
+ this.add(item, 32 /* TRANSACTION.FAIL */);
165
+ item.transactionFail = true;
166
+ if (options && typeof options.errorQuery === 'function') {
167
+ if (options.errorQuery(err, item, options.commandType)) {
168
+ if (item.willAbort) {
169
+ this.abort();
170
+ }
171
+ return true;
172
+ }
173
+ }
174
+ else {
175
+ if (item.willAbort) {
176
+ this.abort();
177
+ }
178
+ this.writeFail(["Unable to execute query" /* ERR_DB.EXEC_QUERY */, item.source], err, 65536 /* LOG_TYPE.DB */);
179
+ }
180
+ return false;
181
+ }
182
+ commit(items) {
183
+ if (this.aborted) {
184
+ return Promise.reject((0, types_1.createAbortError)());
185
+ }
186
+ const tasks = (items || this.pending).map(data => {
187
+ data.ignoreCache ?? (data.ignoreCache = true);
188
+ return this.executeQuery(data).catch(() => {
189
+ this.applyState([data], 16 /* TRANSACTION.ABORT */);
190
+ return [];
191
+ });
192
+ });
193
+ return tasks.length === 0 ? Promise.resolve(false) : this.allSettled(tasks, ["Execute unassigned queries" /* CMD_DB.EXEC_QUERYUNASSIGNED */, this.moduleName]).then(result => result.length > 0).catch(() => false);
194
+ }
195
+ readTLSCert(value, cache) {
196
+ if ((0, types_1.isString)(value)) {
197
+ let pathname = value.trim();
198
+ if (request_1.default.isCert(pathname)) {
199
+ return pathname;
200
+ }
201
+ if (Db.isPath(pathname = path.resolve(pathname)) && this.canRead(pathname, { ownPermissionOnly: true })) {
202
+ return request_1.default.readCACert(pathname, cache);
203
+ }
204
+ }
205
+ return '';
206
+ }
207
+ readTLSConfig(options, cache = true) {
208
+ if ((0, types_1.isPlainObject)(options)) {
209
+ const { ca, cert, key } = options;
210
+ if (ca) {
211
+ options.ca = setCert.call(this, ca);
212
+ }
213
+ if (cert) {
214
+ options.cert = setCert.call(this, cert);
215
+ }
216
+ if (key) {
217
+ if ((0, types_1.isString)(key)) {
218
+ options.key = this.readTLSCert(key, cache);
219
+ }
220
+ else if ((0, types_1.isArray)(key)) {
221
+ options.key = key.map(item => (0, types_1.isString)(item) ? { pem: this.readTLSCert(item, cache) } : Buffer.isBuffer(item) ? { pem: item.toString('utf-8') } : item).filter(item => item.pem);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ resolveSource(source, folder) {
227
+ let result, sep = path.sep;
228
+ if (source[0] === '@') {
229
+ if ((result = source).indexOf('/') === -1) {
230
+ folder || (folder = 'client');
231
+ }
232
+ sep = '/';
233
+ }
234
+ else if (!Db.isDir(result = path.join(__dirname, source))) {
235
+ result = source;
236
+ sep = '/';
237
+ }
238
+ return result + (folder ? sep + folder : '');
239
+ }
240
+ getPoolConfig(source, uuidKey) {
241
+ const config = Db.getPoolConfig(source);
242
+ const result = uuidKey && this.settingsKey(uuidKey, 'pool');
243
+ if (result) {
244
+ if (config) {
245
+ result.min ?? (result.min = config.min);
246
+ result.max ?? (result.max = config.max);
247
+ result.idle ?? (result.idle = config.idle);
248
+ result.queue_max ?? (result.queue_max = config.queue_max);
249
+ result.queue_idle ?? (result.queue_idle = config.queue_idle);
250
+ }
251
+ else {
252
+ sanitizePoolConfig(result);
253
+ }
254
+ return result;
255
+ }
256
+ return config;
257
+ }
258
+ get sourceType() {
259
+ return types_1.DB_TYPE;
260
+ }
261
+ get commandType() {
262
+ return util_1.SQL_COMMAND;
263
+ }
264
+ getClient(source) {
265
+ let client;
266
+ if (client = DB_CLIENT[source]) {
267
+ return client;
268
+ }
269
+ try {
270
+ client = require(this.resolveSource(source));
271
+ if (client?.DB_SOURCE_CLIENT) {
272
+ client.DB_SOURCE_NAME = source;
273
+ return DB_CLIENT[source] = client;
274
+ }
275
+ }
276
+ catch {
277
+ }
278
+ throw (0, types_1.errorMessage)(source, "Database provider not found" /* ERR_DB.PROVIDER_NOTFOUND */);
279
+ }
280
+ }
281
+ Object.freeze(types_1.DB_TYPE);
282
+ Object.freeze(util_1.SQL_COMMAND);
283
+ exports.default = Db;
284
+
285
+ if (exports.default) {
286
+ module.exports = exports.default;
287
+ module.exports.default = exports.default;
288
+ }
@@ -0,0 +1,19 @@
1
+ import type { MongoDBDataSource, MongoDBSortValue } from '../../types/lib/db';
2
+
3
+ import type { IDbSourceClient } from '../types';
4
+
5
+ import type { CommandOperationOptions, Document, Filter, Sort, SortDirection } from 'mongodb';
6
+
7
+ interface DocumentFilterValue {
8
+ value?: DocumentFilter;
9
+ options?: CommandOperationOptions;
10
+ }
11
+
12
+ type DocumentFilter = Filter<Document>;
13
+
14
+ declare const MongoDB: IDbSourceClient<MongoDBDataSource> & {
15
+ getFilterValue: (query: DocumentFilter | DocumentFilterValue, coerce?: boolean) => [DocumentFilter, CommandOperationOptions?];
16
+ getSortValue: (sort: Sort | string | MongoDBSortValue, coerce?: boolean) => [Sort | string, SortDirection?];
17
+ };
18
+
19
+ export = MongoDB;