@sdflc/backend-helpers 1.0.100 → 1.0.101

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.
@@ -1,10 +1,11 @@
1
1
  import { DateTimeHelpers, Logger } from '@sdflc/utils';
2
+ import { DataCache } from './DataCache';
2
3
  import { ApiContext, BaseGatewayPropsInterface, BuildListQueryArgsInterface, CacheInterface, ListArgsInterface, LoaderInterface } from './interfaces';
3
4
  import { Database } from './Database';
4
5
  declare class BaseGateway {
5
6
  protected config: BaseGatewayPropsInterface;
6
7
  protected logger: Logger;
7
- protected loader: any;
8
+ protected loader: LoaderInterface | DataCache;
8
9
  protected dateTime: DateTimeHelpers;
9
10
  protected dateTimeNow: Date;
10
11
  constructor(props: BaseGatewayPropsInterface);
@@ -12,7 +13,12 @@ declare class BaseGateway {
12
13
  setConfigPart(props: BaseGatewayPropsInterface): this;
13
14
  setLoader(loader: LoaderInterface): this;
14
15
  setLoaderConfig(config: CacheInterface): this;
15
- generateId(args?: any): Promise<string>;
16
+ /**
17
+ * Generates object's ID
18
+ * @param object use them when overriding the generate method and you may need data from an object
19
+ * @returns unique ID, by default it is UUID v4
20
+ */
21
+ generateId(object?: any): Promise<string>;
16
22
  onListFilter(query: any, filterParams: any): Promise<void>;
17
23
  onUpdateFilter(query: any, filterParams: any): Promise<number>;
18
24
  onRemoveFilter(query: any, filterParams: any): Promise<number>;
@@ -20,6 +26,7 @@ declare class BaseGateway {
20
26
  transformOnUpdate(params: any, where?: any): Promise<any>;
21
27
  transformOnSet(params: any): Promise<any>;
22
28
  transformOnRemove(args?: any): Promise<any>;
29
+ protected transformOnOut(item: any): any;
23
30
  getRequestId(): string;
24
31
  getContext(): ApiContext;
25
32
  getGateways(): any;
@@ -50,7 +50,12 @@ class BaseGateway {
50
50
  this.loader = new DataCache_1.DataCache({ ...this.config, ...config });
51
51
  return this;
52
52
  }
53
- async generateId(args) {
53
+ /**
54
+ * Generates object's ID
55
+ * @param object use them when overriding the generate method and you may need data from an object
56
+ * @returns unique ID, by default it is UUID v4
57
+ */
58
+ async generateId(object) {
54
59
  return (0, uuid_1.v4)();
55
60
  }
56
61
  async onListFilter(query, filterParams) {
@@ -75,7 +80,9 @@ class BaseGateway {
75
80
  query.whereIn(idField.includes('.') ? `${idField}` : `${table}.${idField}`, (0, lodash_1.castArray)(filterParams?.[idField]));
76
81
  }
77
82
  if (fieldForKeyword && filterParams.keyword) {
78
- query.whereRaw(`${fieldForKeyword} ILIKE ?`, `%${filterParams.keyword}%`);
83
+ // const opLike = this.getDb().getDbType() === 'pg' ? 'ILIKE' : 'LIKE';
84
+ // query.whereRaw(`?? ${opLike} ?`, [fieldForKeyword, `%${filterParams.keyword}%`]);
85
+ query.whereILike(fieldForKeyword, `%${filterParams.keyword}%`);
79
86
  }
80
87
  if (filterByUserField) {
81
88
  query.where({ [filterByUserField]: this.getContext().userId });
@@ -249,6 +256,9 @@ class BaseGateway {
249
256
  }
250
257
  return obj;
251
258
  }
259
+ transformOnOut(item) {
260
+ return item;
261
+ }
252
262
  getRequestId() {
253
263
  return this.config.context.requestId;
254
264
  }
@@ -279,7 +289,7 @@ class BaseGateway {
279
289
  async buildListQuery(args) {
280
290
  const { fieldsToUse } = args || {};
281
291
  const query = this.getBuilder();
282
- query.select(fieldsToUse);
292
+ query.select(fieldsToUse || '*');
283
293
  return { query };
284
294
  }
285
295
  async list(args) {
@@ -300,7 +310,7 @@ class BaseGateway {
300
310
  }
301
311
  const items = await query;
302
312
  const result = shouldUseCache ? await this.getMany(items.map((row) => row.id)) : items;
303
- return result;
313
+ return result.map((item) => this.transformOnOut(item));
304
314
  }
305
315
  async create(args) {
306
316
  const objects = (0, lodash_1.castArray)(args);
@@ -319,7 +329,7 @@ class BaseGateway {
319
329
  const items = await this.getBuilder().insert(chunks[idx]).returning(this.config.returnFields);
320
330
  result.push(...items);
321
331
  }
322
- return result;
332
+ return result.map((item) => this.transformOnOut(item));
323
333
  }
324
334
  async update(where, params) {
325
335
  const object = await this.transformOnUpdate(params, where);
@@ -337,7 +347,7 @@ class BaseGateway {
337
347
  }
338
348
  });
339
349
  }
340
- return items;
350
+ return items.map((item) => this.transformOnOut(item));
341
351
  }
342
352
  async updateMany(params) {
343
353
  if (!Array.isArray(params)) {
@@ -357,7 +367,7 @@ class BaseGateway {
357
367
  }
358
368
  });
359
369
  }
360
- return results;
370
+ return results.map((item) => this.transformOnOut(item));
361
371
  }
362
372
  async increment(where, params) {
363
373
  const object = await this.transformOnUpdate(params, where);
@@ -375,7 +385,7 @@ class BaseGateway {
375
385
  }
376
386
  });
377
387
  }
378
- return items;
388
+ return items.map((item) => this.transformOnOut(item));
379
389
  }
380
390
  async decrement(where, params) {
381
391
  const object = await this.transformOnUpdate(params, where);
@@ -393,7 +403,7 @@ class BaseGateway {
393
403
  }
394
404
  });
395
405
  }
396
- return items;
406
+ return items.map((item) => this.transformOnOut(item));
397
407
  }
398
408
  /**
399
409
  * Inserts or updates data in the database.
@@ -436,7 +446,7 @@ class BaseGateway {
436
446
  .merge((0, lodash_1.pullAll)(fields, skipFields));
437
447
  result.push(...items);
438
448
  }
439
- return result;
449
+ return result.map((item) => this.transformOnOut(item));
440
450
  }
441
451
  async remove(where) {
442
452
  const { hardRemove, hasRemovedAt } = this.config || {};
@@ -461,7 +471,7 @@ class BaseGateway {
461
471
  }
462
472
  });
463
473
  }
464
- return items;
474
+ return items.map((item) => this.transformOnOut(item));
465
475
  }
466
476
  }
467
477
  exports.BaseGateway = BaseGateway;
@@ -1,6 +1,7 @@
1
1
  import { DatabaseOptions, DatabaseReadInterface } from './interfaces';
2
2
  declare class Database {
3
3
  private trx;
4
+ private dbType;
4
5
  private knexHandle;
5
6
  private dbSchema;
6
7
  private logger;
@@ -8,6 +9,7 @@ declare class Database {
8
9
  destroy(): void;
9
10
  isDbError(ex: any): any[];
10
11
  createTransaction(trx: any): Promise<unknown>;
12
+ getDbType(): string;
11
13
  getSchema(): string;
12
14
  getBuilder(arg: any): any;
13
15
  raw(query: string, bindings?: any): any;
@@ -29,5 +31,6 @@ declare class Database {
29
31
  offset: number;
30
32
  sortBy: any[] | null;
31
33
  };
34
+ static destroyHandle(props: DatabaseOptions): void;
32
35
  }
33
36
  export { Database };
package/build/Database.js CHANGED
@@ -16,6 +16,7 @@ const buildKey = (args) => {
16
16
  };
17
17
  class Database {
18
18
  trx = null;
19
+ dbType = '';
19
20
  knexHandle = null;
20
21
  dbSchema = '';
21
22
  logger = new utils_1.Logger({ level: utils_1.LoggerLevels.ERROR });
@@ -35,6 +36,7 @@ class Database {
35
36
  this.logger.debug(`Reusing existing KnexJs configuration`);
36
37
  }
37
38
  this.knexHandle = knexHandles[cfgKey];
39
+ this.dbType = props.dbType || props.knexConfig?.client || '';
38
40
  this.dbSchema = props.dbSchema || '';
39
41
  this.trx = props.trx;
40
42
  }
@@ -61,6 +63,9 @@ class Database {
61
63
  return (trx ? trx : this.knexHandle).transaction(resolve);
62
64
  });
63
65
  }
66
+ getDbType() {
67
+ return this.dbType;
68
+ }
64
69
  getSchema() {
65
70
  return this.dbSchema;
66
71
  }
@@ -179,5 +184,12 @@ class Database {
179
184
  sortBy: sortByToUse,
180
185
  };
181
186
  }
187
+ static destroyHandle(props) {
188
+ const cfgKey = buildKey({ connection: props.knexConfig.connection, dbSchema: props.dbSchema });
189
+ if (knexHandles[cfgKey]) {
190
+ knexHandles[cfgKey].destroy();
191
+ delete knexHandles[cfgKey];
192
+ }
193
+ }
182
194
  }
183
195
  exports.Database = Database;
@@ -49,7 +49,7 @@ exports.createApiContext = createApiContext;
49
49
  * @returns {object} A context object with all available cores
50
50
  */
51
51
  const createContextDefault = async (args) => {
52
- const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
52
+ const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
53
53
  const headers = req.headers || { noHeadersSetup: true };
54
54
  const cookies = req.cookies || { noCookiesSetup: true };
55
55
  const authorization = (headers[constants_1.HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
@@ -70,6 +70,7 @@ const createContextDefault = async (args) => {
70
70
  const db = inDb
71
71
  ? inDb
72
72
  : new Database_1.Database({
73
+ dbType: dbType || knexConfig.client || '',
73
74
  knexConfig,
74
75
  dbSchema,
75
76
  logger,
@@ -1,10 +1,11 @@
1
1
  import { DateTimeHelpers, Logger } from '@sdflc/utils';
2
+ import { DataCache } from './DataCache';
2
3
  import { ApiContext, BaseGatewayPropsInterface, BuildListQueryArgsInterface, CacheInterface, ListArgsInterface, LoaderInterface } from './interfaces';
3
4
  import { Database } from './Database';
4
5
  declare class BaseGateway {
5
6
  protected config: BaseGatewayPropsInterface;
6
7
  protected logger: Logger;
7
- protected loader: any;
8
+ protected loader: LoaderInterface | DataCache;
8
9
  protected dateTime: DateTimeHelpers;
9
10
  protected dateTimeNow: Date;
10
11
  constructor(props: BaseGatewayPropsInterface);
@@ -12,7 +13,12 @@ declare class BaseGateway {
12
13
  setConfigPart(props: BaseGatewayPropsInterface): this;
13
14
  setLoader(loader: LoaderInterface): this;
14
15
  setLoaderConfig(config: CacheInterface): this;
15
- generateId(args?: any): Promise<string>;
16
+ /**
17
+ * Generates object's ID
18
+ * @param object use them when overriding the generate method and you may need data from an object
19
+ * @returns unique ID, by default it is UUID v4
20
+ */
21
+ generateId(object?: any): Promise<string>;
16
22
  onListFilter(query: any, filterParams: any): Promise<void>;
17
23
  onUpdateFilter(query: any, filterParams: any): Promise<number>;
18
24
  onRemoveFilter(query: any, filterParams: any): Promise<number>;
@@ -20,6 +26,7 @@ declare class BaseGateway {
20
26
  transformOnUpdate(params: any, where?: any): Promise<any>;
21
27
  transformOnSet(params: any): Promise<any>;
22
28
  transformOnRemove(args?: any): Promise<any>;
29
+ protected transformOnOut(item: any): any;
23
30
  getRequestId(): string;
24
31
  getContext(): ApiContext;
25
32
  getGateways(): any;
@@ -44,7 +44,12 @@ class BaseGateway {
44
44
  this.loader = new DataCache({ ...this.config, ...config });
45
45
  return this;
46
46
  }
47
- async generateId(args) {
47
+ /**
48
+ * Generates object's ID
49
+ * @param object use them when overriding the generate method and you may need data from an object
50
+ * @returns unique ID, by default it is UUID v4
51
+ */
52
+ async generateId(object) {
48
53
  return v4();
49
54
  }
50
55
  async onListFilter(query, filterParams) {
@@ -69,7 +74,9 @@ class BaseGateway {
69
74
  query.whereIn(idField.includes('.') ? `${idField}` : `${table}.${idField}`, castArray(filterParams?.[idField]));
70
75
  }
71
76
  if (fieldForKeyword && filterParams.keyword) {
72
- query.whereRaw(`${fieldForKeyword} ILIKE ?`, `%${filterParams.keyword}%`);
77
+ // const opLike = this.getDb().getDbType() === 'pg' ? 'ILIKE' : 'LIKE';
78
+ // query.whereRaw(`?? ${opLike} ?`, [fieldForKeyword, `%${filterParams.keyword}%`]);
79
+ query.whereILike(fieldForKeyword, `%${filterParams.keyword}%`);
73
80
  }
74
81
  if (filterByUserField) {
75
82
  query.where({ [filterByUserField]: this.getContext().userId });
@@ -243,6 +250,9 @@ class BaseGateway {
243
250
  }
244
251
  return obj;
245
252
  }
253
+ transformOnOut(item) {
254
+ return item;
255
+ }
246
256
  getRequestId() {
247
257
  return this.config.context.requestId;
248
258
  }
@@ -273,7 +283,7 @@ class BaseGateway {
273
283
  async buildListQuery(args) {
274
284
  const { fieldsToUse } = args || {};
275
285
  const query = this.getBuilder();
276
- query.select(fieldsToUse);
286
+ query.select(fieldsToUse || '*');
277
287
  return { query };
278
288
  }
279
289
  async list(args) {
@@ -294,7 +304,7 @@ class BaseGateway {
294
304
  }
295
305
  const items = await query;
296
306
  const result = shouldUseCache ? await this.getMany(items.map((row) => row.id)) : items;
297
- return result;
307
+ return result.map((item) => this.transformOnOut(item));
298
308
  }
299
309
  async create(args) {
300
310
  const objects = castArray(args);
@@ -313,7 +323,7 @@ class BaseGateway {
313
323
  const items = await this.getBuilder().insert(chunks[idx]).returning(this.config.returnFields);
314
324
  result.push(...items);
315
325
  }
316
- return result;
326
+ return result.map((item) => this.transformOnOut(item));
317
327
  }
318
328
  async update(where, params) {
319
329
  const object = await this.transformOnUpdate(params, where);
@@ -331,7 +341,7 @@ class BaseGateway {
331
341
  }
332
342
  });
333
343
  }
334
- return items;
344
+ return items.map((item) => this.transformOnOut(item));
335
345
  }
336
346
  async updateMany(params) {
337
347
  if (!Array.isArray(params)) {
@@ -351,7 +361,7 @@ class BaseGateway {
351
361
  }
352
362
  });
353
363
  }
354
- return results;
364
+ return results.map((item) => this.transformOnOut(item));
355
365
  }
356
366
  async increment(where, params) {
357
367
  const object = await this.transformOnUpdate(params, where);
@@ -369,7 +379,7 @@ class BaseGateway {
369
379
  }
370
380
  });
371
381
  }
372
- return items;
382
+ return items.map((item) => this.transformOnOut(item));
373
383
  }
374
384
  async decrement(where, params) {
375
385
  const object = await this.transformOnUpdate(params, where);
@@ -387,7 +397,7 @@ class BaseGateway {
387
397
  }
388
398
  });
389
399
  }
390
- return items;
400
+ return items.map((item) => this.transformOnOut(item));
391
401
  }
392
402
  /**
393
403
  * Inserts or updates data in the database.
@@ -430,7 +440,7 @@ class BaseGateway {
430
440
  .merge(pullAll(fields, skipFields));
431
441
  result.push(...items);
432
442
  }
433
- return result;
443
+ return result.map((item) => this.transformOnOut(item));
434
444
  }
435
445
  async remove(where) {
436
446
  const { hardRemove, hasRemovedAt } = this.config || {};
@@ -455,7 +465,7 @@ class BaseGateway {
455
465
  }
456
466
  });
457
467
  }
458
- return items;
468
+ return items.map((item) => this.transformOnOut(item));
459
469
  }
460
470
  }
461
471
  export { BaseGateway };
@@ -1,6 +1,7 @@
1
1
  import { DatabaseOptions, DatabaseReadInterface } from './interfaces';
2
2
  declare class Database {
3
3
  private trx;
4
+ private dbType;
4
5
  private knexHandle;
5
6
  private dbSchema;
6
7
  private logger;
@@ -8,6 +9,7 @@ declare class Database {
8
9
  destroy(): void;
9
10
  isDbError(ex: any): any[];
10
11
  createTransaction(trx: any): Promise<unknown>;
12
+ getDbType(): string;
11
13
  getSchema(): string;
12
14
  getBuilder(arg: any): any;
13
15
  raw(query: string, bindings?: any): any;
@@ -29,5 +31,6 @@ declare class Database {
29
31
  offset: number;
30
32
  sortBy: any[] | null;
31
33
  };
34
+ static destroyHandle(props: DatabaseOptions): void;
32
35
  }
33
36
  export { Database };
@@ -10,6 +10,7 @@ const buildKey = (args) => {
10
10
  };
11
11
  class Database {
12
12
  trx = null;
13
+ dbType = '';
13
14
  knexHandle = null;
14
15
  dbSchema = '';
15
16
  logger = new Logger({ level: LoggerLevels.ERROR });
@@ -29,6 +30,7 @@ class Database {
29
30
  this.logger.debug(`Reusing existing KnexJs configuration`);
30
31
  }
31
32
  this.knexHandle = knexHandles[cfgKey];
33
+ this.dbType = props.dbType || props.knexConfig?.client || '';
32
34
  this.dbSchema = props.dbSchema || '';
33
35
  this.trx = props.trx;
34
36
  }
@@ -55,6 +57,9 @@ class Database {
55
57
  return (trx ? trx : this.knexHandle).transaction(resolve);
56
58
  });
57
59
  }
60
+ getDbType() {
61
+ return this.dbType;
62
+ }
58
63
  getSchema() {
59
64
  return this.dbSchema;
60
65
  }
@@ -173,5 +178,12 @@ class Database {
173
178
  sortBy: sortByToUse,
174
179
  };
175
180
  }
181
+ static destroyHandle(props) {
182
+ const cfgKey = buildKey({ connection: props.knexConfig.connection, dbSchema: props.dbSchema });
183
+ if (knexHandles[cfgKey]) {
184
+ knexHandles[cfgKey].destroy();
185
+ delete knexHandles[cfgKey];
186
+ }
187
+ }
176
188
  }
177
189
  export { Database };
@@ -42,7 +42,7 @@ export const createApiContext = async (args) => {
42
42
  * @returns {object} A context object with all available cores
43
43
  */
44
44
  export const createContextDefault = async (args) => {
45
- const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
45
+ const { knexConfig, isProduction, logger, doAuth, spaceGw, interserviceApiKey, jwtSecret, verifyTokenArgs, dbType, dbSchema, cores, gateways, req, res, extendContext, getCoreContext, getGatewayContext, authorizationToken, db: inDb, } = args || {};
46
46
  const headers = req.headers || { noHeadersSetup: true };
47
47
  const cookies = req.cookies || { noCookiesSetup: true };
48
48
  const authorization = (headers[HEADERS.AUTHORIZATION] || authorizationToken || '').replace('Bearer ', '');
@@ -63,6 +63,7 @@ export const createContextDefault = async (args) => {
63
63
  const db = inDb
64
64
  ? inDb
65
65
  : new Database({
66
+ dbType: dbType || knexConfig.client || '',
66
67
  knexConfig,
67
68
  dbSchema,
68
69
  logger,
@@ -7,6 +7,10 @@ export interface DatabaseOptions {
7
7
  * Knex configuration object
8
8
  */
9
9
  knexConfig: any;
10
+ /**
11
+ * Database type: pg, msql, etc
12
+ */
13
+ dbType: string;
10
14
  /**
11
15
  * Name of database schema
12
16
  */
@@ -1,4 +1,5 @@
1
1
  export interface LoaderInterface {
2
2
  load(id: any): any;
3
3
  loadMany(id: any): any;
4
+ clear(key: any | any[]): void;
4
5
  }
@@ -7,6 +7,10 @@ export interface DatabaseOptions {
7
7
  * Knex configuration object
8
8
  */
9
9
  knexConfig: any;
10
+ /**
11
+ * Database type: pg, msql, etc
12
+ */
13
+ dbType: string;
10
14
  /**
11
15
  * Name of database schema
12
16
  */
@@ -1,4 +1,5 @@
1
1
  export interface LoaderInterface {
2
2
  load(id: any): any;
3
3
  loadMany(id: any): any;
4
+ clear(key: any | any[]): void;
4
5
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdflc/backend-helpers",
3
- "version": "1.0.100",
3
+ "version": "1.0.101",
4
4
  "description": "Set of helper functions and classes to simplify building backend apps within @sdflc ecosystem",
5
5
  "type": "commonjs",
6
6
  "exports": {