@samet-it/be-couchbase-common 1.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.
Files changed (39) hide show
  1. package/LICENSE +24 -0
  2. package/README.md +90 -0
  3. package/dist/adapter/cb-adapter.module.d.ts +2 -0
  4. package/dist/adapter/cb-adapter.module.js +23 -0
  5. package/dist/adapter/cb-adapter.service.d.ts +70 -0
  6. package/dist/adapter/cb-adapter.service.js +447 -0
  7. package/dist/adapter/index.d.ts +3 -0
  8. package/dist/adapter/index.js +19 -0
  9. package/dist/adapter/index.types.d.ts +163 -0
  10. package/dist/adapter/index.types.js +2 -0
  11. package/dist/assets/.gitkeep +0 -0
  12. package/dist/assets/source.MD +1 -0
  13. package/dist/config/couchbase-common.config.d.ts +2 -0
  14. package/dist/config/couchbase-common.config.js +13 -0
  15. package/dist/config/index.d.ts +2 -0
  16. package/dist/config/index.js +18 -0
  17. package/dist/config/index.types.d.ts +31 -0
  18. package/dist/config/index.types.js +2 -0
  19. package/dist/filter/cb-filter-util.impl.d.ts +2 -0
  20. package/dist/filter/cb-filter-util.impl.js +88 -0
  21. package/dist/filter/index.d.ts +2 -0
  22. package/dist/filter/index.js +18 -0
  23. package/dist/filter/index.types.d.ts +32 -0
  24. package/dist/filter/index.types.js +2 -0
  25. package/dist/index.d.ts +6 -0
  26. package/dist/index.js +25 -0
  27. package/dist/line/cb-line.impl.d.ts +2 -0
  28. package/dist/line/cb-line.impl.js +90 -0
  29. package/dist/line/index.d.ts +2 -0
  30. package/dist/line/index.js +18 -0
  31. package/dist/line/index.types.d.ts +58 -0
  32. package/dist/line/index.types.js +2 -0
  33. package/dist/repo/cb.repo.d.ts +95 -0
  34. package/dist/repo/cb.repo.js +375 -0
  35. package/dist/repo/index.d.ts +2 -0
  36. package/dist/repo/index.js +18 -0
  37. package/dist/repo/index.types.d.ts +144 -0
  38. package/dist/repo/index.types.js +2 -0
  39. package/package.json +75 -0
package/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Samet Global
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ Web: https://sametglobal.com
24
+ Responsible: Mustafa Yelmer (mustafay@samet.com.tr)
package/README.md ADDED
@@ -0,0 +1,90 @@
1
+ # Samet IT : Couchbase Common
2
+ `ts` `component` `backend`
3
+ ```
4
+ __ __
5
+ _________ __ _______/ /_ / /_ ____ _________ _________ ____ ___ ____ ___ ____ ____
6
+ / ___/ __ \/ / / / ___/ __ \/ __ \/ __ `/ ___/ _ \ / ___/ __ \/ __ `__ \/ __ `__ \/ __ \/ __ \
7
+ / /__/ /_/ / /_/ / /__/ / / / /_/ / /_/ (__ / __/ / /__/ /_/ / / / / / / / / / / / /_/ / / / /
8
+ \___/\____/\__,_/\___/_/ /_/_.___/\__,_/____/\___/ \___/\____/_/ /_/ /_/_/ /_/ /_/\____/_/ /_/
9
+ ```
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
12
+ - `TR`: Couchbase bağlantıları için bu bileşeni kullanınız
13
+
14
+ ## Prerequisite
15
+ - [Help](https://github.com/samet-digital/help)
16
+ - [1 - Install Git](https://github.com/samet-digital/help/blob/main//install-git.MD)
17
+ - [2 - Build Up a Git Connection](https://github.com/samet-digital/help/blob/main//build-git-connection.MD)
18
+ - [3 - Install Node/NPM](https://github.com/samet-digital/help/blob/main//install-npm.MD)
19
+ - [4 - Create Project Folder](https://github.com/samet-digital/help/blob/main//create-project-folder.MD)
20
+ - [5 - Bind Projects Folder to Git](https://github.com/samet-digital/help/blob/main//bind-project-folder.MD)
21
+
22
+ ## Usage
23
+ - `EN`: How to add into your project?
24
+ - `TR`: Projene nasıl eklersin?
25
+
26
+ ```shell
27
+ npm i @samet-it/be-couchbase-common
28
+ ```
29
+
30
+ ## Environments
31
+ - [couchbaseCommonConfig](./src/config/couchbase-common.config.ts) : config
32
+
33
+ | Name | Type | Default | Required | Secret | Description |
34
+ |---------------------|---------|---------|----------|--------|---------------------------------------------|
35
+ | `CB_HOST` | string | | ✅ | ⭕ | DB Host or IP Address |
36
+ | `CB_USER` | string | | ✅ | ⭕ | DB User |
37
+ | `CB_PASS` | string | | ✅ | ⭕ | DB Password |
38
+ | `CB_BUCKET` | string | | ✅ | | Bucket/DB Name |
39
+ | `CB_SCOPE` | string | | ✅ | | Scope/Schema Name |
40
+ | `CB_CREATE_INDICES` | boolean | _false_ | | | Does it create the indices when it deploys? |
41
+
42
+
43
+ ## 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
50
+
51
+
52
+ ## Development
53
+ > You can start to develop on it
54
+ >
55
+ ### Step 1
56
+ - [Go to project folder](https://github.com/samet-digital/help/blob/main/go-to-project-folder.MD)
57
+
58
+ ### Step 2
59
+ - `EN`: Clone the project
60
+ - `TR`: Projeyi bilgisiyarına çek
61
+ ```shell
62
+ git clone https://github.com/samet-digital/be-couchbase-common.git -b development
63
+ ```
64
+
65
+ ## Dependencies
66
+ - `@samet-it/be-base-common`: **samet** base common
67
+ - `@leyyo/*`: leyyo utilities
68
+ - `@nestjs/*`: nestjs framework
69
+ - `couchbase`: couchbase client
70
+
71
+ ## Commands
72
+ - [Component Commands](https://github.com/samet-digital/help/blob/main/commands-component.MD)
73
+
74
+ ## Standards
75
+ ```diff
76
+ + language: TS
77
+ + lint: eslint
78
+ + inspections: intelli-j code inspections
79
+ + ddd: domain driven development
80
+ + edd: exception driven development
81
+ ! tdd: test driven development
82
+ + ldd: log driven development
83
+ + ddd: document driven development
84
+ ```
85
+
86
+ ## History
87
+ | Date | Developer | Info | Ticket |
88
+ |------------|----------------|--------------|----------------|
89
+ | 2025-08-13 | Mustafa Yelmer | _Created_ | ~~[none](./)~~ |
90
+ | 2026-01-11 | Mustafa Yelmer | _Refactored_ | ~~[none](./)~~ |
@@ -0,0 +1,2 @@
1
+ export declare class CbAdapterModule {
2
+ }
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ // ~~console.log(__filename);
3
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
4
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
5
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
6
+ 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;
7
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
8
+ };
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.CbAdapterModule = void 0;
11
+ const common_1 = require("@nestjs/common");
12
+ const cb_adapter_service_1 = require("./cb-adapter.service");
13
+ let CbAdapterModule = class CbAdapterModule {
14
+ };
15
+ exports.CbAdapterModule = CbAdapterModule;
16
+ exports.CbAdapterModule = CbAdapterModule = __decorate([
17
+ (0, common_1.Module)({
18
+ imports: [],
19
+ controllers: [],
20
+ providers: [cb_adapter_service_1.CbAdapterService],
21
+ exports: [cb_adapter_service_1.CbAdapterService],
22
+ })
23
+ ], CbAdapterModule);
@@ -0,0 +1,70 @@
1
+ import { type IgnoreFieldsByType, type ReplaceType } from "@leyyo/common";
2
+ import { type QueryOptions } from 'couchbase';
3
+ import { Cluster, Collection, QueryResult } from 'couchbase';
4
+ import type { CbAdapterServiceLike, CbEntity, CbExecOpt, CbExecRec } from "./index.types";
5
+ import type { CbRepoDef } from "../repo";
6
+ export declare class CbAdapterService implements CbAdapterServiceLike {
7
+ private readonly _CLEAR_ERROR_INTERVAL;
8
+ private logger;
9
+ private _connected;
10
+ private _undefined;
11
+ private _cluster;
12
+ private readonly _cbErrors;
13
+ private readonly _nativeErrors;
14
+ constructor();
15
+ /**
16
+ * Clear native errors
17
+ * */
18
+ private _clearErrors;
19
+ /**
20
+ * Ping to DB
21
+ * */
22
+ private _ping;
23
+ /**
24
+ * Execute the creation of index
25
+ * */
26
+ private _createIndex;
27
+ /**
28
+ * Build json format of CB object
29
+ * */
30
+ private _toJson;
31
+ /** {@inheritDoc} */
32
+ f(field: string): string;
33
+ /** {@inheritDoc} */
34
+ field(field: string): string;
35
+ s(value: string): string;
36
+ v(value: unknown): string;
37
+ value(value: unknown): string;
38
+ /** {@inheritDoc} */
39
+ string(value: string): string;
40
+ /** {@inheritDoc} */
41
+ flatten<T>(result: QueryResult<T>): Array<T>;
42
+ /** {@inheritDoc} */
43
+ rows<T>(rows: Array<T>): Array<T>;
44
+ /** {@inheritDoc} */
45
+ row<T>(row: T): T | undefined;
46
+ /** {@inheritDoc} */
47
+ first<T>(rows: Array<T>): T | undefined;
48
+ /** {@inheritDoc} */
49
+ checkError(p1: string | Error, p2?: Error): void;
50
+ /** {@inheritDoc} */
51
+ createIndex<T = Record<string, unknown>>(coll: Collection, p1: (keyof T | string) | Array<keyof T | string>, name?: string): Promise<void>;
52
+ /** {@inheritDoc} */
53
+ createBaseIndices(coll: Collection, ...keys: Array<keyof CbEntity>): Promise<void>;
54
+ /** {@inheritDoc} */
55
+ createPk(coll: Collection): Promise<void>;
56
+ /** {@inheritDoc} */
57
+ castDates<T>(given: ReplaceType<T, Date, string> | T, ...fields: Array<IgnoreFieldsByType<T, Date>>): void;
58
+ /** {@inheritDoc} */
59
+ castDatesForList<T>(given: Array<ReplaceType<T, Date, string> | T>, ...fields: Array<IgnoreFieldsByType<T, Date>>): void;
60
+ protected _checkError<R = any>(err: Error, op: string, opt: CbExecOpt): R;
61
+ exec2<T>(repo: CbRepoDef, sql: string, opt?: CbExecOpt): Promise<Array<T>>;
62
+ exec2First<T>(repo: CbRepoDef, sql: string, opt?: CbExecOpt): Promise<T | undefined>;
63
+ execExtended<T>(repo: CbRepoDef, sql: string, query: QueryOptions, opt?: CbExecOpt): Promise<Array<T>>;
64
+ execFirstExtended<T>(repo: CbRepoDef, sql: string, query: QueryOptions, opt?: CbExecOpt): Promise<T | undefined>;
65
+ exec1<T>(repo: CbRepoDef, fn: Promise<T>, opt?: CbExecOpt): Promise<T>;
66
+ /** {@inheritDoc} */
67
+ exec<T>(opt: CbExecRec<T>): Promise<T>;
68
+ /** {@inheritDoc} */
69
+ connectDb(): Promise<Cluster>;
70
+ }
@@ -0,0 +1,447 @@
1
+ "use strict";
2
+ // ~~console.log(__filename);
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
15
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
16
+ }) : function(o, v) {
17
+ o["default"] = v;
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
+ var __importStar = (this && this.__importStar) || (function () {
26
+ var ownKeys = function(o) {
27
+ ownKeys = Object.getOwnPropertyNames || function (o) {
28
+ var ar = [];
29
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
30
+ return ar;
31
+ };
32
+ return ownKeys(o);
33
+ };
34
+ return function (mod) {
35
+ if (mod && mod.__esModule) return mod;
36
+ var result = {};
37
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
38
+ __setModuleDefault(result, mod);
39
+ return result;
40
+ };
41
+ })();
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
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
46
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
47
+ return new (P || (P = Promise))(function (resolve, reject) {
48
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
49
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
50
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
51
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
52
+ });
53
+ };
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.CbAdapterService = void 0;
56
+ const couchbase = __importStar(require("couchbase"));
57
+ const common_1 = require("@nestjs/common");
58
+ const common_2 = require("@leyyo/common");
59
+ const couchbase_1 = require("couchbase");
60
+ const config_1 = require("../config");
61
+ // noinspection JSUnusedGlobalSymbols
62
+ let CbAdapterService = class CbAdapterService {
63
+ constructor() {
64
+ this._CLEAR_ERROR_INTERVAL = 1000 * 60 * 60 * 24; // daily
65
+ this._undefined = 0;
66
+ this._cbErrors = new Map();
67
+ this._nativeErrors = new Map();
68
+ this.logger = new common_1.Logger(this.constructor.name);
69
+ this._clearErrors();
70
+ this._cbErrors.set('AmbiguousTimeoutError', { count: 0, log: true, known: true });
71
+ this._cbErrors.set('AuthenticationFailureError', { count: 0, log: true, known: true });
72
+ this._cbErrors.set('ConnectionClosedError', { count: 0, log: true, known: true });
73
+ this._cbErrors.set('InternalServerFailureError', { count: 0, log: true, known: true });
74
+ this._cbErrors.set('ServiceNotAvailableError', { count: 0, log: true, known: true });
75
+ this._cbErrors.set('TimeoutError', { count: 0, log: true, known: true });
76
+ this._cbErrors.set('UnambiguousTimeoutError', { count: 0, log: true, known: true });
77
+ }
78
+ /**
79
+ * Clear native errors
80
+ * */
81
+ _clearErrors() {
82
+ this._nativeErrors.clear();
83
+ setTimeout(() => this._clearErrors(), this._CLEAR_ERROR_INTERVAL);
84
+ }
85
+ /**
86
+ * Ping to DB
87
+ * */
88
+ _ping() {
89
+ return __awaiter(this, void 0, void 0, function* () {
90
+ var _a;
91
+ try {
92
+ yield this.exec({
93
+ name: 'ping',
94
+ promise: this._cluster.ping()
95
+ });
96
+ }
97
+ catch (err) {
98
+ this.logger.error(`!ping[${(_a = err.name) !== null && _a !== void 0 ? _a : ''}]`, err);
99
+ }
100
+ setTimeout(() => this._ping(), 30000);
101
+ });
102
+ }
103
+ /**
104
+ * Execute the creation of index
105
+ * */
106
+ _createIndex(scope, sql) {
107
+ return __awaiter(this, void 0, void 0, function* () {
108
+ var _a;
109
+ try {
110
+ return yield scope.query(sql);
111
+ }
112
+ catch (e) {
113
+ if (e instanceof couchbase_1.IndexExistsError) {
114
+ return undefined;
115
+ }
116
+ this.logger.error(`!index[${(_a = e.name) !== null && _a !== void 0 ? _a : ''}] #${scope.name}] => ${sql}`, e);
117
+ // throw e; // TODO
118
+ }
119
+ });
120
+ }
121
+ /**
122
+ * Build json format of CB object
123
+ * */
124
+ _toJson(val) {
125
+ if ([undefined, null].includes(val)) {
126
+ return 'null';
127
+ }
128
+ switch (typeof val) {
129
+ case "string":
130
+ case "number":
131
+ case "bigint":
132
+ case "boolean":
133
+ return JSON.stringify(val);
134
+ case "object":
135
+ if (Array.isArray(val)) {
136
+ return '[' + val
137
+ .filter(v => v !== undefined)
138
+ .map(v => this._toJson(v))
139
+ .join(', ') + ']';
140
+ }
141
+ else if (val instanceof Map) {
142
+ return this._toJson(Object.fromEntries(val.entries()));
143
+ }
144
+ else if (val instanceof Set) {
145
+ return this._toJson(Array.from(val.values()));
146
+ }
147
+ else {
148
+ return '{' + Array.from(Object.entries(val))
149
+ .filter(item => item[1] !== undefined)
150
+ .map(item => {
151
+ const [k, v] = item;
152
+ return '`' + k + '`: ' + this._toJson(v);
153
+ }).join(', ') + '}';
154
+ }
155
+ case "symbol":
156
+ return JSON.stringify(val.description);
157
+ case "function":
158
+ case "undefined":
159
+ return 'null';
160
+ }
161
+ }
162
+ /** {@inheritDoc} */
163
+ f(field) {
164
+ if (field.includes('.')) {
165
+ return field.split('.').map(part => this.f(part)).join('.');
166
+ }
167
+ else if (field.startsWith('`')) {
168
+ return field;
169
+ }
170
+ return `\`${field}\``;
171
+ }
172
+ /** {@inheritDoc} */
173
+ field(field) {
174
+ return this.f(field);
175
+ }
176
+ s(value) {
177
+ if (typeof value === 'string') {
178
+ return value.includes('"') ? this._toJson(value) : `"${value}"`;
179
+ }
180
+ return this._toJson(value);
181
+ }
182
+ v(value) {
183
+ return this._toJson(value);
184
+ }
185
+ value(value) {
186
+ return this._toJson(value);
187
+ }
188
+ /** {@inheritDoc} */
189
+ string(value) {
190
+ return this.s(value);
191
+ }
192
+ /** {@inheritDoc} */
193
+ flatten(result) {
194
+ if (result && Array.isArray(result.rows) && (result.rows.length > 0)) {
195
+ return result.rows;
196
+ }
197
+ return [];
198
+ }
199
+ /** {@inheritDoc} */
200
+ rows(rows) {
201
+ if (rows && Array.isArray(rows) && (rows.length > 0)) {
202
+ return rows.filter(row => row['_trashId'] === undefined);
203
+ }
204
+ return [];
205
+ }
206
+ /** {@inheritDoc} */
207
+ row(row) {
208
+ if (row && row['_trashId'] === undefined) {
209
+ return row;
210
+ }
211
+ return undefined;
212
+ }
213
+ /** {@inheritDoc} */
214
+ first(rows) {
215
+ if (rows && Array.isArray(rows) && (rows.length > 0)) {
216
+ return rows[0];
217
+ }
218
+ return undefined;
219
+ }
220
+ /** {@inheritDoc} */
221
+ checkError(p1, p2) {
222
+ var _a;
223
+ let op;
224
+ let err;
225
+ if (typeof p1 === 'string') {
226
+ p1 = p1.trim();
227
+ op = p1 ? `(${p1})` : '';
228
+ err = p2;
229
+ }
230
+ else {
231
+ op = '';
232
+ err = p1;
233
+ }
234
+ const name = (_a = err === null || err === void 0 ? void 0 : err.constructor) === null || _a === void 0 ? void 0 : _a.name;
235
+ if (name) {
236
+ if (!this._cbErrors.has(name)) {
237
+ this.logger.warn(`!first[${name}] #${op} [1]`, err);
238
+ this._cbErrors.set(name, { count: 1, log: true });
239
+ }
240
+ else {
241
+ const obj = this._cbErrors.get(name);
242
+ obj.count++;
243
+ if (obj.known) {
244
+ this.logger.error(`!known[${name}] #${op} [${obj.count}]`, err);
245
+ }
246
+ else {
247
+ this.logger.warn(`!unknown[${name}] #${op} [${obj.count}]`, err);
248
+ }
249
+ }
250
+ }
251
+ else {
252
+ this._undefined++;
253
+ this.logger.warn(`!undefined[] #${op} [${this._undefined}]`, err);
254
+ }
255
+ }
256
+ /** {@inheritDoc} */
257
+ createIndex(coll, p1, name) {
258
+ return __awaiter(this, void 0, void 0, function* () {
259
+ if (Array.isArray(p1)) {
260
+ const fields = p1.map(f => f.split('.').map(part => '`' + part + '`').join('.'));
261
+ name = name.split('.').join('_').split('-').join('_');
262
+ if (!name.startsWith('idx_')) {
263
+ name = 'idx_' + name;
264
+ }
265
+ yield this._createIndex(coll.scope, `CREATE INDEX \`${name}\` ON \`${coll.name}\` (${fields.join(', ')})`);
266
+ }
267
+ else {
268
+ const field = p1;
269
+ if (!name) {
270
+ name = 'idx_' + field.split('.').join('_').split('-').join('_');
271
+ }
272
+ else if (!name.startsWith('idx_')) {
273
+ name = 'idx_' + name;
274
+ }
275
+ yield this._createIndex(coll.scope, `CREATE INDEX \`${name}\` ON \`${coll.name}\` (${field.split('.').map(part => '`' + part + '`').join('.')})`);
276
+ }
277
+ });
278
+ }
279
+ /** {@inheritDoc} */
280
+ createBaseIndices(coll, ...keys) {
281
+ return __awaiter(this, void 0, void 0, function* () {
282
+ if (keys.includes('id')) {
283
+ yield this.createIndex(coll, 'id');
284
+ }
285
+ if (keys.includes('createdAt')) {
286
+ yield this.createIndex(coll, 'createdAt');
287
+ }
288
+ if (keys.includes('updatedAt')) {
289
+ yield this.createIndex(coll, 'updatedAt');
290
+ }
291
+ if (keys.includes('_trashId')) {
292
+ yield this.createIndex(coll, '_trashId', 'trashId');
293
+ }
294
+ if (keys.includes('_urn')) {
295
+ yield this.createIndex(coll, '_urn', 'urn');
296
+ }
297
+ });
298
+ }
299
+ /** {@inheritDoc} */
300
+ createPk(coll) {
301
+ return __awaiter(this, void 0, void 0, function* () {
302
+ yield this._createIndex(coll.scope, `CREATE PRIMARY INDEX \`pk\` ON \`${coll.name}\``);
303
+ });
304
+ }
305
+ /** {@inheritDoc} */
306
+ castDates(given, ...fields) {
307
+ if (fields.length < 1) {
308
+ return;
309
+ }
310
+ if (!given || typeof given !== 'object' && Array.isArray(given)) {
311
+ return;
312
+ }
313
+ const doc = given;
314
+ fields.forEach(field => {
315
+ const val = doc[field];
316
+ if (typeof val === 'string' || (typeof val === 'number' && val > 0 && Number.isInteger(val))) {
317
+ doc[field] = new Date(val);
318
+ }
319
+ });
320
+ }
321
+ /** {@inheritDoc} */
322
+ castDatesForList(given, ...fields) {
323
+ if (fields.length < 1) {
324
+ return;
325
+ }
326
+ if (!given || !Array.isArray(given) || given.length < 1) {
327
+ return;
328
+ }
329
+ const arr = given;
330
+ arr.forEach(item => this.castDates(item, ...fields));
331
+ }
332
+ _checkError(err, op, opt) {
333
+ var _a;
334
+ if (!this._nativeErrors.has(err)) {
335
+ this._nativeErrors.set(err, 1);
336
+ }
337
+ else {
338
+ this._nativeErrors.set(err, this._nativeErrors.get(err) + 1);
339
+ }
340
+ if ((_a = opt === null || opt === void 0 ? void 0 : opt.ignoredErrors) === null || _a === void 0 ? void 0 : _a.includes(err)) {
341
+ return undefined;
342
+ }
343
+ this.logger.error(`${op}${err.message}`, err);
344
+ throw err;
345
+ }
346
+ exec2(repo, sql, opt) {
347
+ return __awaiter(this, void 0, void 0, function* () {
348
+ return this.execExtended(repo, sql, undefined, opt);
349
+ });
350
+ }
351
+ exec2First(repo, sql, opt) {
352
+ return __awaiter(this, void 0, void 0, function* () {
353
+ return this.first(yield this.exec2(repo, sql, opt));
354
+ });
355
+ }
356
+ execExtended(repo, sql, query, opt) {
357
+ return __awaiter(this, void 0, void 0, function* () {
358
+ const op = (opt === null || opt === void 0 ? void 0 : opt.name) ? `[${opt.name}]` : '';
359
+ if (opt === null || opt === void 0 ? void 0 : opt.printSql) {
360
+ this.logger.log(`${repo.path} > SQL${op}`, sql);
361
+ }
362
+ try {
363
+ return this.flatten(yield repo.scope.query(sql, query));
364
+ }
365
+ catch (err) {
366
+ return this._checkError(err, op, opt);
367
+ }
368
+ });
369
+ }
370
+ execFirstExtended(repo, sql, query, opt) {
371
+ return __awaiter(this, void 0, void 0, function* () {
372
+ return this.first(yield this.execExtended(repo, sql, query, opt));
373
+ });
374
+ }
375
+ exec1(repo, fn, opt) {
376
+ return __awaiter(this, void 0, void 0, function* () {
377
+ const op = (opt === null || opt === void 0 ? void 0 : opt.name) ? `[${opt.name}]` : '';
378
+ common_2.$assert.object(fn, () => {
379
+ return { field: 'fn', where: 'CbAdapterService', path: repo.path, op: op };
380
+ });
381
+ common_2.$assert.func(fn.then, () => {
382
+ return { field: 'fn.then', where: 'CbAdapterService', path: repo.path, op: op };
383
+ });
384
+ try {
385
+ return yield fn;
386
+ }
387
+ catch (err) {
388
+ return this._checkError(err, op, opt);
389
+ }
390
+ });
391
+ }
392
+ /** {@inheritDoc} */
393
+ exec(opt) {
394
+ return __awaiter(this, void 0, void 0, function* () {
395
+ if (!common_2.$is.bareObject(opt) || !common_2.$is.object(opt.promise) || !common_2.$is.func(opt.promise.then)) {
396
+ throw new Error(`Invalid exec options [${typeof opt}, ${typeof (opt === null || opt === void 0 ? void 0 : opt.promise)}]`);
397
+ }
398
+ try {
399
+ return yield opt.promise;
400
+ }
401
+ catch (err) {
402
+ const e = err;
403
+ if (!this._nativeErrors.has(e)) {
404
+ this._nativeErrors.set(e, 1);
405
+ }
406
+ else {
407
+ this._nativeErrors.set(e, this._nativeErrors.get(e) + 1);
408
+ }
409
+ if (Array.isArray(opt.ignoredErrors) && opt.ignoredErrors.includes(e)) {
410
+ return undefined;
411
+ }
412
+ const op = opt.name ? `[${opt.name}] ` : '';
413
+ this.logger.error(`${op}${err.message}`, err);
414
+ throw err;
415
+ }
416
+ });
417
+ }
418
+ /** {@inheritDoc} */
419
+ connectDb() {
420
+ return __awaiter(this, void 0, void 0, function* () {
421
+ var _a;
422
+ if (this._connected) {
423
+ return this._cluster;
424
+ }
425
+ const opt = config_1.couchbaseCommonConfig.raw;
426
+ try {
427
+ this._cluster = yield couchbase.connect(`couchbase://${opt.CB_HOST}`, {
428
+ username: opt.CB_USER,
429
+ password: opt.CB_PASS,
430
+ });
431
+ this._connected = true;
432
+ this.logger.log('Connected');
433
+ setTimeout(() => this._ping(), 30000);
434
+ return this._cluster;
435
+ }
436
+ catch (e) {
437
+ this.logger.error(`!connection[${(_a = e.name) !== null && _a !== void 0 ? _a : ''}]`, e);
438
+ throw e;
439
+ }
440
+ });
441
+ }
442
+ };
443
+ exports.CbAdapterService = CbAdapterService;
444
+ exports.CbAdapterService = CbAdapterService = __decorate([
445
+ (0, common_1.Injectable)(),
446
+ __metadata("design:paramtypes", [])
447
+ ], CbAdapterService);
@@ -0,0 +1,3 @@
1
+ export * from './index.types';
2
+ export * from './cb-adapter.service';
3
+ export * from './cb-adapter.module';
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./index.types"), exports);
18
+ __exportStar(require("./cb-adapter.service"), exports);
19
+ __exportStar(require("./cb-adapter.module"), exports);