@samet-it/be-couchbase-common 1.0.17 → 1.1.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.
Files changed (40) hide show
  1. package/README.md +10 -10
  2. package/dist/config/couchbase-common.config.d.ts +5 -1
  3. package/dist/config/couchbase-common.config.js +15 -9
  4. package/dist/config/index.types.d.ts +17 -13
  5. package/dist/connection/cb-connection.fn.d.ts +8 -0
  6. package/dist/connection/cb-connection.fn.js +14 -0
  7. package/dist/connection/cb-direct.connection.d.ts +13 -0
  8. package/dist/connection/cb-direct.connection.js +21 -0
  9. package/dist/connection/cb.connection.d.ts +35 -0
  10. package/dist/{adapter/cb-adapter.service.js → connection/cb.connection.js} +97 -127
  11. package/dist/connection/index.d.ts +4 -0
  12. package/dist/{adapter → connection}/index.js +3 -2
  13. package/dist/connection/index.types.d.ts +94 -0
  14. package/dist/filter/cb-filter-util.impl.js +4 -4
  15. package/dist/filter/index.types.d.ts +4 -4
  16. package/dist/index.d.ts +1 -3
  17. package/dist/index.js +1 -6
  18. package/dist/repo/cb-direct.repo.d.ts +11 -0
  19. package/dist/repo/cb-direct.repo.js +37 -0
  20. package/dist/repo/cb-schema.error.d.ts +4 -0
  21. package/dist/repo/cb-schema.error.js +10 -0
  22. package/dist/repo/cb.repo.d.ts +43 -61
  23. package/dist/repo/cb.repo.js +480 -269
  24. package/dist/repo/index.d.ts +2 -0
  25. package/dist/repo/index.js +2 -0
  26. package/dist/repo/index.types.d.ts +121 -93
  27. package/package.json +8 -5
  28. package/dist/adapter/cb-adapter.module.d.ts +0 -2
  29. package/dist/adapter/cb-adapter.module.js +0 -23
  30. package/dist/adapter/cb-adapter.service.d.ts +0 -46
  31. package/dist/adapter/index.d.ts +0 -3
  32. package/dist/adapter/index.types.d.ts +0 -135
  33. package/dist/assets/source.MD +0 -1
  34. package/dist/line/cb-line.impl.d.ts +0 -2
  35. package/dist/line/cb-line.impl.js +0 -119
  36. package/dist/line/index.d.ts +0 -2
  37. package/dist/line/index.js +0 -18
  38. package/dist/line/index.types.d.ts +0 -62
  39. package/dist/line/index.types.js +0 -2
  40. /package/dist/{adapter → connection}/index.types.js +0 -0
package/README.md CHANGED
@@ -8,7 +8,7 @@
8
8
  \___/\____/\__,_/\___/_/ /_/_.___/\__,_/____/\___/ \___/\____/_/ /_/ /_/_/ /_/ /_/\____/_/ /_/
9
9
  ```
10
10
  <!-- https://patorjk.com/software/taag/#p=display&f=Slant&t=couchbase+common&x=none&v=4&h=3&w=80&we=false -->
11
- - `EN`: Use it for Couchbase connections
11
+ - `EN`: Use it for couchbase connections
12
12
  - `TR`: Couchbase bağlantıları için bu bileşeni kullanınız
13
13
 
14
14
  ## Prerequisite
@@ -28,7 +28,7 @@ npm i @samet-it/be-couchbase-common
28
28
  ```
29
29
 
30
30
  ## Environments
31
- - [CouchbaseCommon](./src/config/couchbase-common.config.ts)
31
+ - [CouchbaseCommonConf](./src/config/couchbase-common.config.ts)
32
32
 
33
33
  | Name | Type | Default | Required | Secret | Description |
34
34
  |---------------------|---------|---------|----------|--------|---------------------------------------------|
@@ -39,14 +39,13 @@ npm i @samet-it/be-couchbase-common
39
39
  | `CB_SCOPE` | string | | ✅ | | Scope/Schema Name |
40
40
  | `CB_CREATE_INDICES` | boolean | _false_ | | | Does it create the indices when it deploys? |
41
41
 
42
-
43
42
  ## Contents
44
- - [CbAdapterService](./src/adapter/cb-adapter.service.ts) - Injectable service
45
- - [CbAdapterModule](./src/adapter/cb-adapter.module.ts) - Nestjs Module
46
- - [couchbaseCommonConfig](./src/config/couchbase-common.config.ts) - config
47
- - [cbFilterUtil](./src/filter/cb-filter-util.impl.ts) - query filter utility
48
- - [cbLine()](./src/line/cb-line.impl.ts) - sql line utility
49
- - [CbRepo](./src/repo/cb.repo.ts) - abstract repository
43
+ - `abstract` [CbConnection](src/connection/cb.connection.ts) - abstract connection class
44
+ - `class` [CbDirectConnection](src/connection/cb-direct.connection.ts) - Direct connection
45
+ - `function` [cbConnection()](src/connection/cb-connection.fn.ts) - Connection function
46
+ - `abstract` [CbRepo](./src/repo/cb.repo.ts) - abstract repository
47
+ - `class` [CbDirectRepo](./src/repo/cb-direct.repo.ts) - direct repository
48
+ - `instance` [cbFilterUtil](./src/filter/cb-filter-util.impl.ts) - query filter utility
50
49
 
51
50
 
52
51
  ## Development
@@ -64,8 +63,9 @@ git clone https://github.com/samet-digital/be-couchbase-common.git -b developmen
64
63
 
65
64
  ## Dependencies
66
65
  - `@samet-it/be-base-common`: **samet** base common
66
+ - `@samet-it/be-db-common`: **samet** db common
67
+ - `@samet-it/be-cache-common`: **samet** cache common
67
68
  - `@leyyo/*`: leyyo utilities
68
- - `@nestjs/*`: nestjs framework
69
69
  - `couchbase`: couchbase client
70
70
 
71
71
  ## Commands
@@ -1,2 +1,6 @@
1
1
  import type { CouchbaseCommonConf } from "./index.types";
2
- export declare const couchbaseCommonConfig: import("@leyyo/env").EnvScopeRuntime<CouchbaseCommonConf>;
2
+ /**
3
+ * Couchbase common config
4
+ * @config
5
+ * */
6
+ export declare const couchbaseCommonConfig: import("@leyyo/env").EnvScopeRuntime<CouchbaseCommonConf, "CB", undefined>;
@@ -2,13 +2,19 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.couchbaseCommonConfig = void 0;
4
4
  const env_1 = require("@leyyo/env");
5
+ /**
6
+ * Couchbase common config
7
+ * @config
8
+ * */
5
9
  exports.couchbaseCommonConfig = env_1.envCore.configure
6
- .scope('CouchbaseCommon')
7
- .begin
8
- .field('CB_HOST').text().required().end
9
- .field('CB_USER').text().required().end
10
- .field('CB_PASS').text().required().end
11
- .field('CB_BUCKET').text().required().end
12
- .field('CB_SCOPE').text().required().end
13
- .field('CB_CREATE_INDICES').boolean().def(false).end
14
- .end;
10
+ .scope('CouchbaseCommon', 'CB')
11
+ .start()
12
+ .field('PROTOCOL').text().def('couchbase').end()
13
+ .field('HOST').text().required().end()
14
+ .field('PORT').integer().end()
15
+ .field('USER').text().required().end()
16
+ .field('PASS').text().required().end()
17
+ .field('BUCKET').text().required().end()
18
+ .field('SCOPE').text().required().end()
19
+ .field('CREATE_INDICES').boolean().def(false).end()
20
+ .finish();
@@ -1,31 +1,35 @@
1
1
  import type { EnvBase } from "@leyyo/env";
2
- export declare namespace NodeJS {
3
- interface ProcessEnv extends CouchbaseCommonConf {
4
- }
5
- }
6
2
  export interface CouchbaseCommonConf extends EnvBase {
7
3
  /**
8
- * DB Host
4
+ * Protocol
5
+ * */
6
+ readonly PROTOCOL: string;
7
+ /**
8
+ * Host name or ip address
9
+ * */
10
+ readonly HOST: string;
11
+ /**
12
+ * Port number
9
13
  * */
10
- readonly CB_HOST: string;
14
+ readonly PORT: number;
11
15
  /**
12
- * DB User
16
+ * Username
13
17
  * */
14
- readonly CB_USER: string;
18
+ readonly USER: string;
15
19
  /**
16
- * DB Password
20
+ * Password
17
21
  * */
18
- readonly CB_PASS: string;
22
+ readonly PASS: string;
19
23
  /**
20
24
  * Current bucket (database name)
21
25
  * */
22
- readonly CB_BUCKET: string;
26
+ readonly BUCKET: string;
23
27
  /**
24
28
  * Current scope (schema name)
25
29
  * */
26
- readonly CB_SCOPE: string;
30
+ readonly SCOPE: string;
27
31
  /**
28
32
  * Create indices when it's started
29
33
  * */
30
- readonly CB_CREATE_INDICES: boolean;
34
+ readonly CREATE_INDICES: boolean;
31
35
  }
@@ -0,0 +1,8 @@
1
+ import type { CbDirectConnectionLike, CbDirectConnOpt } from "./index.types";
2
+ /**
3
+ * Crete new couchbase connection
4
+ *
5
+ * @param {CbDirectConnOpt?} opt - option
6
+ * @return {CbDirectConnectionLike} - new connection instance
7
+ * */
8
+ export declare function cbConnection(opt?: CbDirectConnOpt): CbDirectConnectionLike;
@@ -0,0 +1,14 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cbConnection = cbConnection;
4
+ const cb_direct_connection_1 = require("./cb-direct.connection");
5
+ // noinspection JSUnusedGlobalSymbols
6
+ /**
7
+ * Crete new couchbase connection
8
+ *
9
+ * @param {CbDirectConnOpt?} opt - option
10
+ * @return {CbDirectConnectionLike} - new connection instance
11
+ * */
12
+ function cbConnection(opt) {
13
+ return new cb_direct_connection_1.CbDirectConnection(opt);
14
+ }
@@ -0,0 +1,13 @@
1
+ import { CbConnection } from "./cb.connection";
2
+ import type { DefDims, Entity, UrnDocLike, Pair, Portion, View } from "@samet-it/be-base-common";
3
+ import { type CbRepoDirectOpt, type CbRepoLike } from "../repo";
4
+ import type { CbDirectConnectionLike, CbDirectConnOpt } from "./index.types";
5
+ import type { KeyValue } from "@leyyo/common";
6
+ /**
7
+ * Couchbase connection direct class
8
+ * */
9
+ export declare class CbDirectConnection extends CbConnection implements CbDirectConnectionLike {
10
+ constructor(opt?: CbDirectConnOpt);
11
+ /** @inheritDoc */
12
+ newRepo<ID extends KeyValue, ENTITY extends Entity<ID>, URN extends UrnDocLike, KEYS extends string = string, DIMS extends DefDims = DefDims, PAIR extends Pair<ID> = Pair<ID>, VIEW extends View<ID> = View<ID>, PORTION extends Portion<ID> = Portion<ID>, R = unknown>(opt: CbRepoDirectOpt<ID, ENTITY, URN, DIMS, R>): CbRepoLike<ID, ENTITY, URN, KEYS, DIMS, PAIR, VIEW, PORTION>;
13
+ }
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CbDirectConnection = void 0;
4
+ const cb_connection_1 = require("./cb.connection");
5
+ const be_base_common_1 = require("@samet-it/be-base-common");
6
+ const repo_1 = require("../repo");
7
+ // noinspection JSUnusedGlobalSymbols
8
+ /**
9
+ * Couchbase connection direct class
10
+ * */
11
+ class CbDirectConnection extends cb_connection_1.CbConnection {
12
+ constructor(opt) {
13
+ super(opt);
14
+ this.logger = be_base_common_1.logger.of(`CbConnection${(opt === null || opt === void 0 ? void 0 : opt.name) ? '#' + (opt === null || opt === void 0 ? void 0 : opt.name) : ''}`);
15
+ }
16
+ /** @inheritDoc */
17
+ newRepo(opt) {
18
+ return new repo_1.CbDirectRepo(this, opt);
19
+ }
20
+ }
21
+ exports.CbDirectConnection = CbDirectConnection;
@@ -0,0 +1,35 @@
1
+ import type { QueryResult, QueryMetaData } from 'couchbase';
2
+ import { type IgnoreFieldsByType, type ReplaceType } from "@leyyo/common";
3
+ import { DbConnection, type DbLines } from "@samet-it/be-db-common";
4
+ import type { CbConnectionLike, CbConnOpt, CbExecOpt, CbConnProps } from "./index.types";
5
+ import type { CbRepoDef } from "../repo";
6
+ import type { DbQueryResultMore, DbQueryResultOne } from "@samet-it/be-db-common";
7
+ /**
8
+ * Couchbase connection abstract class
9
+ * */
10
+ export declare abstract class CbConnection extends DbConnection<CbRepoDef, QueryMetaData, CbExecOpt> implements CbConnectionLike {
11
+ /** {@inheritDoc} */
12
+ protected _props: CbConnProps;
13
+ protected constructor(opt?: CbConnOpt);
14
+ protected _readEnv(): void;
15
+ /** {@inheritDoc} */
16
+ get props(): Readonly<CbConnProps>;
17
+ /** {@inheritDoc} */
18
+ field(field: string): string;
19
+ /** {@inheritDoc} */
20
+ value(value: unknown): string;
21
+ /** {@inheritDoc} */
22
+ flatten<T>(result: QueryResult<T>): Array<T>;
23
+ /** {@inheritDoc} */
24
+ castDates<T>(given: ReplaceType<T, Date, string> | T, ...fields: Array<IgnoreFieldsByType<T, Date>>): void;
25
+ /** {@inheritDoc} */
26
+ castDatesForList<T>(given: Array<ReplaceType<T, Date, string> | T>, ...fields: Array<IgnoreFieldsByType<T, Date>>): void;
27
+ /** {@inheritDoc} */
28
+ more<T>(repo: CbRepoDef, lines: string | DbLines, p1?: string | CbExecOpt): Promise<DbQueryResultMore<T, QueryMetaData>>;
29
+ /** {@inheritDoc} */
30
+ one<T>(repo: CbRepoDef, lines: string | DbLines, p1?: string | CbExecOpt): Promise<DbQueryResultOne<T, QueryMetaData>>;
31
+ /** {@inheritDoc} */
32
+ connect(): Promise<boolean>;
33
+ /** {@inheritDoc} */
34
+ ping(next?: boolean): Promise<boolean>;
35
+ }
@@ -16,12 +16,6 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
16
16
  }) : function(o, v) {
17
17
  o["default"] = v;
18
18
  });
19
- var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
20
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
21
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
22
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
23
- return c > 3 && r && Object.defineProperty(target, key, r), r;
24
- };
25
19
  var __importStar = (this && this.__importStar) || (function () {
26
20
  var ownKeys = function(o) {
27
21
  ownKeys = Object.getOwnPropertyNames || function (o) {
@@ -39,9 +33,6 @@ var __importStar = (this && this.__importStar) || (function () {
39
33
  return result;
40
34
  };
41
35
  })();
42
- var __metadata = (this && this.__metadata) || function (k, v) {
43
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
44
- };
45
36
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
46
37
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
47
38
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -52,63 +43,48 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
52
43
  });
53
44
  };
54
45
  Object.defineProperty(exports, "__esModule", { value: true });
55
- exports.CbAdapterService = void 0;
46
+ exports.CbConnection = void 0;
56
47
  const couchbase = __importStar(require("couchbase"));
57
- const common_1 = require("@nestjs/common");
58
48
  const config_1 = require("../config");
59
- const common_2 = require("@leyyo/common");
49
+ const common_1 = require("@leyyo/common");
60
50
  const filter_1 = require("../filter");
61
- // noinspection JSUnusedGlobalSymbols
62
- let CbAdapterService = class CbAdapterService {
63
- constructor() {
64
- this._CLEAR_ERROR_INTERVAL = 1000 * 60 * 60 * 24; // daily
65
- this._nativeErrors = new Map();
66
- this.logger = new common_1.Logger(this.constructor.name);
67
- this._clearErrors();
51
+ const be_db_common_1 = require("@samet-it/be-db-common");
52
+ const type_1 = require("@leyyo/type");
53
+ /**
54
+ * Couchbase connection abstract class
55
+ * */
56
+ class CbConnection extends be_db_common_1.DbConnection {
57
+ // endregion protected-property
58
+ constructor(opt) {
59
+ super(opt);
68
60
  filter_1.cbFilterUtil.$set(this);
61
+ this._readEnv();
69
62
  }
70
- /**
71
- * Clear native errors
72
- * */
73
- _clearErrors() {
74
- this._nativeErrors.clear();
75
- setTimeout(() => this._clearErrors(), this._CLEAR_ERROR_INTERVAL);
76
- }
77
- /**
78
- * Ping to DB
79
- * */
80
- _ping() {
81
- return __awaiter(this, void 0, void 0, function* () {
82
- try {
83
- yield this.exec(this._cluster.ping(), { name: 'ping' });
84
- }
85
- catch (err) {
86
- this.logger.warn(`Ping error => [${err.name}: ${err.message}]`);
87
- }
88
- setTimeout(() => this._ping(), 30000);
89
- });
90
- }
91
- _checkError(err, opt) {
92
- var _a, _b, _c;
93
- let size = 1;
94
- if (!this._nativeErrors.has(err)) {
95
- this._nativeErrors.set(err, size);
96
- }
97
- else {
98
- size = this._nativeErrors.get(err) + 1;
99
- this._nativeErrors.set(err, size);
100
- }
101
- if ((_a = opt === null || opt === void 0 ? void 0 : opt.ignoredErrors) === null || _a === void 0 ? void 0 : _a.includes(err)) {
102
- this.logger.warn(`[${size}] ${(_b = opt.name) !== null && _b !== void 0 ? _b : 'Ignored error'} => [${err.name}: ${err.message}]`);
103
- return;
63
+ // region protected-method
64
+ _readEnv() {
65
+ var _a, _b, _c, _d, _e, _f, _g, _h;
66
+ const { _props: props } = this;
67
+ let env = config_1.couchbaseCommonConfig.valueShort;
68
+ if (props.envVariant) {
69
+ env = config_1.couchbaseCommonConfig.configure.getVariation(props.envVariant).valueShort;
104
70
  }
105
- this.logger.error(`[${size}] ${(_c = opt.name) !== null && _c !== void 0 ? _c : 'Database error'} => [${err.name}: ${err.message}]`, JSON.stringify(err.context));
106
- throw err;
71
+ props.protocol = (_a = props.protocol) !== null && _a !== void 0 ? _a : env.PROTOCOL;
72
+ props.host = (_b = props.host) !== null && _b !== void 0 ? _b : env.HOST;
73
+ props.port = (_c = props.port) !== null && _c !== void 0 ? _c : env.PORT;
74
+ props.username = (_d = props.username) !== null && _d !== void 0 ? _d : env.USER;
75
+ props.password = (_e = props.password) !== null && _e !== void 0 ? _e : env.PASS;
76
+ props.bucketName = (_f = props.bucketName) !== null && _f !== void 0 ? _f : env.BUCKET;
77
+ props.scopeName = (_g = props.scopeName) !== null && _g !== void 0 ? _g : env.SCOPE;
78
+ props.createIndices = (_h = props.createIndices) !== null && _h !== void 0 ? _h : env.CREATE_INDICES;
107
79
  }
80
+ // endregion protected-method
81
+ // region getter
108
82
  /** {@inheritDoc} */
109
- f(field) {
110
- return this.field(field);
83
+ get props() {
84
+ return this._props;
111
85
  }
86
+ // endregion getter
87
+ // region field-value
112
88
  /** {@inheritDoc} */
113
89
  field(field) {
114
90
  field = field.trim();
@@ -117,9 +93,7 @@ let CbAdapterService = class CbAdapterService {
117
93
  }
118
94
  return field.startsWith('`') ? field : `\`${field}\``;
119
95
  }
120
- v(value) {
121
- return this.value(value);
122
- }
96
+ /** {@inheritDoc} */
123
97
  value(value) {
124
98
  var _a;
125
99
  switch (typeof value) {
@@ -131,7 +105,7 @@ let CbAdapterService = class CbAdapterService {
131
105
  return value ? `true` : 'false';
132
106
  case "object":
133
107
  if (value) {
134
- return common_2.$dev.secureJson(value, true);
108
+ return (0, common_1.secureJson)(value);
135
109
  }
136
110
  else {
137
111
  return 'null';
@@ -152,27 +126,8 @@ let CbAdapterService = class CbAdapterService {
152
126
  }
153
127
  return [];
154
128
  }
155
- /** {@inheritDoc} */
156
- rows(rows) {
157
- if (rows && Array.isArray(rows) && (rows.length > 0)) {
158
- return rows.filter(row => row['_trashId'] === undefined);
159
- }
160
- return [];
161
- }
162
- /** {@inheritDoc} */
163
- row(row) {
164
- if (row && row['_trashId'] === undefined) {
165
- return row;
166
- }
167
- return undefined;
168
- }
169
- /** {@inheritDoc} */
170
- first(rows) {
171
- if (rows && Array.isArray(rows) && (rows.length > 0)) {
172
- return rows[0];
173
- }
174
- return undefined;
175
- }
129
+ // endregion field-value
130
+ // region transcoders
176
131
  /** {@inheritDoc} */
177
132
  castDates(given, ...fields) {
178
133
  if (fields.length < 1) {
@@ -200,35 +155,18 @@ let CbAdapterService = class CbAdapterService {
200
155
  const arr = given;
201
156
  arr.forEach(item => this.castDates(item, ...fields));
202
157
  }
203
- buildOpt(p1, name) {
204
- const opt = typeof p1 === 'string' ? { name: p1 } : Object.assign({}, p1);
205
- if (typeof opt.name === undefined && typeof name !== undefined) {
206
- opt.name = name;
207
- }
208
- opt.name = opt.name ? `[${opt.name}]` : '';
209
- return opt;
210
- }
158
+ // endregion transcoders
159
+ // region query
211
160
  /** {@inheritDoc} */
212
- exec(fn, p1) {
213
- return __awaiter(this, void 0, void 0, function* () {
214
- const opt = this.buildOpt(p1);
215
- try {
216
- return yield fn;
217
- }
218
- catch (err) {
219
- this._checkError(err, opt);
220
- return undefined;
221
- }
222
- });
223
- }
224
- more(repo, sql, p1) {
161
+ more(repo, lines, p1) {
225
162
  return __awaiter(this, void 0, void 0, function* () {
226
163
  const opt = this.buildOpt(p1);
164
+ const sql = (0, type_1.isObjectValid)(lines) ? lines.end() : lines;
227
165
  if (opt.printSql) {
228
- this.logger.log(`${repo.path} > SQL${opt.name}`, sql);
166
+ this.logger.log(`${repo.props.path} > SQL${opt.name}`, sql);
229
167
  }
230
168
  try {
231
- const result = yield repo.scope.query(sql, opt);
169
+ const result = yield repo.props.scope.query(sql, opt);
232
170
  return {
233
171
  success: true,
234
172
  rows: result.rows,
@@ -236,7 +174,7 @@ let CbAdapterService = class CbAdapterService {
236
174
  };
237
175
  }
238
176
  catch (err) {
239
- this._checkError(err, opt);
177
+ this.checkError(err, Object.assign(Object.assign({}, opt), { sql }));
240
178
  return {
241
179
  success: false,
242
180
  rows: [],
@@ -245,14 +183,16 @@ let CbAdapterService = class CbAdapterService {
245
183
  }
246
184
  });
247
185
  }
248
- one(repo, sql, p1) {
186
+ /** {@inheritDoc} */
187
+ one(repo, lines, p1) {
249
188
  return __awaiter(this, void 0, void 0, function* () {
250
189
  const opt = this.buildOpt(p1);
190
+ const sql = (0, type_1.isObjectValid)(lines) ? lines.end() : lines;
251
191
  if (opt.printSql) {
252
- this.logger.log(`${repo.path} > SQL${opt.name}`, sql);
192
+ this.logger.log(`${repo.props.path} > SQL${opt.name}`, sql);
253
193
  }
254
194
  try {
255
- const result = yield repo.scope.query(sql, opt);
195
+ const result = yield repo.props.scope.query(sql, opt);
256
196
  return {
257
197
  success: true,
258
198
  row: (Array.isArray(result.rows) && result.rows.length > 0) ? result.rows[0] : undefined,
@@ -260,7 +200,7 @@ let CbAdapterService = class CbAdapterService {
260
200
  };
261
201
  }
262
202
  catch (err) {
263
- this._checkError(err, opt);
203
+ this.checkError(err, Object.assign(Object.assign({}, opt), { sql }));
264
204
  return {
265
205
  success: false,
266
206
  row: undefined,
@@ -269,32 +209,62 @@ let CbAdapterService = class CbAdapterService {
269
209
  }
270
210
  });
271
211
  }
212
+ // endregion query
213
+ // region connect
272
214
  /** {@inheritDoc} */
273
- connectDb() {
215
+ connect() {
274
216
  return __awaiter(this, void 0, void 0, function* () {
275
- if (this._connected) {
276
- return this._cluster;
217
+ const { _props: props } = this;
218
+ if (props.isConnected) {
219
+ return true;
277
220
  }
278
- const opt = config_1.couchbaseCommonConfig.raw;
279
221
  try {
280
- this._cluster = yield couchbase.connect(`couchbase://${opt.CB_HOST}`, {
281
- username: opt.CB_USER,
282
- password: opt.CB_PASS,
222
+ props.cluster = yield couchbase.connect(`${props.protocol}://${props.host}`, {
223
+ username: props.username,
224
+ password: props.password,
283
225
  });
284
- this._connected = true;
226
+ props.isConnected = true;
285
227
  this.logger.log('Connected');
286
- setTimeout(() => this._ping(), 30000);
287
- return this._cluster;
228
+ setTimeout(() => this.ping(true).then(), 30000);
288
229
  }
289
230
  catch (e) {
290
- this.logger.error(`Connection error => [${e.name}: ${e.message}]`);
231
+ this.checkError(e, { name: 'connection' });
291
232
  throw e;
292
233
  }
234
+ if (props.isFirst === undefined) {
235
+ if (this._onFirstConnected.length > 0) {
236
+ yield Promise.all(this._onFirstConnected);
237
+ this._onFirstConnected = [];
238
+ }
239
+ props.isFirst = false;
240
+ }
241
+ if (this._onConnected.length > 0) {
242
+ this._onConnected.forEach(fn => {
243
+ fn().then().catch(e => {
244
+ this.logger.error(`OnConnected <${e.name}> ${e.message}`);
245
+ });
246
+ });
247
+ }
248
+ return true;
293
249
  });
294
250
  }
295
- };
296
- exports.CbAdapterService = CbAdapterService;
297
- exports.CbAdapterService = CbAdapterService = __decorate([
298
- (0, common_1.Injectable)(),
299
- __metadata("design:paramtypes", [])
300
- ], CbAdapterService);
251
+ /** {@inheritDoc} */
252
+ ping(next) {
253
+ return __awaiter(this, void 0, void 0, function* () {
254
+ const { _props: props } = this;
255
+ let result = false;
256
+ try {
257
+ yield this.exec(props.cluster.ping(), { name: 'ping' });
258
+ result = true;
259
+ }
260
+ catch (err) {
261
+ this.checkError(err, { name: 'ping', silent: true });
262
+ }
263
+ if (next) {
264
+ setTimeout(() => this.ping(true).then(), 30000);
265
+ }
266
+ return result;
267
+ });
268
+ }
269
+ }
270
+ exports.CbConnection = CbConnection;
@@ -0,0 +1,4 @@
1
+ export * from './index.types';
2
+ export * from './cb.connection';
3
+ export * from './cb-connection.fn';
4
+ export * from './cb-direct.connection';
@@ -15,5 +15,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./index.types"), exports);
18
- __exportStar(require("./cb-adapter.service"), exports);
19
- __exportStar(require("./cb-adapter.module"), exports);
18
+ __exportStar(require("./cb.connection"), exports);
19
+ __exportStar(require("./cb-connection.fn"), exports);
20
+ __exportStar(require("./cb-direct.connection"), exports);