@naturalcycles/db-lib 8.35.0 → 8.36.0

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.
@@ -5,7 +5,7 @@ import { BaseCommonDB } from '../../base.common.db';
5
5
  import { CommonDB } from '../../common.db';
6
6
  import { RunQueryResult } from '../../db.model';
7
7
  import { DBQuery } from '../../query/dbQuery';
8
- import { CacheDBCfg, CacheDBCreateOptions, CacheDBOptions, CacheDBStreamOptions } from './cache.db.model';
8
+ import { CacheDBCfg, CacheDBCreateOptions, CacheDBOptions, CacheDBSaveOptions, CacheDBStreamOptions } from './cache.db.model';
9
9
  /**
10
10
  * CommonDB implementation that proxies requests to downstream CommonDB
11
11
  * and does in-memory caching.
@@ -21,12 +21,12 @@ export declare class CacheDB extends BaseCommonDB implements CommonDB {
21
21
  */
22
22
  getTables(): Promise<string[]>;
23
23
  getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaRootObject<ROW>>;
24
- createTable<ROW extends ObjectWithId>(table: string, schema: JsonSchemaObject<ROW>, opt?: CacheDBCreateOptions<ROW>): Promise<void>;
25
- getByIds<ROW extends ObjectWithId>(table: string, ids: string[], opt?: CacheDBOptions<ROW>): Promise<ROW[]>;
26
- deleteByIds<ROW extends ObjectWithId>(table: string, ids: string[], opt?: CacheDBOptions<ROW>): Promise<number>;
27
- saveBatch<ROW extends ObjectWithId>(table: string, rows: ROW[], opt?: CacheDBOptions<ROW>): Promise<void>;
28
- runQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CacheDBOptions<ROW>): Promise<RunQueryResult<ROW>>;
29
- runQueryCount<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CacheDBOptions<ROW>): Promise<number>;
30
- streamQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CacheDBStreamOptions<ROW>): Readable;
31
- deleteByQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CacheDBOptions<ROW>): Promise<number>;
24
+ createTable<ROW extends ObjectWithId>(table: string, schema: JsonSchemaObject<ROW>, opt?: CacheDBCreateOptions): Promise<void>;
25
+ getByIds<ROW extends ObjectWithId>(table: string, ids: ROW['id'][], opt?: CacheDBSaveOptions<ROW>): Promise<ROW[]>;
26
+ deleteByIds<ROW extends ObjectWithId>(table: string, ids: ROW['id'][], opt?: CacheDBOptions): Promise<number>;
27
+ saveBatch<ROW extends ObjectWithId>(table: string, rows: ROW[], opt?: CacheDBSaveOptions<ROW>): Promise<void>;
28
+ runQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CacheDBSaveOptions<ROW>): Promise<RunQueryResult<ROW>>;
29
+ runQueryCount<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CacheDBOptions): Promise<number>;
30
+ streamQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CacheDBStreamOptions): Readable;
31
+ deleteByQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CacheDBOptions): Promise<number>;
32
32
  }
@@ -81,7 +81,9 @@ class CacheDB extends base_common_db_1.BaseCommonDB {
81
81
  }
82
82
  }
83
83
  if (!opt.skipCache && !this.cfg.skipCache) {
84
- const cacheResult = this.cfg.cacheDB.deleteByIds(table, ids, opt).then(deletedFromCache => {
84
+ const cacheResult = this.cfg.cacheDB
85
+ .deleteByIds(table, ids, opt)
86
+ .then(deletedFromCache => {
85
87
  if (this.cfg.logCached) {
86
88
  this.cfg.logger?.log(`${table}.deleteByIds ${deletedFromCache} rows from cache`);
87
89
  }
@@ -37,7 +37,7 @@ export interface CacheDBCfg {
37
37
  */
38
38
  logger?: CommonLogger;
39
39
  }
40
- export interface CacheDBOptions<ROW extends ObjectWithId> extends CommonDBSaveOptions<ROW> {
40
+ export interface CacheDBOptions {
41
41
  /**
42
42
  * @default false
43
43
  */
@@ -47,7 +47,9 @@ export interface CacheDBOptions<ROW extends ObjectWithId> extends CommonDBSaveOp
47
47
  */
48
48
  onlyCache?: boolean;
49
49
  }
50
- export interface CacheDBStreamOptions<ROW extends ObjectWithId> extends CacheDBOptions<ROW>, CommonDBStreamOptions {
50
+ export interface CacheDBSaveOptions<ROW extends ObjectWithId> extends CacheDBOptions, CommonDBSaveOptions<ROW> {
51
51
  }
52
- export interface CacheDBCreateOptions<ROW extends ObjectWithId> extends CacheDBOptions<ROW>, CommonDBCreateOptions {
52
+ export interface CacheDBStreamOptions extends CacheDBOptions, CommonDBStreamOptions {
53
+ }
54
+ export interface CacheDBCreateOptions extends CacheDBOptions, CommonDBCreateOptions {
53
55
  }
@@ -21,7 +21,7 @@ export declare class FileDB extends BaseCommonDB implements CommonDB {
21
21
  cfg: FileDBCfg;
22
22
  ping(): Promise<void>;
23
23
  getTables(): Promise<string[]>;
24
- getByIds<ROW extends ObjectWithId>(table: string, ids: string[], _opt?: CommonDBOptions): Promise<ROW[]>;
24
+ getByIds<ROW extends ObjectWithId>(table: string, ids: ROW['id'][], _opt?: CommonDBOptions): Promise<ROW[]>;
25
25
  saveBatch<ROW extends ObjectWithId>(table: string, rows: ROW[], _opt?: CommonDBSaveOptions<ROW>): Promise<void>;
26
26
  /**
27
27
  * Implementation is optimized for loading/saving _whole files_.
@@ -30,7 +30,7 @@ export declare class FileDB extends BaseCommonDB implements CommonDB {
30
30
  runQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<RunQueryResult<ROW>>;
31
31
  runQueryCount<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<number>;
32
32
  streamQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CommonDBStreamOptions): ReadableTyped<ROW>;
33
- deleteByIds<ROW extends ObjectWithId>(table: string, ids: string[], _opt?: CommonDBOptions): Promise<number>;
33
+ deleteByIds<ROW extends ObjectWithId>(table: string, ids: ROW['id'][], _opt?: CommonDBOptions): Promise<number>;
34
34
  deleteByQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<number>;
35
35
  getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaRootObject<ROW>>;
36
36
  loadFile<ROW extends ObjectWithId>(table: string): Promise<ROW[]>;
@@ -52,9 +52,9 @@ export declare class InMemoryDB implements CommonDB {
52
52
  getTables(): Promise<string[]>;
53
53
  getTableSchema<ROW extends ObjectWithId>(_table: string): Promise<JsonSchemaRootObject<ROW>>;
54
54
  createTable<ROW extends ObjectWithId>(_table: string, _schema: JsonSchemaObject<ROW>, opt?: CommonDBCreateOptions): Promise<void>;
55
- getByIds<ROW extends ObjectWithId>(_table: string, ids: string[], _opt?: CommonDBOptions): Promise<ROW[]>;
55
+ getByIds<ROW extends ObjectWithId>(_table: string, ids: ROW['id'][], _opt?: CommonDBOptions): Promise<ROW[]>;
56
56
  saveBatch<ROW extends ObjectWithId>(_table: string, rows: ROW[], _opt?: CommonDBSaveOptions<ROW>): Promise<void>;
57
- deleteByIds(_table: string, ids: string[], _opt?: CommonDBOptions): Promise<number>;
57
+ deleteByIds<ROW extends ObjectWithId>(_table: string, ids: ROW['id'][], _opt?: CommonDBOptions): Promise<number>;
58
58
  deleteByQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<number>;
59
59
  runQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<RunQueryResult<ROW>>;
60
60
  runQueryCount<ROW extends ObjectWithId>(q: DBQuery<ROW>, _opt?: CommonDBOptions): Promise<number>;
@@ -58,22 +58,25 @@ class InMemoryDB {
58
58
  };
59
59
  }
60
60
  async createTable(_table, _schema, opt = {}) {
61
+ var _a;
61
62
  const table = this.cfg.tablesPrefix + _table;
62
63
  if (opt.dropIfExists) {
63
64
  this.data[table] = {};
64
65
  }
65
66
  else {
66
- this.data[table] = this.data[table] || {};
67
+ (_a = this.data)[table] || (_a[table] = {});
67
68
  }
68
69
  }
69
70
  async getByIds(_table, ids, _opt) {
71
+ var _a;
70
72
  const table = this.cfg.tablesPrefix + _table;
71
- this.data[table] = this.data[table] || {};
73
+ (_a = this.data)[table] || (_a[table] = {});
72
74
  return ids.map(id => this.data[table][id]).filter(Boolean);
73
75
  }
74
76
  async saveBatch(_table, rows, _opt) {
77
+ var _a;
75
78
  const table = this.cfg.tablesPrefix + _table;
76
- this.data[table] = this.data[table] || {};
79
+ (_a = this.data)[table] || (_a[table] = {});
77
80
  rows.forEach(r => {
78
81
  if (!r.id) {
79
82
  this.cfg.logger?.warn({ rows });
@@ -13,9 +13,9 @@ export declare class BaseCommonDB implements CommonDB {
13
13
  getTables(): Promise<string[]>;
14
14
  getTableSchema<ROW extends ObjectWithId>(table: string): Promise<JsonSchemaRootObject<ROW>>;
15
15
  createTable<ROW extends ObjectWithId>(_table: string, _schema: JsonSchemaObject<ROW>): Promise<void>;
16
- deleteByIds(_table: string, _ids: string[]): Promise<number>;
16
+ deleteByIds<ROW extends ObjectWithId>(_table: string, _ids: ROW['id'][]): Promise<number>;
17
17
  deleteByQuery<ROW extends ObjectWithId>(_q: DBQuery<ROW>): Promise<number>;
18
- getByIds<ROW extends ObjectWithId>(_table: string, _ids: string[]): Promise<ROW[]>;
18
+ getByIds<ROW extends ObjectWithId>(_table: string, _ids: ROW['id'][]): Promise<ROW[]>;
19
19
  runQuery<ROW extends ObjectWithId>(_q: DBQuery<ROW>): Promise<RunQueryResult<ROW>>;
20
20
  runQueryCount<ROW extends ObjectWithId>(_q: DBQuery<ROW>): Promise<number>;
21
21
  saveBatch<ROW extends ObjectWithId>(_table: string, _rows: ROW[], _opt?: CommonDBSaveOptions<ROW>): Promise<void>;
@@ -31,7 +31,7 @@ export interface CommonDB {
31
31
  * Order of items returned is not guaranteed to match order of ids.
32
32
  * (Such limitation exists because Datastore doesn't support it).
33
33
  */
34
- getByIds<ROW extends ObjectWithId>(table: string, ids: string[], opt?: CommonDBOptions): Promise<ROW[]>;
34
+ getByIds<ROW extends ObjectWithId>(table: string, ids: ROW['id'][], opt?: CommonDBOptions): Promise<ROW[]>;
35
35
  /**
36
36
  * Order by 'id' is not supported by all implementations (for example, Datastore doesn't support it).
37
37
  */
@@ -40,10 +40,10 @@ export interface CommonDB {
40
40
  streamQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CommonDBStreamOptions): ReadableTyped<ROW>;
41
41
  saveBatch<ROW extends ObjectWithId>(table: string, rows: ROW[], opt?: CommonDBSaveOptions<ROW>): Promise<void>;
42
42
  /**
43
- * @returns number of deleted items.
43
+ * Returns number of deleted items.
44
44
  * Not supported by all implementations (e.g Datastore will always return same number as number of ids).
45
45
  */
46
- deleteByIds(table: string, ids: string[], opt?: CommonDBOptions): Promise<number>;
46
+ deleteByIds<ROW extends ObjectWithId>(table: string, ids: ROW['id'][], opt?: CommonDBOptions): Promise<number>;
47
47
  deleteByQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: CommonDBOptions): Promise<number>;
48
48
  /**
49
49
  * Should be implemented as a Transaction (best effort), which means that
@@ -10,22 +10,22 @@ import { CommonDaoCfg, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoSaveOp
10
10
  * BM = Backend model (optimized for API access)
11
11
  * TM = Transport model (optimized to be sent over the wire)
12
12
  */
13
- export declare class CommonDao<BM extends Partial<ObjectWithId>, DBM extends ObjectWithId = Saved<BM>, TM = BM> {
14
- cfg: CommonDaoCfg<BM, DBM, TM>;
15
- constructor(cfg: CommonDaoCfg<BM, DBM, TM>);
13
+ export declare class CommonDao<BM extends Partial<ObjectWithId<ID>>, DBM extends ObjectWithId<ID> = Saved<BM>, TM = BM, ID extends string | number = DBM['id']> {
14
+ cfg: CommonDaoCfg<BM, DBM, TM, ID>;
15
+ constructor(cfg: CommonDaoCfg<BM, DBM, TM, ID>);
16
16
  create(part?: Partial<BM>, opt?: CommonDaoOptions): Saved<BM>;
17
17
  getById(id: undefined, opt?: CommonDaoOptions): Promise<null>;
18
- getById(id?: string, opt?: CommonDaoOptions): Promise<Saved<BM> | null>;
19
- getByIdOrEmpty(id: string, part?: Partial<BM>, opt?: CommonDaoOptions): Promise<Saved<BM>>;
20
- getByIdAsDBMOrEmpty(id: string, part?: Partial<BM>, opt?: CommonDaoOptions): Promise<DBM>;
18
+ getById(id?: ID, opt?: CommonDaoOptions): Promise<Saved<BM> | null>;
19
+ getByIdOrEmpty(id: ID, part?: Partial<BM>, opt?: CommonDaoOptions): Promise<Saved<BM>>;
20
+ getByIdAsDBMOrEmpty(id: ID, part?: Partial<BM>, opt?: CommonDaoOptions): Promise<DBM>;
21
21
  getByIdAsDBM(id: undefined, opt?: CommonDaoOptions): Promise<null>;
22
- getByIdAsDBM(id?: string, opt?: CommonDaoOptions): Promise<DBM | null>;
22
+ getByIdAsDBM(id?: ID, opt?: CommonDaoOptions): Promise<DBM | null>;
23
23
  getByIdAsTM(id: undefined, opt?: CommonDaoOptions): Promise<null>;
24
- getByIdAsTM(id?: string, opt?: CommonDaoOptions): Promise<TM | null>;
25
- getByIds(ids: string[], opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
26
- getByIdsAsDBM(ids: string[], opt?: CommonDaoOptions): Promise<DBM[]>;
27
- requireById(id: string, opt?: CommonDaoOptions): Promise<Saved<BM>>;
28
- requireByIdAsDBM(id: string, opt?: CommonDaoOptions): Promise<DBM>;
24
+ getByIdAsTM(id?: ID, opt?: CommonDaoOptions): Promise<TM | null>;
25
+ getByIds(ids: ID[], opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
26
+ getByIdsAsDBM(ids: ID[], opt?: CommonDaoOptions): Promise<DBM[]>;
27
+ requireById(id: ID, opt?: CommonDaoOptions): Promise<Saved<BM>>;
28
+ requireByIdAsDBM(id: ID, opt?: CommonDaoOptions): Promise<DBM>;
29
29
  private throwRequiredError;
30
30
  /**
31
31
  * Throws if readOnly is true
@@ -41,7 +41,7 @@ export declare class CommonDao<BM extends Partial<ObjectWithId>, DBM extends Obj
41
41
  /**
42
42
  * Pass `table` to override table
43
43
  */
44
- query(table?: string): RunnableDBQuery<BM, DBM, TM>;
44
+ query(table?: string): RunnableDBQuery<BM, DBM, TM, ID>;
45
45
  runQuery(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
46
46
  runQuerySingleColumn<T = any>(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<T[]>;
47
47
  /**
@@ -72,9 +72,9 @@ export declare class CommonDao<BM extends Partial<ObjectWithId>, DBM extends Obj
72
72
  * You can do `.pipe(transformNoOp)` to make it "valid again".
73
73
  */
74
74
  streamQuery(q: DBQuery<DBM>, opt?: CommonDaoStreamOptions): ReadableTyped<Saved<BM>>;
75
- queryIds(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<string[]>;
76
- streamQueryIds(q: DBQuery<DBM>, opt?: CommonDaoStreamOptions): ReadableTyped<string>;
77
- streamQueryIdsForEach(q: DBQuery<DBM>, mapper: AsyncMapper<string, void>, opt?: CommonDaoStreamForEachOptions<string>): Promise<void>;
75
+ queryIds(q: DBQuery<DBM>, opt?: CommonDaoOptions): Promise<ID[]>;
76
+ streamQueryIds(q: DBQuery<DBM>, opt?: CommonDaoStreamOptions): ReadableTyped<ID>;
77
+ streamQueryIdsForEach(q: DBQuery<DBM>, mapper: AsyncMapper<ID, void>, opt?: CommonDaoStreamForEachOptions<ID>): Promise<void>;
78
78
  /**
79
79
  * Mutates!
80
80
  * "Returns", just to have a type of "Saved"
@@ -96,8 +96,8 @@ export declare class CommonDao<BM extends Partial<ObjectWithId>, DBM extends Obj
96
96
  *
97
97
  * Convenience method to replace 3 operations (loading+patching+saving) with one.
98
98
  */
99
- patch(id: string, patch: Partial<BM>, opt?: CommonDaoSaveOptions<DBM>): Promise<Saved<BM>>;
100
- patchAsDBM(id: string, patch: Partial<DBM>, opt?: CommonDaoSaveOptions<DBM>): Promise<DBM>;
99
+ patch(id: ID, patch: Partial<BM>, opt?: CommonDaoSaveOptions<DBM>): Promise<Saved<BM>>;
100
+ patchAsDBM(id: ID, patch: Partial<DBM>, opt?: CommonDaoSaveOptions<DBM>): Promise<DBM>;
101
101
  saveAsDBM(dbm: DBM, opt?: CommonDaoSaveOptions<DBM>): Promise<DBM>;
102
102
  saveBatch(bms: BM[], opt?: CommonDaoSaveOptions<DBM>): Promise<Saved<BM>[]>;
103
103
  saveBatchAsDBM(dbms: DBM[], opt?: CommonDaoSaveOptions<DBM>): Promise<DBM[]>;
@@ -105,8 +105,8 @@ export declare class CommonDao<BM extends Partial<ObjectWithId>, DBM extends Obj
105
105
  * @returns number of deleted items
106
106
  */
107
107
  deleteById(id: undefined, opt?: CommonDaoOptions): Promise<0>;
108
- deleteById(id?: string, opt?: CommonDaoOptions): Promise<number>;
109
- deleteByIds(ids: string[], opt?: CommonDaoOptions): Promise<number>;
108
+ deleteById(id?: ID, opt?: CommonDaoOptions): Promise<number>;
109
+ deleteByIds(ids: ID[], opt?: CommonDaoOptions): Promise<number>;
110
110
  /**
111
111
  * Pass `stream: true` option to use Streaming: it will Stream the query, batch by 500, and execute
112
112
  * `deleteByIds` for each batch concurrently (infinite concurrency).
@@ -19,18 +19,20 @@ const isCI = !!process.env['CI'];
19
19
  */
20
20
  class CommonDao {
21
21
  constructor(cfg) {
22
+ var _a;
22
23
  this.cfg = cfg;
23
24
  this.cfg = {
24
25
  // Default is to NOT log in AppEngine and in CI,
25
26
  // otherwise to log Operations
26
27
  // e.g in Dev (local machine), Test - it will log operations (useful for debugging)
27
28
  logLevel: isGAE || isCI ? common_dao_model_1.CommonDaoLogLevel.NONE : common_dao_model_1.CommonDaoLogLevel.OPERATIONS,
29
+ idType: 'string',
30
+ createId: true,
28
31
  created: true,
29
32
  updated: true,
30
33
  logger: console,
31
34
  ...cfg,
32
35
  hooks: {
33
- createId: () => (0, nodejs_lib_1.stringId)(),
34
36
  parseNaturalId: () => ({}),
35
37
  beforeCreate: bm => bm,
36
38
  beforeDBMValidate: dbm => dbm,
@@ -43,12 +45,18 @@ class CommonDao {
43
45
  ...cfg.hooks,
44
46
  },
45
47
  };
48
+ if (this.cfg.createId) {
49
+ (0, js_lib_1._assert)(this.cfg.idType === 'string', 'db-lib: automatic generation of non-string ids is not supported');
50
+ (_a = this.cfg.hooks).createId || (_a.createId = () => (0, nodejs_lib_1.stringId)());
51
+ }
52
+ else {
53
+ delete this.cfg.hooks.createId;
54
+ }
46
55
  }
47
56
  // CREATE
48
57
  create(part = {}, opt = {}) {
49
58
  let bm = this.cfg.hooks.beforeCreate(part);
50
59
  bm = this.validateAndConvert(bm, this.cfg.bmSchema, db_model_1.DBModelType.BM, opt);
51
- // If no SCHEMA - return as is
52
60
  return this.assignIdCreatedUpdated(bm, opt);
53
61
  }
54
62
  async getById(id, opt = {}) {
@@ -416,16 +424,12 @@ class CommonDao {
416
424
  }
417
425
  assignIdCreatedUpdated(obj, opt = {}) {
418
426
  const now = Math.floor(Date.now() / 1000);
419
- obj.id = obj.id || this.cfg.hooks.createId(obj);
427
+ obj.id || (obj.id = this.cfg.hooks.createId?.(obj));
420
428
  if (this.cfg.created) {
421
- Object.assign(obj, {
422
- created: obj.created || obj.updated || now,
423
- });
429
+ obj['created'] || (obj['created'] = obj['updated'] || now);
424
430
  }
425
431
  if (this.cfg.updated) {
426
- Object.assign(obj, {
427
- updated: opt.preserveUpdatedCreated && obj.updated ? obj.updated : now,
428
- });
432
+ obj['updated'] = opt.preserveUpdatedCreated && obj['updated'] ? obj['updated'] : now;
429
433
  }
430
434
  return obj;
431
435
  }
@@ -2,25 +2,16 @@ import { CommonLogger, ErrorMode, ObjectWithId, Saved } from '@naturalcycles/js-
2
2
  import { AjvSchema, AjvValidationError, JoiValidationError, ObjectSchemaTyped, TransformLogProgressOptions, TransformMapOptions } from '@naturalcycles/nodejs-lib';
3
3
  import { CommonDB } from '../common.db';
4
4
  import { CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions } from '../db.model';
5
- export declare type CommonDaoCreateIdHook<BM, DBM> = (obj: DBM | BM) => string;
6
- export declare type CommonDaoParseNaturalIdHook<DBM> = (id: string) => Partial<DBM>;
7
- export declare type CommonDaoBeforeCreateHook<BM> = (bm: Partial<BM>) => Partial<BM>;
8
- export declare type CommonDaoBeforeDBMValidateHook<DBM> = (dbm: Partial<DBM>) => Partial<DBM>;
9
- export declare type CommonDaoBeforeDBMToBMHook<BM, DBM> = (dbm: DBM) => Partial<BM> | Promise<Partial<BM>>;
10
- export declare type CommonDaoBeforeBMToDBMHook<BM, DBM> = (bm: BM) => Partial<DBM> | Promise<Partial<DBM>>;
11
- export declare type CommonDaoBeforeTMToBMHook<BM, TM> = (tm: TM) => Partial<BM>;
12
- export declare type CommonDaoBeforeBMToTMHook<BM, TM> = (bm: BM) => Partial<TM>;
13
- export declare type CommonDaoAnonymizeHook<DBM> = (dbm: DBM) => DBM;
14
- interface CommonDaoHooks<BM, DBM, TM> {
15
- createId: CommonDaoCreateIdHook<BM, DBM>;
16
- parseNaturalId: CommonDaoParseNaturalIdHook<DBM>;
17
- beforeCreate: CommonDaoBeforeCreateHook<BM>;
18
- beforeDBMValidate: CommonDaoBeforeDBMValidateHook<DBM>;
19
- beforeDBMToBM: CommonDaoBeforeDBMToBMHook<BM, DBM>;
20
- beforeBMToDBM: CommonDaoBeforeBMToDBMHook<BM, DBM>;
21
- beforeTMToBM: CommonDaoBeforeTMToBMHook<BM, TM>;
22
- beforeBMToTM: CommonDaoBeforeBMToTMHook<BM, TM>;
23
- anonymize: CommonDaoAnonymizeHook<DBM>;
5
+ export interface CommonDaoHooks<BM extends Partial<ObjectWithId<ID>>, DBM extends ObjectWithId<ID>, TM, ID extends string | number> {
6
+ createId: (obj: DBM | BM) => ID;
7
+ parseNaturalId: (id: ID) => Partial<DBM>;
8
+ beforeCreate: (bm: Partial<BM>) => Partial<BM>;
9
+ beforeDBMValidate: (dbm: Partial<DBM>) => Partial<DBM>;
10
+ beforeDBMToBM: (dbm: DBM) => Partial<BM> | Promise<Partial<BM>>;
11
+ beforeBMToDBM: (bm: BM) => Partial<DBM> | Promise<Partial<DBM>>;
12
+ beforeTMToBM: (tm: TM) => Partial<BM>;
13
+ beforeBMToTM: (bm: BM) => Partial<TM>;
14
+ anonymize: (dbm: DBM) => DBM;
24
15
  /**
25
16
  * If hook is defined - allows to prevent or modify the error thrown.
26
17
  * Return `false` to prevent throwing an error.
@@ -47,7 +38,7 @@ export declare enum CommonDaoLogLevel {
47
38
  */
48
39
  DATA_FULL = 30
49
40
  }
50
- export interface CommonDaoCfg<BM extends Partial<ObjectWithId>, DBM extends ObjectWithId = Saved<BM>, TM = BM> {
41
+ export interface CommonDaoCfg<BM extends Partial<ObjectWithId<ID>>, DBM extends ObjectWithId<ID> = Saved<BM>, TM = BM, ID extends string | number = DBM['id']> {
51
42
  db: CommonDB;
52
43
  table: string;
53
44
  /**
@@ -83,7 +74,17 @@ export interface CommonDaoCfg<BM extends Partial<ObjectWithId>, DBM extends Obje
83
74
  * @default false
84
75
  */
85
76
  logStarted?: boolean;
86
- hooks?: Partial<CommonDaoHooks<BM, DBM, TM>>;
77
+ hooks?: Partial<CommonDaoHooks<BM, DBM, TM, ID>>;
78
+ /**
79
+ * Defaults to 'string'
80
+ */
81
+ idType?: 'string' | 'number';
82
+ /**
83
+ * Defaults to true.
84
+ * Set to false to disable auto-generation of `id`.
85
+ * Useful e.g when your DB is generating ids by itself (e.g mysql auto_increment).
86
+ */
87
+ createId?: boolean;
87
88
  /**
88
89
  * Defaults to true
89
90
  * Set to false to disable `created` field management.
@@ -194,4 +195,3 @@ export interface CommonDaoStreamOptions extends CommonDaoOptions {
194
195
  errorMode?: ErrorMode;
195
196
  }
196
197
  export declare type CommonDaoCreateOptions = CommonDBCreateOptions;
197
- export {};
@@ -1,5 +1,4 @@
1
1
  import { AnyObjectWithId, ObjectWithId } from '@naturalcycles/js-lib';
2
- import { CommonDB } from './common.db';
3
2
  export interface CommonDBOptions {
4
3
  }
5
4
  /**
@@ -11,8 +10,9 @@ export interface CommonDBSaveOptions<ROW extends ObjectWithId = AnyObjectWithId>
11
10
  export declare type CommonDBStreamOptions = CommonDBOptions;
12
11
  export interface CommonDBCreateOptions extends CommonDBOptions {
13
12
  /**
14
- * @default false
15
13
  * Caution! If set to true - will actually DROP the table!
14
+ *
15
+ * @default false
16
16
  */
17
17
  dropIfExists?: boolean;
18
18
  }
@@ -40,18 +40,3 @@ export declare enum DBModelType {
40
40
  BM = "BM",
41
41
  TM = "TM"
42
42
  }
43
- /**
44
- * Interface for a module (lib) that implements CommonDB.
45
- *
46
- * Example:
47
- *
48
- * const lib: CommonDBModule = require('mysql-lib')
49
- * const db = lib.getDB()
50
- */
51
- export interface CommonDBAdapter {
52
- /**
53
- * @param cfg was read from SECRET_DB${i} by secret('SECRET_DB${i}') method and passed there.
54
- * It's a string that can contain e.g JSON.stringified configuration object (depends on the adapter).
55
- */
56
- getDBAdapter(cfg?: string): CommonDB;
57
- }
package/dist/index.d.ts CHANGED
@@ -5,8 +5,8 @@ import { BaseCommonDB } from './base.common.db';
5
5
  import { DBLibError } from './cnst';
6
6
  import { CommonDB } from './common.db';
7
7
  import { CommonDao } from './commondao/common.dao';
8
- import { CommonDaoAnonymizeHook, CommonDaoBeforeBMToDBMHook, CommonDaoBeforeBMToTMHook, CommonDaoBeforeCreateHook, CommonDaoBeforeDBMToBMHook, CommonDaoBeforeDBMValidateHook, CommonDaoBeforeTMToBMHook, CommonDaoCfg, CommonDaoCreateIdHook, CommonDaoCreateOptions, CommonDaoLogLevel, CommonDaoOptions, CommonDaoParseNaturalIdHook, CommonDaoSaveOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions } from './commondao/common.dao.model';
9
- import { CommonDBAdapter, CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions, CommonDBStreamOptions, DBDeleteByIdsOperation, DBModelType, DBOperation, DBRelation, DBSaveBatchOperation, RunQueryResult } from './db.model';
8
+ import { CommonDaoCfg, CommonDaoCreateOptions, CommonDaoLogLevel, CommonDaoOptions, CommonDaoSaveOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions, CommonDaoHooks } from './commondao/common.dao.model';
9
+ import { CommonDBCreateOptions, CommonDBOptions, CommonDBSaveOptions, CommonDBStreamOptions, DBDeleteByIdsOperation, DBModelType, DBOperation, DBRelation, DBSaveBatchOperation, RunQueryResult } from './db.model';
10
10
  import { CommonKeyValueDao, CommonKeyValueDaoCfg } from './kv/commonKeyValueDao';
11
11
  import { CommonKeyValueDB, KeyValueDBTuple } from './kv/commonKeyValueDB';
12
12
  import { createdUpdatedFields, createdUpdatedIdFields, deserializeJsonField, serializeJsonField } from './model.util';
@@ -17,5 +17,5 @@ import { DBQuery, DBQueryFilter, DBQueryFilterOperator, dbQueryFilterOperatorVal
17
17
  import { DBTransaction, RunnableDBTransaction } from './transaction/dbTransaction';
18
18
  import { commitDBTransactionSimple, mergeDBOperations } from './transaction/dbTransaction.util';
19
19
  export * from './kv/commonKeyValueDaoMemoCache';
20
- export type { DBQueryFilterOperator, DBQueryFilter, DBQueryOrder, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoSaveOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions, CommonDBOptions, CommonDBSaveOptions, CommonDBStreamOptions, CommonDBCreateOptions, CommonDB, RunQueryResult, CommonDaoCfg, CommonDaoCreateIdHook, CommonDaoParseNaturalIdHook, CommonDaoBeforeCreateHook, CommonDaoBeforeDBMValidateHook, CommonDaoBeforeDBMToBMHook, CommonDaoBeforeBMToDBMHook, CommonDaoBeforeTMToBMHook, CommonDaoBeforeBMToTMHook, CommonDaoAnonymizeHook, InMemoryDBCfg, InMemoryKeyValueDBCfg, DBPipelineBackupOptions, DBPipelineRestoreOptions, DBPipelineCopyOptions, CommonDBAdapter, DBOperation, DBSaveBatchOperation, DBDeleteByIdsOperation, CommonKeyValueDB, CommonKeyValueDaoCfg, KeyValueDBTuple, };
20
+ export type { DBQueryFilterOperator, DBQueryFilter, DBQueryOrder, CommonDaoCreateOptions, CommonDaoOptions, CommonDaoSaveOptions, CommonDaoStreamForEachOptions, CommonDaoStreamOptions, CommonDaoHooks, CommonDBOptions, CommonDBSaveOptions, CommonDBStreamOptions, CommonDBCreateOptions, CommonDB, RunQueryResult, CommonDaoCfg, InMemoryDBCfg, InMemoryKeyValueDBCfg, DBPipelineBackupOptions, DBPipelineRestoreOptions, DBPipelineCopyOptions, DBOperation, DBSaveBatchOperation, DBDeleteByIdsOperation, CommonKeyValueDB, CommonKeyValueDaoCfg, KeyValueDBTuple, };
21
21
  export { DBQuery, dbQueryFilterOperatorValues, RunnableDBQuery, CommonDaoLogLevel, DBRelation, DBModelType, CommonDao, createdUpdatedFields, createdUpdatedIdFields, InMemoryDB, InMemoryKeyValueDB, queryInMemory, serializeJsonField, deserializeJsonField, dbPipelineBackup, dbPipelineRestore, dbPipelineCopy, DBLibError, BaseCommonDB, DBTransaction, RunnableDBTransaction, mergeDBOperations, commitDBTransactionSimple, CommonKeyValueDao, };
@@ -83,12 +83,12 @@ export declare class DBQuery<ROW extends ObjectWithId = AnyObjectWithId> {
83
83
  /**
84
84
  * DBQuery that has additional method to support Fluent API style.
85
85
  */
86
- export declare class RunnableDBQuery<BM extends Partial<ObjectWithId>, DBM extends ObjectWithId, TM> extends DBQuery<DBM> {
87
- dao: CommonDao<BM, DBM, TM>;
86
+ export declare class RunnableDBQuery<BM extends Partial<ObjectWithId<ID>>, DBM extends ObjectWithId<ID>, TM, ID extends string | number> extends DBQuery<DBM> {
87
+ dao: CommonDao<BM, DBM, TM, ID>;
88
88
  /**
89
89
  * Pass `table` to override table.
90
90
  */
91
- constructor(dao: CommonDao<BM, DBM, TM>, table?: string);
91
+ constructor(dao: CommonDao<BM, DBM, TM, ID>, table?: string);
92
92
  runQuery(opt?: CommonDaoOptions): Promise<Saved<BM>[]>;
93
93
  runQuerySingleColumn<T = any>(opt?: CommonDaoOptions): Promise<T[]>;
94
94
  runQueryAsDBM(opt?: CommonDaoOptions): Promise<DBM[]>;
@@ -101,9 +101,9 @@ export declare class RunnableDBQuery<BM extends Partial<ObjectWithId>, DBM exten
101
101
  streamQueryAsDBMForEach(mapper: AsyncMapper<DBM, void>, opt?: CommonDaoStreamForEachOptions<DBM>): Promise<void>;
102
102
  streamQuery(opt?: CommonDaoStreamOptions): ReadableTyped<Saved<BM>>;
103
103
  streamQueryAsDBM(opt?: CommonDaoStreamOptions): ReadableTyped<DBM>;
104
- queryIds(opt?: CommonDaoOptions): Promise<string[]>;
105
- streamQueryIds(opt?: CommonDaoStreamOptions): ReadableTyped<string>;
106
- streamQueryIdsForEach(mapper: AsyncMapper<string, void>, opt?: CommonDaoStreamForEachOptions<string>): Promise<void>;
104
+ queryIds(opt?: CommonDaoOptions): Promise<ID[]>;
105
+ streamQueryIds(opt?: CommonDaoStreamOptions): ReadableTyped<ID>;
106
+ streamQueryIdsForEach(mapper: AsyncMapper<ID, void>, opt?: CommonDaoStreamForEachOptions<ID>): Promise<void>;
107
107
  deleteByQuery(opt?: CommonDaoStreamForEachOptions<DBM> & {
108
108
  stream?: boolean;
109
109
  }): Promise<number>;
@@ -1,8 +1,8 @@
1
1
  import { CommonDBOptions, CommonDBSaveOptions } from '../db.model';
2
2
  import { DBQuery, DBQueryFilter, DBQueryOrder } from '../query/dbQuery';
3
3
  export declare const commonDBOptionsSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<CommonDBOptions, CommonDBOptions>;
4
- export declare const commonDBSaveOptionsSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<CommonDBSaveOptions<import("@naturalcycles/js-lib").AnyObjectWithId<string>>, CommonDBSaveOptions<import("@naturalcycles/js-lib").AnyObjectWithId<string>>>;
4
+ export declare const commonDBSaveOptionsSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<CommonDBSaveOptions<import("@naturalcycles/js-lib").AnyObjectWithId<string | number>>, CommonDBSaveOptions<import("@naturalcycles/js-lib").AnyObjectWithId<string | number>>>;
5
5
  export declare const dbQueryFilterOperatorSchema: import("@naturalcycles/nodejs-lib/dist/validation/joi/string.extensions").ExtendedStringSchema;
6
- export declare const dbQueryFilterSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<DBQueryFilter<import("@naturalcycles/js-lib").AnyObjectWithId<string>>, DBQueryFilter<import("@naturalcycles/js-lib").AnyObjectWithId<string>>>;
7
- export declare const dbQueryOrderSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<DBQueryOrder<import("@naturalcycles/js-lib").AnyObjectWithId<string>>, DBQueryOrder<import("@naturalcycles/js-lib").AnyObjectWithId<string>>>;
6
+ export declare const dbQueryFilterSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<DBQueryFilter<import("@naturalcycles/js-lib").AnyObjectWithId<string | number>>, DBQueryFilter<import("@naturalcycles/js-lib").AnyObjectWithId<string | number>>>;
7
+ export declare const dbQueryOrderSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<DBQueryOrder<import("@naturalcycles/js-lib").AnyObjectWithId<string | number>>, DBQueryOrder<import("@naturalcycles/js-lib").AnyObjectWithId<string | number>>>;
8
8
  export declare const dbQuerySchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<DBQuery<any>, DBQuery<any>>;
package/package.json CHANGED
@@ -42,7 +42,7 @@
42
42
  "engines": {
43
43
  "node": ">=14.15"
44
44
  },
45
- "version": "8.35.0",
45
+ "version": "8.36.0",
46
46
  "description": "Lowest Common Denominator API to supported Databases",
47
47
  "keywords": [
48
48
  "db",
@@ -45,7 +45,7 @@ export interface CacheDBCfg {
45
45
  logger?: CommonLogger
46
46
  }
47
47
 
48
- export interface CacheDBOptions<ROW extends ObjectWithId> extends CommonDBSaveOptions<ROW> {
48
+ export interface CacheDBOptions {
49
49
  /**
50
50
  * @default false
51
51
  */
@@ -57,9 +57,10 @@ export interface CacheDBOptions<ROW extends ObjectWithId> extends CommonDBSaveOp
57
57
  onlyCache?: boolean
58
58
  }
59
59
 
60
- export interface CacheDBStreamOptions<ROW extends ObjectWithId>
61
- extends CacheDBOptions<ROW>,
62
- CommonDBStreamOptions {}
63
- export interface CacheDBCreateOptions<ROW extends ObjectWithId>
64
- extends CacheDBOptions<ROW>,
65
- CommonDBCreateOptions {}
60
+ export interface CacheDBSaveOptions<ROW extends ObjectWithId>
61
+ extends CacheDBOptions,
62
+ CommonDBSaveOptions<ROW> {}
63
+
64
+ export interface CacheDBStreamOptions extends CacheDBOptions, CommonDBStreamOptions {}
65
+
66
+ export interface CacheDBCreateOptions extends CacheDBOptions, CommonDBCreateOptions {}
@@ -13,6 +13,7 @@ import {
13
13
  CacheDBCfg,
14
14
  CacheDBCreateOptions,
15
15
  CacheDBOptions,
16
+ CacheDBSaveOptions,
16
17
  CacheDBStreamOptions,
17
18
  } from './cache.db.model'
18
19
 
@@ -59,7 +60,7 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
59
60
  override async createTable<ROW extends ObjectWithId>(
60
61
  table: string,
61
62
  schema: JsonSchemaObject<ROW>,
62
- opt: CacheDBCreateOptions<ROW> = {},
63
+ opt: CacheDBCreateOptions = {},
63
64
  ): Promise<void> {
64
65
  if (!opt.onlyCache && !this.cfg.onlyCache) {
65
66
  await this.cfg.downstreamDB.createTable(table, schema, opt)
@@ -72,11 +73,11 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
72
73
 
73
74
  override async getByIds<ROW extends ObjectWithId>(
74
75
  table: string,
75
- ids: string[],
76
- opt: CacheDBOptions<ROW> = {},
76
+ ids: ROW['id'][],
77
+ opt: CacheDBSaveOptions<ROW> = {},
77
78
  ): Promise<ROW[]> {
78
79
  const resultMap: StringMap<ROW> = {}
79
- const missingIds: string[] = []
80
+ const missingIds: ROW['id'][] = []
80
81
 
81
82
  if (!opt.skipCache && !this.cfg.skipCache) {
82
83
  const results = await this.cfg.cacheDB.getByIds<ROW>(table, ids, opt)
@@ -118,13 +119,13 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
118
119
 
119
120
  override async deleteByIds<ROW extends ObjectWithId>(
120
121
  table: string,
121
- ids: string[],
122
- opt: CacheDBOptions<ROW> = {},
122
+ ids: ROW['id'][],
123
+ opt: CacheDBOptions = {},
123
124
  ): Promise<number> {
124
125
  let deletedIds = 0
125
126
 
126
127
  if (!opt.onlyCache && !this.cfg.onlyCache) {
127
- deletedIds = await this.cfg.downstreamDB.deleteByIds(table, ids, opt)
128
+ deletedIds = await this.cfg.downstreamDB.deleteByIds<ROW>(table, ids, opt)
128
129
 
129
130
  if (this.cfg.logDownstream) {
130
131
  this.cfg.logger?.log(`${table}.deleteByIds ${deletedIds} rows from downstream`)
@@ -132,11 +133,13 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
132
133
  }
133
134
 
134
135
  if (!opt.skipCache && !this.cfg.skipCache) {
135
- const cacheResult = this.cfg.cacheDB.deleteByIds(table, ids, opt).then(deletedFromCache => {
136
- if (this.cfg.logCached) {
137
- this.cfg.logger?.log(`${table}.deleteByIds ${deletedFromCache} rows from cache`)
138
- }
139
- })
136
+ const cacheResult = this.cfg.cacheDB
137
+ .deleteByIds<ROW>(table, ids, opt)
138
+ .then(deletedFromCache => {
139
+ if (this.cfg.logCached) {
140
+ this.cfg.logger?.log(`${table}.deleteByIds ${deletedFromCache} rows from cache`)
141
+ }
142
+ })
140
143
  if (this.cfg.awaitCache) await cacheResult
141
144
  }
142
145
 
@@ -146,7 +149,7 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
146
149
  override async saveBatch<ROW extends ObjectWithId>(
147
150
  table: string,
148
151
  rows: ROW[],
149
- opt: CacheDBOptions<ROW> = {},
152
+ opt: CacheDBSaveOptions<ROW> = {},
150
153
  ): Promise<void> {
151
154
  if (!opt.onlyCache && !this.cfg.onlyCache) {
152
155
  await this.cfg.downstreamDB.saveBatch(table, rows, opt)
@@ -174,7 +177,7 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
174
177
 
175
178
  override async runQuery<ROW extends ObjectWithId>(
176
179
  q: DBQuery<ROW>,
177
- opt: CacheDBOptions<ROW> = {},
180
+ opt: CacheDBSaveOptions<ROW> = {},
178
181
  ): Promise<RunQueryResult<ROW>> {
179
182
  if (!opt.onlyCache && !this.cfg.onlyCache) {
180
183
  const { rows, ...queryResult } = await this.cfg.downstreamDB.runQuery(q, opt)
@@ -204,7 +207,7 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
204
207
 
205
208
  override async runQueryCount<ROW extends ObjectWithId>(
206
209
  q: DBQuery<ROW>,
207
- opt: CacheDBOptions<ROW> = {},
210
+ opt: CacheDBOptions = {},
208
211
  ): Promise<number> {
209
212
  if (!opt.onlyCache && !this.cfg.onlyCache) {
210
213
  return await this.cfg.downstreamDB.runQueryCount(q, opt)
@@ -221,7 +224,7 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
221
224
 
222
225
  override streamQuery<ROW extends ObjectWithId>(
223
226
  q: DBQuery<ROW>,
224
- opt: CacheDBStreamOptions<ROW> = {},
227
+ opt: CacheDBStreamOptions = {},
225
228
  ): Readable {
226
229
  if (!opt.onlyCache && !this.cfg.onlyCache) {
227
230
  const stream = this.cfg.downstreamDB.streamQuery<ROW>(q, opt)
@@ -260,7 +263,7 @@ export class CacheDB extends BaseCommonDB implements CommonDB {
260
263
 
261
264
  override async deleteByQuery<ROW extends ObjectWithId>(
262
265
  q: DBQuery<ROW>,
263
- opt: CacheDBOptions<ROW> = {},
266
+ opt: CacheDBOptions = {},
264
267
  ): Promise<number> {
265
268
  if (!opt.onlyCache && !this.cfg.onlyCache) {
266
269
  const deletedIds = await this.cfg.downstreamDB.deleteByQuery(q, opt)