@naturalcycles/datastore-lib 3.19.0 → 3.20.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.
@@ -20,7 +20,7 @@ export declare class DatastoreDB extends BaseCommonDB implements CommonDB {
20
20
  protected KEY: symbol;
21
21
  ds(): Datastore;
22
22
  ping(): Promise<void>;
23
- getByIds<ROW extends ObjectWithId>(table: string, ids: string[], _opt?: DatastoreDBOptions): Promise<ROW[]>;
23
+ getByIds<ROW extends ObjectWithId>(table: string, ids: ROW['id'][], _opt?: DatastoreDBOptions): Promise<ROW[]>;
24
24
  getQueryKind(q: Query): string;
25
25
  runQuery<ROW extends ObjectWithId>(dbQuery: DBQuery<ROW>, _opt?: DatastoreDBOptions): Promise<RunQueryResult<ROW>>;
26
26
  runQueryCount<ROW extends ObjectWithId>(dbQuery: DBQuery<ROW>, _opt?: DatastoreDBOptions): Promise<number>;
@@ -30,13 +30,13 @@ export declare class DatastoreDB extends BaseCommonDB implements CommonDB {
30
30
  /**
31
31
  * Returns saved entities with generated id/updated/created (non-mutating!)
32
32
  */
33
- saveBatch<ROW extends ObjectWithId>(table: string, rows: ROW[], opt?: DatastoreDBSaveOptions<ROW>): Promise<void>;
33
+ saveBatch<ROW extends Partial<ObjectWithId>>(table: string, rows: ROW[], opt?: DatastoreDBSaveOptions<ROW>): Promise<void>;
34
34
  deleteByQuery<ROW extends ObjectWithId>(q: DBQuery<ROW>, opt?: DatastoreDBOptions): Promise<number>;
35
35
  /**
36
36
  * Limitation: Datastore's delete returns void, so we always return all ids here as "deleted"
37
37
  * regardless if they were actually deleted or not.
38
38
  */
39
- deleteByIds(table: string, ids: string[], opt?: DatastoreDBOptions): Promise<number>;
39
+ deleteByIds<ROW extends ObjectWithId>(table: string, ids: ROW['id'][], opt?: DatastoreDBOptions): Promise<number>;
40
40
  /**
41
41
  * https://cloud.google.com/datastore/docs/concepts/transactions#datastore-datastore-transactional-update-nodejs
42
42
  */
@@ -50,9 +50,9 @@ export declare class DatastoreDB extends BaseCommonDB implements CommonDB {
50
50
  getTableProperties(table: string): Promise<DatastorePropertyStats[]>;
51
51
  mapId<T = any>(o: any, preserveKey?: boolean): T;
52
52
  toDatastoreEntity<T = any>(kind: string, o: T & {
53
- id?: string;
53
+ id?: string | number;
54
54
  }, excludeFromIndexes?: string[]): DatastorePayload<T>;
55
- key(kind: string, id: string): Key;
55
+ key(kind: string, id: string | number): Key;
56
56
  getDsKey(o: any): Key | undefined;
57
57
  getKey(key: Key): string | undefined;
58
58
  getTables(): Promise<string[]>;
@@ -13,6 +13,11 @@ const MAX_ITEMS = 500;
13
13
  const RETRY_ON = ['GOAWAY', 'UNAVAILABLE', 'UNKNOWN'];
14
14
  // Examples of errors:
15
15
  // UNKNOWN: Stream removed
16
+ const methodMap = {
17
+ insert: 'insert',
18
+ update: 'update',
19
+ upsert: 'save',
20
+ };
16
21
  /**
17
22
  * Datastore API:
18
23
  * https://googlecloudplatform.github.io/google-cloud-node/#/docs/datastore/1.0.3/datastore
@@ -79,6 +84,10 @@ class DatastoreDB extends db_lib_1.BaseCommonDB {
79
84
  const r = await (0, js_lib_1.pTimeout)(this.ds().get(keys), {
80
85
  timeout: this.cfg.timeout,
81
86
  name: `datastore.getByIds(${table}) second try`,
87
+ errorData: {
88
+ // This error will be grouped ACROSS all endpoints and usages
89
+ fingerprint: ['DATASTORE_TIMEOUT'],
90
+ },
82
91
  });
83
92
  rows = r[0];
84
93
  }
@@ -143,8 +152,9 @@ class DatastoreDB extends db_lib_1.BaseCommonDB {
143
152
  */
144
153
  async saveBatch(table, rows, opt = {}) {
145
154
  const entities = rows.map(obj => this.toDatastoreEntity(table, obj, opt.excludeFromIndexes));
155
+ const method = methodMap[opt.saveMethod || 'upsert'] || 'save';
146
156
  const save = (0, js_lib_1.pRetryFn)(async (batch) => {
147
- await (opt.tx || this.ds()).save(batch);
157
+ await (opt.tx || this.ds())[method](batch);
148
158
  }, {
149
159
  // Here we retry the GOAWAY errors that are somewhat common for Datastore
150
160
  // Currently only retrying them here in .saveBatch(), cause probably they're only thrown when saving
@@ -88,7 +88,7 @@ export interface DatastoreDBStreamOptions extends DatastoreDBOptions {
88
88
  export interface DatastoreDBOptions extends CommonDBOptions {
89
89
  tx?: Transaction;
90
90
  }
91
- export interface DatastoreDBSaveOptions<ROW extends ObjectWithId = AnyObjectWithId> extends CommonDBSaveOptions<ROW> {
91
+ export interface DatastoreDBSaveOptions<ROW extends Partial<ObjectWithId> = AnyObjectWithId> extends CommonDBSaveOptions<ROW> {
92
92
  tx?: Transaction;
93
93
  }
94
94
  export interface DatastoreStats {
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  import { DatastoreDB } from './datastore.db';
2
2
  import { DatastoreCredentials, DatastoreDBCfg, DatastoreDBOptions, DatastoreDBSaveOptions, DatastoreDBStreamOptions, DatastorePayload, DatastorePropertyStats, DatastoreStats, DatastoreType } from './datastore.model';
3
3
  import { DatastoreKeyValueDB, DatastoreKeyValueDBCfg } from './datastoreKeyValueDB';
4
- import { getDBAdapter } from './dbAdapter';
5
4
  export type { DatastorePayload, DatastoreDBCfg, DatastoreKeyValueDBCfg, DatastoreStats, DatastoreCredentials, DatastorePropertyStats, DatastoreDBStreamOptions, DatastoreDBOptions, DatastoreDBSaveOptions, };
6
- export { DatastoreDB, DatastoreType, getDBAdapter, DatastoreKeyValueDB };
5
+ export { DatastoreDB, DatastoreType, DatastoreKeyValueDB };
package/dist/index.js CHANGED
@@ -1,11 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DatastoreKeyValueDB = exports.getDBAdapter = exports.DatastoreType = exports.DatastoreDB = void 0;
3
+ exports.DatastoreKeyValueDB = exports.DatastoreType = exports.DatastoreDB = void 0;
4
4
  const datastore_db_1 = require("./datastore.db");
5
5
  Object.defineProperty(exports, "DatastoreDB", { enumerable: true, get: function () { return datastore_db_1.DatastoreDB; } });
6
6
  const datastore_model_1 = require("./datastore.model");
7
7
  Object.defineProperty(exports, "DatastoreType", { enumerable: true, get: function () { return datastore_model_1.DatastoreType; } });
8
8
  const datastoreKeyValueDB_1 = require("./datastoreKeyValueDB");
9
9
  Object.defineProperty(exports, "DatastoreKeyValueDB", { enumerable: true, get: function () { return datastoreKeyValueDB_1.DatastoreKeyValueDB; } });
10
- const dbAdapter_1 = require("./dbAdapter");
11
- Object.defineProperty(exports, "getDBAdapter", { enumerable: true, get: function () { return dbAdapter_1.getDBAdapter; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@naturalcycles/datastore-lib",
3
- "version": "3.19.0",
3
+ "version": "3.20.0",
4
4
  "description": "Opinionated library to work with Google Datastore",
5
5
  "scripts": {
6
6
  "prepare": "husky install"
@@ -3,6 +3,7 @@ import type { Datastore, Key, Query } from '@google-cloud/datastore'
3
3
  import {
4
4
  BaseCommonDB,
5
5
  CommonDB,
6
+ CommonDBSaveMethod,
6
7
  DBQuery,
7
8
  DBTransaction,
8
9
  mergeDBOperations,
@@ -48,6 +49,12 @@ const RETRY_ON = ['GOAWAY', 'UNAVAILABLE', 'UNKNOWN']
48
49
  // Examples of errors:
49
50
  // UNKNOWN: Stream removed
50
51
 
52
+ const methodMap: Record<CommonDBSaveMethod, string> = {
53
+ insert: 'insert',
54
+ update: 'update',
55
+ upsert: 'save',
56
+ }
57
+
51
58
  /**
52
59
  * Datastore API:
53
60
  * https://googlecloudplatform.github.io/google-cloud-node/#/docs/datastore/1.0.3/datastore
@@ -111,7 +118,7 @@ export class DatastoreDB extends BaseCommonDB implements CommonDB {
111
118
 
112
119
  override async getByIds<ROW extends ObjectWithId>(
113
120
  table: string,
114
- ids: string[],
121
+ ids: ROW['id'][],
115
122
  _opt?: DatastoreDBOptions,
116
123
  ): Promise<ROW[]> {
117
124
  if (!ids.length) return []
@@ -138,6 +145,10 @@ export class DatastoreDB extends BaseCommonDB implements CommonDB {
138
145
  const r = await pTimeout(this.ds().get(keys), {
139
146
  timeout: this.cfg.timeout,
140
147
  name: `datastore.getByIds(${table}) second try`,
148
+ errorData: {
149
+ // This error will be grouped ACROSS all endpoints and usages
150
+ fingerprint: ['DATASTORE_TIMEOUT'],
151
+ },
141
152
  })
142
153
  rows = r[0]
143
154
  }
@@ -234,7 +245,7 @@ export class DatastoreDB extends BaseCommonDB implements CommonDB {
234
245
  /**
235
246
  * Returns saved entities with generated id/updated/created (non-mutating!)
236
247
  */
237
- override async saveBatch<ROW extends ObjectWithId>(
248
+ override async saveBatch<ROW extends Partial<ObjectWithId>>(
238
249
  table: string,
239
250
  rows: ROW[],
240
251
  opt: DatastoreDBSaveOptions<ROW> = {},
@@ -243,9 +254,11 @@ export class DatastoreDB extends BaseCommonDB implements CommonDB {
243
254
  this.toDatastoreEntity(table, obj, opt.excludeFromIndexes as string[]),
244
255
  )
245
256
 
257
+ const method = methodMap[opt.saveMethod || 'upsert'] || 'save'
258
+
246
259
  const save = pRetryFn(
247
260
  async (batch: DatastorePayload<ROW>[]) => {
248
- await (opt.tx || this.ds()).save(batch)
261
+ await (opt.tx || this.ds())[method](batch)
249
262
  },
250
263
  {
251
264
  // Here we retry the GOAWAY errors that are somewhat common for Datastore
@@ -298,9 +311,9 @@ export class DatastoreDB extends BaseCommonDB implements CommonDB {
298
311
  * Limitation: Datastore's delete returns void, so we always return all ids here as "deleted"
299
312
  * regardless if they were actually deleted or not.
300
313
  */
301
- override async deleteByIds(
314
+ override async deleteByIds<ROW extends ObjectWithId>(
302
315
  table: string,
303
- ids: string[],
316
+ ids: ROW['id'][],
304
317
  opt: DatastoreDBOptions = {},
305
318
  ): Promise<number> {
306
319
  const keys = ids.map(id => this.key(table, id))
@@ -382,7 +395,7 @@ export class DatastoreDB extends BaseCommonDB implements CommonDB {
382
395
  // if key field exists on entity, it will be used as key (prevent to duplication of numeric keyed entities)
383
396
  toDatastoreEntity<T = any>(
384
397
  kind: string,
385
- o: T & { id?: string },
398
+ o: T & { id?: string | number },
386
399
  excludeFromIndexes: string[] = [],
387
400
  ): DatastorePayload<T> {
388
401
  const key = this.getDsKey(o) || this.key(kind, o.id!)
@@ -397,7 +410,7 @@ export class DatastoreDB extends BaseCommonDB implements CommonDB {
397
410
  }
398
411
  }
399
412
 
400
- key(kind: string, id: string): Key {
413
+ key(kind: string, id: string | number): Key {
401
414
  _assert(id, `Cannot save "${kind}" entity without "id"`)
402
415
  return this.ds().key([kind, String(id)])
403
416
  }
@@ -102,7 +102,7 @@ export interface DatastoreDBStreamOptions extends DatastoreDBOptions {
102
102
  export interface DatastoreDBOptions extends CommonDBOptions {
103
103
  tx?: Transaction
104
104
  }
105
- export interface DatastoreDBSaveOptions<ROW extends ObjectWithId = AnyObjectWithId>
105
+ export interface DatastoreDBSaveOptions<ROW extends Partial<ObjectWithId> = AnyObjectWithId>
106
106
  extends CommonDBSaveOptions<ROW> {
107
107
  tx?: Transaction
108
108
  }
@@ -50,7 +50,7 @@ export class DatastoreKeyValueDB implements CommonKeyValueDB {
50
50
  .limit(limit || 0)
51
51
 
52
52
  return this.db.streamQuery<KVObject>(q).pipe(
53
- transformMapSimple<ObjectWithId, string>(objectWithId => objectWithId.id, {
53
+ transformMapSimple<ObjectWithId<string>, string>(objectWithId => objectWithId.id, {
54
54
  errorMode: ErrorMode.SUPPRESS, // cause .pipe() cannot propagate errors
55
55
  }),
56
56
  )
package/src/index.ts CHANGED
@@ -11,7 +11,6 @@ import {
11
11
  DatastoreType,
12
12
  } from './datastore.model'
13
13
  import { DatastoreKeyValueDB, DatastoreKeyValueDBCfg } from './datastoreKeyValueDB'
14
- import { getDBAdapter } from './dbAdapter'
15
14
 
16
15
  export type {
17
16
  DatastorePayload,
@@ -25,4 +24,4 @@ export type {
25
24
  DatastoreDBSaveOptions,
26
25
  }
27
26
 
28
- export { DatastoreDB, DatastoreType, getDBAdapter, DatastoreKeyValueDB }
27
+ export { DatastoreDB, DatastoreType, DatastoreKeyValueDB }
@@ -1,2 +0,0 @@
1
- import { DatastoreDB } from './datastore.db';
2
- export declare function getDBAdapter(cfgStr?: string): DatastoreDB;
package/dist/dbAdapter.js DELETED
@@ -1,13 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDBAdapter = void 0;
4
- const datastore_db_1 = require("./datastore.db");
5
- function getDBAdapter(cfgStr) {
6
- const cfg = cfgStr
7
- ? JSON.parse(cfgStr)
8
- : {
9
- useLegacyGRPC: true,
10
- };
11
- return new datastore_db_1.DatastoreDB(cfg);
12
- }
13
- exports.getDBAdapter = getDBAdapter;
package/src/dbAdapter.ts DELETED
@@ -1,11 +0,0 @@
1
- import { DatastoreDB } from './datastore.db'
2
- import { DatastoreDBCfg } from './datastore.model'
3
-
4
- export function getDBAdapter(cfgStr?: string): DatastoreDB {
5
- const cfg: DatastoreDBCfg = cfgStr
6
- ? JSON.parse(cfgStr)
7
- : {
8
- useLegacyGRPC: true,
9
- }
10
- return new DatastoreDB(cfg)
11
- }