@samet-it/be-db-common 1.1.5 → 1.1.8

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/README.md CHANGED
@@ -35,6 +35,12 @@ npm i @samet-it/be-db-common
35
35
  - [function dbLines()](./src/line/db-lines.impl.ts)
36
36
  - [abstract class DbRepo](./src/repo/db.repo.ts)
37
37
 
38
+ ## Errors
39
+ - `base error` [DbError](./src/error/db.error.ts)
40
+ - `execute error` [DbExecuteError](./src/error/db-execute.error.ts)
41
+ - `invalid value error` [DbInvalidValueError](./src/error/db-invalid-value.error.ts)
42
+ - `not supported error` [DbNotSupportedError](./src/error/db-not-supported.error.ts)
43
+
38
44
  ## Development
39
45
  > You can start to develop on it
40
46
  >
@@ -1,15 +1,16 @@
1
- import { DbConnectionLike, DbExecOpt, DbQueryResultMore, DbQueryResultOne, DbConnOpt, DbMeta, DbOnAfter, DbConnProps, DbRepoLink, DbEvent } from "./index.types";
2
- import { LoggerLike } from "@samet-it/be-base-common";
3
- import type { DbLines } from "../line";
4
- import type { Opt } from "@leyyo/common";
1
+ import type { DbConnectionLike, DbConnOpt, DbOnAfter, DbConnProps, DbEvent } from "./index.types";
2
+ import type { Logger } from "@leyyo/common";
5
3
  /**
6
4
  * DB connection abstract class
5
+ *
6
+ * Generics:
7
+ * - 0-`OPT`: db execution options {@link DbExecOpt}
7
8
  * */
8
- export declare abstract class DbConnection<LINK extends DbRepoLink, META extends DbMeta, OPT extends DbExecOpt> implements DbConnectionLike<LINK, META, OPT> {
9
+ export declare abstract class DbConnection implements DbConnectionLike {
9
10
  /**
10
11
  * Logger
11
12
  * */
12
- protected logger: LoggerLike;
13
+ protected logger: Logger;
13
14
  /**
14
15
  * On connected callbacks
15
16
  * */
@@ -54,36 +55,27 @@ export declare abstract class DbConnection<LINK extends DbRepoLink, META extends
54
55
  * @param {boolean} throwable - throwable? yes: throw the error
55
56
  * */
56
57
  protected _triggerOnCase(name: DbEvent, items: Array<DbOnAfter>, throwable: boolean): void;
58
+ /**
59
+ * Generate next delay time with exponential & randomized manner
60
+ *
61
+ * @param {number} count - try count
62
+ * @param {number} baseDelay - starting delay interval
63
+ * @param {number} maxDelay - maximum delay interval
64
+ * @return {number}
65
+ * */
66
+ protected _delayWithJitter(count: number, baseDelay: number, maxDelay: number): number;
57
67
  /** {@inheritDoc} */
58
68
  get props(): Readonly<DbConnProps>;
59
69
  /** {@inheritDoc} */
60
- checkError(err: Error, opt: DbExecOpt | Opt): void;
61
- /** {@inheritDoc} */
62
- f(field: string): string;
63
- /** {@inheritDoc} */
64
- abstract field(field: string): string;
65
- v(value: unknown): string;
66
- abstract value(value: unknown): string;
67
- /** {@inheritDoc} */
68
- rows<T>(rows: Array<T>): Array<T>;
70
+ get isEnabled(): boolean;
69
71
  /** {@inheritDoc} */
70
- row<T>(row: T): T | undefined;
71
- /** {@inheritDoc} */
72
- first<T>(rows: Array<T>): T | undefined;
73
- /** {@inheritDoc} */
74
- buildOpt(p1?: Partial<OPT> | string, name?: string): OPT;
72
+ get isConnected(): boolean;
75
73
  /** {@inheritDoc} */
76
74
  onConnected(fn: DbOnAfter): void;
77
75
  /** {@inheritDoc} */
78
76
  onDisconnected(fn: DbOnAfter): void;
79
77
  /** {@inheritDoc} */
80
78
  onFirstConnected(fn: DbOnAfter): void;
81
- /** {@inheritDoc} */
82
- exec<T>(fn: Promise<T>, p1?: string | Omit<OPT, 'printSql'>): Promise<T>;
83
- /** {@inheritDoc} */
84
- abstract more<T>(link: LINK, sql: string | DbLines, name?: string | DbExecOpt): Promise<DbQueryResultMore<T, META>>;
85
- /** {@inheritDoc} */
86
- abstract one<T>(link: LINK, sql: string | DbLines, name?: string | DbExecOpt): Promise<DbQueryResultOne<T, META>>;
87
79
  /**
88
80
  * It will be called during module based systems
89
81
  * */
@@ -12,10 +12,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.DbConnection = void 0;
13
13
  const be_base_common_1 = require("@samet-it/be-base-common");
14
14
  const type_1 = require("@leyyo/type");
15
- const error_1 = require("../error");
16
15
  // noinspection JSUnusedGlobalSymbols
17
16
  /**
18
17
  * DB connection abstract class
18
+ *
19
+ * Generics:
20
+ * - 0-`OPT`: db execution options {@link DbExecOpt}
19
21
  * */
20
22
  class DbConnection {
21
23
  // endregion protected-property
@@ -47,7 +49,7 @@ class DbConnection {
47
49
  if ((0, type_1.isObjectBare)(opt)) {
48
50
  this._opt = Object.assign(Object.assign({}, this._opt), opt);
49
51
  }
50
- this._props = Object.assign({}, this._opt);
52
+ this._props = Object.assign(Object.assign({}, this._opt), { connectTryCount: 0, pingTryCount: 0 });
51
53
  delete this._opt;
52
54
  }
53
55
  // region protected-method
@@ -94,78 +96,33 @@ class DbConnection {
94
96
  });
95
97
  }
96
98
  }
99
+ /**
100
+ * Generate next delay time with exponential & randomized manner
101
+ *
102
+ * @param {number} count - try count
103
+ * @param {number} baseDelay - starting delay interval
104
+ * @param {number} maxDelay - maximum delay interval
105
+ * @return {number}
106
+ * */
107
+ _delayWithJitter(count, baseDelay, maxDelay) {
108
+ const exp = Math.min(baseDelay * Math.pow(2, count), maxDelay);
109
+ return exp / 2 + Math.random() * (exp / 2);
110
+ }
97
111
  // endregion protected-method
98
112
  // region getter
99
113
  /** {@inheritDoc} */
100
114
  get props() {
101
115
  return this._props;
102
116
  }
103
- // endregion getter
104
- // region field-value
105
- /** {@inheritDoc} */
106
- checkError(err, opt) {
107
- var _a, _b, _c;
108
- const size = be_base_common_1.errorHandler.addStat(err);
109
- const ignoredErrors = (_a = opt === null || opt === void 0 ? void 0 : opt.ignoredErrors) !== null && _a !== void 0 ? _a : [];
110
- if (ignoredErrors.includes(err) || ignoredErrors.includes(err.name)) {
111
- return;
112
- }
113
- if (opt === null || opt === void 0 ? void 0 : opt.silent) {
114
- if (size < 100) {
115
- this.logger.warn(be_base_common_1.errorHandler.common.logText(err, ((_b = opt.name) !== null && _b !== void 0 ? _b : 'Database error'), size));
116
- }
117
- return;
118
- }
119
- if (size < 100) {
120
- this.logger.error(be_base_common_1.errorHandler.common.logText(err, ((_c = opt.name) !== null && _c !== void 0 ? _c : 'Database error'), size));
121
- }
122
- if (err instanceof error_1.DbError) {
123
- throw err;
124
- }
125
- else {
126
- throw be_base_common_1.errorHandler.common.castForClass(error_1.DbError, err, { queryName: opt.name });
127
- }
128
- }
129
117
  /** {@inheritDoc} */
130
- f(field) {
131
- return this.field(field);
132
- }
133
- v(value) {
134
- return this.value(value);
118
+ get isEnabled() {
119
+ return this._props.isEnabled;
135
120
  }
136
121
  /** {@inheritDoc} */
137
- rows(rows) {
138
- if (rows && Array.isArray(rows) && (rows.length > 0)) {
139
- return rows.filter(row => row['_trashId'] === undefined);
140
- }
141
- return [];
122
+ get isConnected() {
123
+ return this._props.isConnected;
142
124
  }
143
- /** {@inheritDoc} */
144
- row(row) {
145
- if (row && row['_trashId'] === undefined) {
146
- return row;
147
- }
148
- return undefined;
149
- }
150
- /** {@inheritDoc} */
151
- first(rows) {
152
- if (rows && Array.isArray(rows) && (rows.length > 0)) {
153
- return rows[0];
154
- }
155
- return undefined;
156
- }
157
- // endregion field-value
158
- // region option
159
- /** {@inheritDoc} */
160
- buildOpt(p1, name) {
161
- const opt = (typeof p1 === 'string' ? { name: p1 } : Object.assign({}, p1));
162
- if (typeof opt.name === undefined && typeof name !== undefined) {
163
- opt.name = name;
164
- }
165
- opt.name = opt.name ? `[${opt.name}]` : '';
166
- return opt;
167
- }
168
- // endregion option
125
+ // endregion getter
169
126
  // region callback
170
127
  /** {@inheritDoc} */
171
128
  onConnected(fn) {
@@ -180,30 +137,12 @@ class DbConnection {
180
137
  this._on('first-connected', this._onFirstConnected, fn, true);
181
138
  }
182
139
  // endregion callback
183
- // region query
184
- /** {@inheritDoc} */
185
- exec(fn, p1) {
186
- return __awaiter(this, void 0, void 0, function* () {
187
- if (!this._props.enabled) {
188
- return undefined;
189
- }
190
- const opt = this.buildOpt(p1);
191
- try {
192
- return yield fn;
193
- }
194
- catch (err) {
195
- this.checkError(err, opt);
196
- return undefined;
197
- }
198
- });
199
- }
200
- // endregion query
201
140
  /**
202
141
  * It will be called during module based systems
203
142
  * */
204
143
  onModuleInit() {
205
144
  return __awaiter(this, void 0, void 0, function* () {
206
- if (!this._props.enabled) {
145
+ if (!this.isEnabled) {
207
146
  return;
208
147
  }
209
148
  yield this.connect();
@@ -1,145 +1,20 @@
1
- import type { DbLines } from "../line";
2
- import type { OmitError, Opt } from "@leyyo/common";
1
+ import { KeyValue } from "@leyyo/common";
3
2
  /**
4
- * DB query result
5
- * */
6
- export interface DbQueryResult<META> {
7
- /**
8
- * Success or failure
9
- */
10
- success: boolean;
11
- /**
12
- * [when success=true] The meta-data which has been returned by the query.
13
- */
14
- meta?: META;
15
- /**
16
- * [when success=false] Couchbase error
17
- */
18
- error?: OmitError;
19
- }
20
- /**
21
- * DB query result as a row
22
- * */
23
- export interface DbQueryResultOne<E = any, META = unknown> extends DbQueryResult<META> {
24
- /**
25
- * The rows which have been returned by the query.
26
- */
27
- row: E | undefined;
28
- }
29
- /**
30
- * DB query result as rows
31
- * */
32
- export interface DbQueryResultMore<E = any, META = unknown> extends DbQueryResult<META> {
33
- /**
34
- * The rows which have been returned by the query.
35
- */
36
- rows: E[];
37
- }
38
- /**
39
- * DB query option
40
- * */
41
- export interface DbExecOpt extends Opt {
42
- /**
43
- * Name of SQL
44
- * */
45
- name?: string;
46
- /**
47
- * do not use cache
48
- * */
49
- noCache?: boolean;
50
- /**
51
- * Ignore context cache
52
- * */
53
- ignoreContext?: string;
54
- /**
55
- * Ignored errors
56
- * */
57
- ignoredErrors?: Array<OmitError | string>;
58
- /**
59
- * Print sql?
60
- * */
61
- printSql?: boolean;
62
- /**
63
- * Ignore any error
64
- * */
65
- silent?: boolean;
66
- /**
67
- * Trash id for only trash case
68
- * */
69
- trashId?: string;
70
- }
71
- /**
72
- * DB connection
3
+ * DB connection interface
73
4
  * */
74
- export interface DbConnectionBase<OPT extends DbExecOpt = DbExecOpt> {
75
- /**
76
- * Field name
77
- *
78
- * @param {string} field - raw field name
79
- * @return {string} - formatted field name
80
- * */
81
- field(field: string): string;
82
- /**
83
- * Field name
84
- * @alias #field
85
- *
86
- * @param {string} field - raw field name
87
- * @return {string} - formatted field name
88
- * */
89
- f(field: string): string;
90
- /**
91
- * Format value
92
- *
93
- * @param {string} value - raw value
94
- * @return {string} - formatted value
95
- * */
96
- value(value: unknown): string;
97
- /**
98
- * Format value
99
- * @alias #value
100
- *
101
- * @param {string} value - raw value
102
- * @return {string} - formatted value
103
- * */
104
- v(value: unknown): string;
105
- /**
106
- * Check rows and discard trashed
107
- *
108
- * @param {Array<any>} rows - rows
109
- * @return {Array<any>} - checked rows
110
- * */
111
- rows<T>(rows: Array<T>): Array<T>;
5
+ export interface DbConnectionLike {
112
6
  /**
113
- * Check row and discard trashed
114
- *
115
- * @param {any} row - row
116
- * @return {any} - checked row
117
- * */
118
- row<T>(row: T): T | undefined;
119
- /**
120
- * Return first row of rows
121
- *
122
- * @param {Array<any>} rows - rows
123
- * @return {any} - first row if exists
7
+ * Props on connection
124
8
  * */
125
- first<T>(rows: Array<T>): T | undefined;
9
+ get props(): Readonly<DbConnProps>;
126
10
  /**
127
- * Build option
128
- *
129
- * @param {(DbExecOpt|string)?} opt - option or query name
130
- * @param {string?} name - query name, if first param is option
131
- * @return {DbExecOpt} - formatted option
11
+ * Shortcut to {@link DbConnOpt#isEnabled}
132
12
  * */
133
- buildOpt(opt?: Partial<OPT> | string, name?: string): OPT;
134
- }
135
- /**
136
- * DB connection interface
137
- * */
138
- export interface DbConnectionLike<LINK extends DbRepoLink, META extends DbMeta, OPT extends DbExecOpt> extends DbConnectionBase {
13
+ get isEnabled(): boolean;
139
14
  /**
140
- * Props on connection
15
+ * Shortcut to {@link DbConnProps#isConnected}
141
16
  * */
142
- get props(): Readonly<DbConnProps>;
17
+ get isConnected(): boolean;
143
18
  /**
144
19
  * Add an async function into queue
145
20
  *
@@ -158,42 +33,6 @@ export interface DbConnectionLike<LINK extends DbRepoLink, META extends DbMeta,
158
33
  * @param {function} fn - callback
159
34
  * */
160
35
  onDisconnected(fn: DbOnAfter): void;
161
- /**
162
- * Check error
163
- *
164
- * @param {Error} err - error
165
- * @param {DbExecOpt} opt - option
166
- * */
167
- checkError(err: Error, opt: DbExecOpt | Opt): void;
168
- /**
169
- * Execute a lambda
170
- *
171
- * @param {function} fn - promise callback
172
- * @param {(DbExecOpt|string)?} opt - option or query name
173
- * @return {Promise} - generic type
174
- * @async
175
- * */
176
- exec<T>(fn: Promise<T>, opt?: string | Omit<OPT, 'printSql'>): Promise<T>;
177
- /**
178
- * Execute a sql and return rows
179
- *
180
- * @param {DbRepoLink} link - repository link
181
- * @param {(string|DbLines)} sql - sql or sql lines
182
- * @param {(DbExecOpt|string)?} opt - option or query name
183
- * @return {Promise<DbQueryResultMore>} - rows
184
- * @async
185
- * */
186
- more<T>(link: LINK, sql: string | DbLines, opt?: string | OPT): Promise<DbQueryResultMore<T, META>>;
187
- /**
188
- * Execute a sql and return a row
189
- *
190
- * @param {DbRepoLink} link - repository link
191
- * @param {(string|DbLines)} sql - sql or sql lines
192
- * @param {(DbExecOpt|string)?} opt - option or query name
193
- * @return {Promise<DbQueryResultOne>} - row
194
- * @async
195
- * */
196
- one<T>(link: LINK, sql: string | DbLines, opt?: string | OPT): Promise<DbQueryResultOne<T, META>>;
197
36
  /**
198
37
  * It will be called during module based systems
199
38
  *
@@ -218,11 +57,6 @@ export interface DbConnectionLike<LINK extends DbRepoLink, META extends DbMeta,
218
57
  * */
219
58
  ping(next?: boolean): Promise<boolean>;
220
59
  }
221
- /**
222
- * DB meta
223
- * */
224
- export interface DbMeta {
225
- }
226
60
  /**
227
61
  * DB connection option
228
62
  * */
@@ -232,7 +66,7 @@ export interface DbConnOpt {
232
66
  *
233
67
  * @type {boolean}
234
68
  * */
235
- enabled?: boolean;
69
+ isEnabled?: boolean;
236
70
  /**
237
71
  * Protocol
238
72
  *
@@ -276,7 +110,7 @@ export interface DbConnOpt {
276
110
  * @default `undefined`
277
111
  * @type {function}
278
112
  * */
279
- userFetcher?: () => Promise<string>;
113
+ userFetcher?: UserFetcherLambda;
280
114
  }
281
115
  /**
282
116
  * DB connection props
@@ -294,6 +128,20 @@ export interface DbConnProps extends DbConnOpt {
294
128
  * @type {boolean}
295
129
  * */
296
130
  isFirst: boolean;
131
+ /**
132
+ * Consecutive attempts for connection
133
+ * - It is cleared (zero) when it connected
134
+ *
135
+ * @type {number}
136
+ * */
137
+ connectTryCount: number;
138
+ /**
139
+ * Consecutive attempts for ping
140
+ * - It is cleared (zero) when it pinged
141
+ *
142
+ * @type {number}
143
+ * */
144
+ pingTryCount: number;
297
145
  }
298
146
  /**
299
147
  * DB on after lambda
@@ -304,7 +152,19 @@ export type DbOnAfter = () => Promise<void>;
304
152
  * DB connection events
305
153
  * */
306
154
  export type DbEvent = 'connected' | 'disconnected' | 'first-connected';
307
- /** Repository Link */
308
- export interface DbRepoLink {
309
- path: string;
155
+ /**
156
+ * User fetcher lambda
157
+ * - It uses ASL
158
+ * */
159
+ export type UserFetcherLambda = () => Promise<KeyValue>;
160
+ /**
161
+ * Db direct connection option
162
+ * */
163
+ export interface DbConnDirectOpt extends DbConnOpt {
164
+ /**
165
+ * logger name
166
+ *
167
+ * @type {string}
168
+ * */
169
+ name?: string;
310
170
  }