@naturalcycles/db-lib 8.30.0 → 8.33.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.
@@ -25,7 +25,8 @@ class CommonDao {
25
25
  // otherwise to log Operations
26
26
  // e.g in Dev (local machine), Test - it will log operations (useful for debugging)
27
27
  logLevel: isGAE || isCI ? common_dao_model_1.CommonDaoLogLevel.NONE : common_dao_model_1.CommonDaoLogLevel.OPERATIONS,
28
- createdUpdated: true,
28
+ created: true,
29
+ updated: true,
29
30
  logger: console,
30
31
  ...cfg,
31
32
  hooks: {
@@ -405,9 +406,13 @@ class CommonDao {
405
406
  assignIdCreatedUpdated(obj, opt = {}) {
406
407
  const now = Math.floor(Date.now() / 1000);
407
408
  obj.id = obj.id || this.cfg.hooks.createId(obj);
408
- if (this.cfg.createdUpdated) {
409
+ if (this.cfg.created) {
409
410
  Object.assign(obj, {
410
411
  created: obj.created || obj.updated || now,
412
+ });
413
+ }
414
+ if (this.cfg.updated) {
415
+ Object.assign(obj, {
411
416
  updated: opt.preserveUpdatedCreated && obj.updated ? obj.updated : now,
412
417
  });
413
418
  }
@@ -76,10 +76,15 @@ export interface CommonDaoCfg<BM extends Partial<ObjectWithId>, DBM extends Obje
76
76
  logStarted?: boolean;
77
77
  hooks?: Partial<CommonDaoHooks<BM, DBM, TM>>;
78
78
  /**
79
- * @default true
80
- * Set to false to disable created/updated fields management.
79
+ * Defaults to true
80
+ * Set to false to disable `created` field management.
81
81
  */
82
- createdUpdated?: boolean;
82
+ created?: boolean;
83
+ /**
84
+ * Defaults to true
85
+ * Set to false to disable `updated` field management.
86
+ */
87
+ updated?: boolean;
83
88
  /**
84
89
  * Default is false.
85
90
  * If true - will run `_filterNullishValues` inside `validateAndConvert` function
package/dist/index.d.ts CHANGED
@@ -17,5 +17,6 @@ import { dbPipelineRestore, DBPipelineRestoreOptions } from './pipeline/dbPipeli
17
17
  import { DBQuery, DBQueryFilter, DBQueryFilterOperator, dbQueryFilterOperatorValues, DBQueryOrder, RunnableDBQuery } from './query/dbQuery';
18
18
  import { DBTransaction, RunnableDBTransaction } from './transaction/dbTransaction';
19
19
  import { commitDBTransactionSimple, mergeDBOperations } from './transaction/dbTransaction.util';
20
+ export * from './kv/commonKeyValueDaoMemoCache';
20
21
  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, };
21
22
  export { DBQuery, dbQueryFilterOperatorValues, RunnableDBQuery, CommonDaoLogLevel, DBRelation, DBModelType, CommonDao, createdUpdatedFields, createdUpdatedIdFields, InMemoryDB, InMemoryKeyValueDB, queryInMemory, serializeJsonField, deserializeJsonField, dbPipelineBackup, dbPipelineRestore, dbPipelineCopy, getDB, DBLibError, BaseCommonDB, DBTransaction, RunnableDBTransaction, mergeDBOperations, commitDBTransactionSimple, CommonKeyValueDao, };
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CommonKeyValueDao = exports.commitDBTransactionSimple = exports.mergeDBOperations = exports.RunnableDBTransaction = exports.DBTransaction = exports.BaseCommonDB = exports.DBLibError = exports.getDB = exports.dbPipelineCopy = exports.dbPipelineRestore = exports.dbPipelineBackup = exports.deserializeJsonField = exports.serializeJsonField = exports.queryInMemory = exports.InMemoryKeyValueDB = exports.InMemoryDB = exports.createdUpdatedIdFields = exports.createdUpdatedFields = exports.CommonDao = exports.DBModelType = exports.DBRelation = exports.CommonDaoLogLevel = exports.RunnableDBQuery = exports.dbQueryFilterOperatorValues = exports.DBQuery = void 0;
4
+ const tslib_1 = require("tslib");
4
5
  const inMemory_db_1 = require("./adapter/inmemory/inMemory.db");
5
6
  Object.defineProperty(exports, "InMemoryDB", { enumerable: true, get: function () { return inMemory_db_1.InMemoryDB; } });
6
7
  const inMemoryKeyValueDB_1 = require("./adapter/inmemory/inMemoryKeyValueDB");
@@ -43,3 +44,4 @@ Object.defineProperty(exports, "RunnableDBTransaction", { enumerable: true, get:
43
44
  const dbTransaction_util_1 = require("./transaction/dbTransaction.util");
44
45
  Object.defineProperty(exports, "commitDBTransactionSimple", { enumerable: true, get: function () { return dbTransaction_util_1.commitDBTransactionSimple; } });
45
46
  Object.defineProperty(exports, "mergeDBOperations", { enumerable: true, get: function () { return dbTransaction_util_1.mergeDBOperations; } });
47
+ (0, tslib_1.__exportStar)(require("./kv/commonKeyValueDaoMemoCache"), exports);
@@ -25,6 +25,12 @@ export interface CommonKeyValueDaoCfg<T> {
25
25
  mapBufferToValue?: (b: Buffer) => Promise<T>;
26
26
  beforeCreate?: (v: Partial<T>) => Partial<T>;
27
27
  };
28
+ /**
29
+ * Set to `true` to conveniently enable zipping+JSON.stringify
30
+ * (and unzipping+JSON.parse) of the Buffer value via hooks.
31
+ * Custom hooks will override these hooks (if provided).
32
+ */
33
+ deflatedJsonValue?: boolean;
28
34
  }
29
35
  export declare class CommonKeyValueDao<T> {
30
36
  cfg: CommonKeyValueDaoCfg<T>;
@@ -33,6 +39,7 @@ export declare class CommonKeyValueDao<T> {
33
39
  createTable(opt?: CommonDBCreateOptions): Promise<void>;
34
40
  create(input?: Partial<T>): T;
35
41
  getById(id?: string): Promise<T | null>;
42
+ requireById(id: string): Promise<T>;
36
43
  getByIdOrEmpty(id: string, part?: Partial<T>): Promise<T>;
37
44
  patch(id: string, patch: Partial<T>): Promise<T>;
38
45
  getByIds(ids: string[]): Promise<KeyValueTuple<string, T>[]>;
@@ -3,11 +3,19 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CommonKeyValueDao = void 0;
4
4
  const js_lib_1 = require("@naturalcycles/js-lib");
5
5
  const nodejs_lib_1 = require("@naturalcycles/nodejs-lib");
6
+ const cnst_1 = require("../cnst");
6
7
  // todo: logging
7
8
  // todo: readonly
8
9
  class CommonKeyValueDao {
9
10
  constructor(cfg) {
10
11
  this.cfg = cfg;
12
+ if (cfg.deflatedJsonValue) {
13
+ cfg.hooks = {
14
+ mapValueToBuffer: async (v) => await (0, nodejs_lib_1.deflateString)(JSON.stringify(v)),
15
+ mapBufferToValue: async (buf) => JSON.parse(await (0, nodejs_lib_1.inflateToString)(buf)),
16
+ ...cfg.hooks,
17
+ };
18
+ }
11
19
  }
12
20
  async ping() {
13
21
  await this.cfg.db.ping();
@@ -26,6 +34,18 @@ class CommonKeyValueDao {
26
34
  const [r] = await this.getByIds([id]);
27
35
  return r?.[1] || null;
28
36
  }
37
+ async requireById(id) {
38
+ const [r] = await this.getByIds([id]);
39
+ if (!r) {
40
+ const { table } = this.cfg;
41
+ throw new js_lib_1.AppError(`DB row required, but not found: ${table}.${id}`, {
42
+ code: cnst_1.DBLibError.DB_ROW_REQUIRED,
43
+ table,
44
+ id,
45
+ });
46
+ }
47
+ return r[1];
48
+ }
29
49
  async getByIdOrEmpty(id, part = {}) {
30
50
  const [r] = await this.getByIds([id]);
31
51
  if (r)
@@ -0,0 +1,17 @@
1
+ import { AsyncMemoCache } from '@naturalcycles/js-lib';
2
+ import { CommonKeyValueDao } from './commonKeyValueDao';
3
+ /**
4
+ * AsyncMemoCache implementation, backed by CommonKeyValueDao.
5
+ *
6
+ * Does NOT support persisting Errors, skips them instead.
7
+ *
8
+ * Also, does not support .clear(), as it's more dangerous than useful to actually
9
+ * clear the whole table/cache.
10
+ */
11
+ export declare class CommonKeyValueDaoMemoCache<VALUE = any> implements AsyncMemoCache<string, VALUE> {
12
+ private dao;
13
+ constructor(dao: CommonKeyValueDao<VALUE>);
14
+ get(k: string): Promise<VALUE | Error | undefined>;
15
+ set(k: string, v: VALUE | Error): Promise<void>;
16
+ clear(): Promise<void>;
17
+ }
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CommonKeyValueDaoMemoCache = void 0;
4
+ /**
5
+ * AsyncMemoCache implementation, backed by CommonKeyValueDao.
6
+ *
7
+ * Does NOT support persisting Errors, skips them instead.
8
+ *
9
+ * Also, does not support .clear(), as it's more dangerous than useful to actually
10
+ * clear the whole table/cache.
11
+ */
12
+ class CommonKeyValueDaoMemoCache {
13
+ constructor(dao) {
14
+ this.dao = dao;
15
+ }
16
+ async get(k) {
17
+ return (await this.dao.getById(k)) || undefined;
18
+ }
19
+ async set(k, v) {
20
+ if (v instanceof Error) {
21
+ // We currently don't persist errors there
22
+ return;
23
+ }
24
+ await this.dao.save(k, v);
25
+ }
26
+ async clear() {
27
+ throw new Error('CommonKeyValueDaoMemoCache.clear is not supported, because cache is expected to be persistent');
28
+ }
29
+ }
30
+ exports.CommonKeyValueDaoMemoCache = CommonKeyValueDaoMemoCache;
@@ -17,7 +17,7 @@ export interface TestItemTM {
17
17
  export declare const testItemBMSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<TestItemBM, TestItemBM>;
18
18
  export declare const testItemDBMSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<TestItemDBM, TestItemDBM>;
19
19
  export declare const testItemTMSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<TestItemTM, TestItemTM>;
20
- export declare const testItemBMJsonSchema: import("@naturalcycles/js-lib/dist/json-schema/jsonSchemaBuilder").JsonSchemaObjectBuilder<TestItemBM & Partial<import("@naturalcycles/js-lib").SavedDBEntity>>;
20
+ export declare const testItemBMJsonSchema: import("@naturalcycles/js-lib/dist/json-schema/jsonSchemaBuilder").JsonSchemaObjectBuilder<TestItemBM & Partial<import("@naturalcycles/js-lib").SavedDBEntity<string>>>;
21
21
  export declare const testItemDBMJsonSchema: import("@naturalcycles/js-lib/dist/json-schema/jsonSchemaBuilder").JsonSchemaObjectBuilder<TestItemDBM>;
22
22
  export declare function createTestItemDBM(num?: number): TestItemDBM;
23
23
  export declare function createTestItemBM(num?: number): Saved<TestItemBM>;
@@ -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>, CommonDBSaveOptions<import("@naturalcycles/js-lib").AnyObjectWithId>>;
4
+ export declare const commonDBSaveOptionsSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<CommonDBSaveOptions<import("@naturalcycles/js-lib").AnyObjectWithId<string>>, CommonDBSaveOptions<import("@naturalcycles/js-lib").AnyObjectWithId<string>>>;
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>, DBQueryFilter<import("@naturalcycles/js-lib").AnyObjectWithId>>;
7
- export declare const dbQueryOrderSchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<DBQueryOrder<import("@naturalcycles/js-lib").AnyObjectWithId>, DBQueryOrder<import("@naturalcycles/js-lib").AnyObjectWithId>>;
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>>>;
8
8
  export declare const dbQuerySchema: import("@naturalcycles/nodejs-lib").ObjectSchemaTyped<DBQuery<any>, DBQuery<any>>;
package/package.json CHANGED
@@ -43,7 +43,7 @@
43
43
  "engines": {
44
44
  "node": ">=14.15"
45
45
  },
46
- "version": "8.30.0",
46
+ "version": "8.33.1",
47
47
  "description": "Lowest Common Denominator API to supported Databases",
48
48
  "keywords": [
49
49
  "db",
@@ -102,10 +102,16 @@ export interface CommonDaoCfg<
102
102
  hooks?: Partial<CommonDaoHooks<BM, DBM, TM>>
103
103
 
104
104
  /**
105
- * @default true
106
- * Set to false to disable created/updated fields management.
105
+ * Defaults to true
106
+ * Set to false to disable `created` field management.
107
107
  */
108
- createdUpdated?: boolean
108
+ created?: boolean
109
+
110
+ /**
111
+ * Defaults to true
112
+ * Set to false to disable `updated` field management.
113
+ */
114
+ updated?: boolean
109
115
 
110
116
  /**
111
117
  * Default is false.
@@ -69,7 +69,8 @@ export class CommonDao<
69
69
  // otherwise to log Operations
70
70
  // e.g in Dev (local machine), Test - it will log operations (useful for debugging)
71
71
  logLevel: isGAE || isCI ? CommonDaoLogLevel.NONE : CommonDaoLogLevel.OPERATIONS,
72
- createdUpdated: true,
72
+ created: true,
73
+ updated: true,
73
74
  logger: console,
74
75
  ...cfg,
75
76
  hooks: {
@@ -562,9 +563,14 @@ export class CommonDao<
562
563
 
563
564
  obj.id = obj.id || this.cfg.hooks!.createId!(obj)
564
565
 
565
- if (this.cfg.createdUpdated) {
566
+ if (this.cfg.created) {
566
567
  Object.assign(obj, {
567
568
  created: (obj as any).created || (obj as any).updated || now,
569
+ })
570
+ }
571
+
572
+ if (this.cfg.updated) {
573
+ Object.assign(obj, {
568
574
  updated: opt.preserveUpdatedCreated && (obj as any).updated ? (obj as any).updated : now,
569
575
  })
570
576
  }
package/src/index.ts CHANGED
@@ -58,6 +58,7 @@ import {
58
58
  } from './query/dbQuery'
59
59
  import { DBTransaction, RunnableDBTransaction } from './transaction/dbTransaction'
60
60
  import { commitDBTransactionSimple, mergeDBOperations } from './transaction/dbTransaction.util'
61
+ export * from './kv/commonKeyValueDaoMemoCache'
61
62
 
62
63
  export type {
63
64
  DBQueryFilterOperator,
@@ -1,5 +1,11 @@
1
- import { ErrorMode, KeyValueTuple, pMap } from '@naturalcycles/js-lib'
2
- import { ReadableTyped, transformMap } from '@naturalcycles/nodejs-lib'
1
+ import { AppError, ErrorMode, KeyValueTuple, pMap } from '@naturalcycles/js-lib'
2
+ import {
3
+ deflateString,
4
+ inflateToString,
5
+ ReadableTyped,
6
+ transformMap,
7
+ } from '@naturalcycles/nodejs-lib'
8
+ import { DBLibError } from '../cnst'
3
9
  import { CommonDaoLogLevel } from '../commondao/common.dao.model'
4
10
  import { CommonDBCreateOptions } from '../db.model'
5
11
  import { CommonKeyValueDB, KeyValueDBTuple } from './commonKeyValueDB'
@@ -30,13 +36,28 @@ export interface CommonKeyValueDaoCfg<T> {
30
36
  mapBufferToValue?: (b: Buffer) => Promise<T>
31
37
  beforeCreate?: (v: Partial<T>) => Partial<T>
32
38
  }
39
+
40
+ /**
41
+ * Set to `true` to conveniently enable zipping+JSON.stringify
42
+ * (and unzipping+JSON.parse) of the Buffer value via hooks.
43
+ * Custom hooks will override these hooks (if provided).
44
+ */
45
+ deflatedJsonValue?: boolean
33
46
  }
34
47
 
35
48
  // todo: logging
36
49
  // todo: readonly
37
50
 
38
51
  export class CommonKeyValueDao<T> {
39
- constructor(public cfg: CommonKeyValueDaoCfg<T>) {}
52
+ constructor(public cfg: CommonKeyValueDaoCfg<T>) {
53
+ if (cfg.deflatedJsonValue) {
54
+ cfg.hooks = {
55
+ mapValueToBuffer: async v => await deflateString(JSON.stringify(v)),
56
+ mapBufferToValue: async buf => JSON.parse(await inflateToString(buf)),
57
+ ...cfg.hooks,
58
+ }
59
+ }
60
+ }
40
61
 
41
62
  async ping(): Promise<void> {
42
63
  await this.cfg.db.ping()
@@ -58,6 +79,21 @@ export class CommonKeyValueDao<T> {
58
79
  return r?.[1] || null
59
80
  }
60
81
 
82
+ async requireById(id: string): Promise<T> {
83
+ const [r] = await this.getByIds([id])
84
+
85
+ if (!r) {
86
+ const { table } = this.cfg
87
+ throw new AppError(`DB row required, but not found: ${table}.${id}`, {
88
+ code: DBLibError.DB_ROW_REQUIRED,
89
+ table,
90
+ id,
91
+ })
92
+ }
93
+
94
+ return r[1]
95
+ }
96
+
61
97
  async getByIdOrEmpty(id: string, part: Partial<T> = {}): Promise<T> {
62
98
  const [r] = await this.getByIds([id])
63
99
  if (r) return r[1]
@@ -0,0 +1,33 @@
1
+ import { AsyncMemoCache } from '@naturalcycles/js-lib'
2
+ import { CommonKeyValueDao } from './commonKeyValueDao'
3
+
4
+ /**
5
+ * AsyncMemoCache implementation, backed by CommonKeyValueDao.
6
+ *
7
+ * Does NOT support persisting Errors, skips them instead.
8
+ *
9
+ * Also, does not support .clear(), as it's more dangerous than useful to actually
10
+ * clear the whole table/cache.
11
+ */
12
+ export class CommonKeyValueDaoMemoCache<VALUE = any> implements AsyncMemoCache<string, VALUE> {
13
+ constructor(private dao: CommonKeyValueDao<VALUE>) {}
14
+
15
+ async get(k: string): Promise<VALUE | Error | undefined> {
16
+ return (await this.dao.getById(k)) || undefined
17
+ }
18
+
19
+ async set(k: string, v: VALUE | Error): Promise<void> {
20
+ if (v instanceof Error) {
21
+ // We currently don't persist errors there
22
+ return
23
+ }
24
+
25
+ await this.dao.save(k, v)
26
+ }
27
+
28
+ async clear(): Promise<void> {
29
+ throw new Error(
30
+ 'CommonKeyValueDaoMemoCache.clear is not supported, because cache is expected to be persistent',
31
+ )
32
+ }
33
+ }