taon 21.0.89 → 21.0.91

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 (65) hide show
  1. package/VERIFIED-BUILD-DATA.jsonc +5 -0
  2. package/bin/taon +5 -5
  3. package/bin/taon-debug +5 -5
  4. package/bin/taon-debug-brk +4 -4
  5. package/browser/fesm2022/taon-browser.mjs +1097 -1190
  6. package/browser/fesm2022/taon-browser.mjs.map +1 -1
  7. package/browser/package.json +1 -1
  8. package/browser/types/taon-browser.d.ts +261 -256
  9. package/browser-prod/fesm2022/taon-browser-prod.mjs +1098 -1191
  10. package/browser-prod/fesm2022/taon-browser-prod.mjs.map +1 -1
  11. package/browser-prod/package.json +1 -1
  12. package/browser-prod/types/taon-browser-prod.d.ts +259 -254
  13. package/icon-menu-taon.svg +15 -15
  14. package/lib/base-classes/base-context.js +1 -2
  15. package/lib/base-classes/base-context.js.map +1 -1
  16. package/lib/build-info._auto-generated_.d.ts +1 -1
  17. package/lib/build-info._auto-generated_.js +1 -1
  18. package/lib/create-context.js +6 -0
  19. package/lib/create-context.js.map +1 -1
  20. package/lib/endpoint-context.d.ts +7 -1
  21. package/lib/endpoint-context.js +18 -1
  22. package/lib/endpoint-context.js.map +1 -1
  23. package/lib/package.json +1 -1
  24. package/lib/realtime/realtime-client.js +20 -9
  25. package/lib/realtime/realtime-client.js.map +1 -1
  26. package/lib/realtime/realtime-core.js +9 -4
  27. package/lib/realtime/realtime-core.js.map +1 -1
  28. package/lib/realtime/realtime-server.js +8 -2
  29. package/lib/realtime/realtime-server.js.map +1 -1
  30. package/lib/ui/index.js +2 -2
  31. package/lib/ui/taon-admin-mode-configuration/index.js +2 -2
  32. package/lib-prod/base-classes/base-context.js +1 -2
  33. package/lib-prod/base-classes/base-context.js.map +1 -1
  34. package/lib-prod/base-classes/base-controller.js.map +1 -1
  35. package/lib-prod/build-info._auto-generated_.d.ts +1 -1
  36. package/lib-prod/build-info._auto-generated_.js +1 -1
  37. package/lib-prod/create-context.js +6 -0
  38. package/lib-prod/create-context.js.map +1 -1
  39. package/lib-prod/decorators/http/http-methods-decorators.js.map +1 -1
  40. package/lib-prod/endpoint-context-storage.js.map +1 -1
  41. package/lib-prod/endpoint-context.d.ts +7 -1
  42. package/lib-prod/endpoint-context.js +18 -1
  43. package/lib-prod/endpoint-context.js.map +1 -1
  44. package/lib-prod/helpers/class-helpers.js.map +1 -1
  45. package/lib-prod/index.js.map +1 -1
  46. package/lib-prod/package.json +1 -1
  47. package/lib-prod/realtime/realtime-client.js +20 -9
  48. package/lib-prod/realtime/realtime-client.js.map +1 -1
  49. package/lib-prod/realtime/realtime-core.js +9 -4
  50. package/lib-prod/realtime/realtime-core.js.map +1 -1
  51. package/lib-prod/realtime/realtime-server.js +8 -2
  52. package/lib-prod/realtime/realtime-server.js.map +1 -1
  53. package/lib-prod/ui/index.d.ts +1 -1
  54. package/lib-prod/ui/index.js +1 -1
  55. package/lib-prod/ui/taon-admin-mode-configuration/index.d.ts +1 -1
  56. package/lib-prod/ui/taon-admin-mode-configuration/index.js +1 -1
  57. package/package.json +1 -1
  58. package/websql/fesm2022/taon-websql.mjs +835 -1024
  59. package/websql/fesm2022/taon-websql.mjs.map +1 -1
  60. package/websql/package.json +1 -1
  61. package/websql/types/taon-websql.d.ts +261 -256
  62. package/websql-prod/fesm2022/taon-websql-prod.mjs +837 -1025
  63. package/websql-prod/fesm2022/taon-websql-prod.mjs.map +1 -1
  64. package/websql-prod/package.json +1 -1
  65. package/websql-prod/types/taon-websql-prod.d.ts +259 -254
@@ -1,15 +1,15 @@
1
1
  import 'reflect-metadata';
2
- import { ___NS__merge, ___NS__cloneDeep, ___NS__camelCase, ___NS__isUndefined, ___NS__isArray, ___NS__isFunction, ___NS__isNull, CoreModels__NS__ClassNameStaticProperty, CoreModels__NS__OrignalClassKey, ___NS__isObject, ___NS__isRegExp, ___NS__isBuffer, ___NS__isArrayBuffer, ___NS__isDate, ___NS__isString, Utils__NS__uniqArray, ___NS__uniq, UtilsMigrations__NS__isValidTimestamp, Helpers__NS__throwError, UtilsMigrations__NS__getTimestampFromClassName, ___NS__times, ___NS__first, Helpers__NS__logInfo, UtilsOs__NS__isWebSQL, UtilsOs__NS__isElectron, Helpers__NS__error, UtilsOs__NS__isRunningInDocker, ___NS__isBoolean, ___NS__isNil, ___NS__set, Helpers__NS__info, Helpers__NS__warn, ___NS__slice, ___NS__last, UtilsOs__NS__isNode, UtilsOs__NS__isBrowser, ___NS__startCase, crossPlatformPath, Helpers__NS__isBlob, Helpers__NS__runSyncOrAsync, config, CoreModels__NS__SPECIAL_APP_READY_MESSAGE, UtilsOs__NS__isRunningInCliMode, Helpers__NS__log, ___NS__isNumber, UtilsTerminal__NS__waitMilliseconds, CoreModels__NS__TaonHttpErrorCustomProp, ___NS__lowerFirst } from 'tnp-core/websql-prod';
2
+ import { ___NS__merge, ___NS__cloneDeep, ___NS__camelCase, ___NS__isUndefined, ___NS__isArray, ___NS__isFunction, ___NS__isNull, CoreModels__NS__ClassNameStaticProperty, CoreModels__NS__OrignalClassKey, ___NS__isObject, ___NS__isRegExp, ___NS__isBuffer, ___NS__isArrayBuffer, ___NS__isDate, ___NS__isString, Utils__NS__uniqArray, ___NS__uniq, UtilsMigrations__NS__isValidTimestamp, Helpers__NS__throwError, UtilsMigrations__NS__getTimestampFromClassName, ___NS__times, ___NS__first, Helpers__NS__logInfo, UtilsOs__NS__isWebSQL, UtilsOs__NS__isElectron, Helpers__NS__error, UtilsOs__NS__isRunningInDocker, ___NS__isBoolean, ___NS__isNil, ___NS__set, Helpers__NS__info, Helpers__NS__warn, ___NS__slice, ___NS__last, UtilsOs__NS__isNode, UtilsOs__NS__isBrowser, ___NS__startCase, crossPlatformPath, Helpers__NS__isBlob, Helpers__NS__runSyncOrAsync, config, CoreModels__NS__SPECIAL_APP_READY_MESSAGE, UtilsOs__NS__isRunningInCliMode, Helpers__NS__log, ___NS__isNumber, ___NS__lowerFirst, UtilsTerminal__NS__waitMilliseconds, CoreModels__NS__TaonHttpErrorCustomProp } from 'tnp-core/websql-prod';
3
3
  import axios from 'axios';
4
4
  import { JSON10 } from 'json10/websql-prod';
5
5
  import { walk } from 'lodash-walk-object/websql-prod';
6
- import { RestResponseWrapper, Resource__NS__globalInterceptors, Resource__NS__methodsInterceptors, HttpResponse, RestHeaders, Resource__NS__create, decodeMappingForHeaderJson, Resource__NS__Cookies, DefaultMapping, DefaultModel, HttpResponseError } from 'ng2-rest/websql-prod';
6
+ import { RestResponseWrapper, Resource__NS__globalInterceptors, Resource__NS__methodsInterceptors, HttpResponse, RestHeaders, Resource__NS__create, decodeMappingForHeaderJson, Resource__NS__Cookies, HttpResponseError, DefaultMapping, DefaultModel } from 'ng2-rest/websql-prod';
7
7
  import { Observable, Subject, from } from 'rxjs';
8
- import { Table, TableIndex, EventSubscriber, Entity, DataSource, Column, PrimaryGeneratedColumn, VersionColumn, CreateDateColumn } from 'taon-typeorm/websql-prod';
8
+ import { Table, TableIndex, EventSubscriber, Entity, DataSource, Column, PrimaryGeneratedColumn, VersionColumn } from 'taon-typeorm/websql-prod';
9
9
  export { AfterInsert, AfterLoad, AfterRecover, AfterRemove, AfterSoftRemove, AfterUpdate, BeforeInsert, BeforeRecover, BeforeRemove, BeforeSoftRemove, BeforeUpdate, Column, Connection, CreateDateColumn, Column as CustomColumn, DeleteDateColumn, Generated, Generated as GeneratedColumn, Index, JoinColumn, JoinTable, ManyToMany, ManyToOne, OneToMany, OneToOne, PrimaryColumn, PrimaryGeneratedColumn, Repository, TreeChildren, TreeParent, UpdateDateColumn, VersionColumn, VirtualColumn } from 'taon-typeorm/websql-prod';
10
10
  import * as i0 from '@angular/core';
11
11
  import { InjectionToken, Injectable, signal, inject as inject$1, PLATFORM_ID, ViewContainerRef, ViewChild, Component } from '@angular/core';
12
- import { CLASS__NS__getName, CLASS__NS__setName, CLASS__NS__getBy } from 'typescript-class-helpers/websql-prod';
12
+ import { CLASS__NS__getName, CLASS__NS__getBy, CLASS__NS__setName } from 'typescript-class-helpers/websql-prod';
13
13
  import * as JSON5 from 'json5';
14
14
  import { io } from 'socket.io-client';
15
15
  import { TaonStor__NS__inLocalstorage } from 'taon-storage/websql-prod';
@@ -1232,18 +1232,29 @@ class RealtimeClient {
1232
1232
  realtime: this.core.pathFor(Symbols__NS__REALTIME.NAMESPACE(this.core.ctx.contextName)),
1233
1233
  };
1234
1234
  // console.log('[browser] nspPath', nspPath);
1235
- if (this.core.ctx.config.frontendHost &&
1236
- this.core.ctx.config.frontendHost !== '' &&
1237
- this.core.ctx.isRunningInsideDocker) {
1235
+ if (this.core.ctx.isRemoteHost) {
1236
+ // NEED for remote host
1237
+ const nodeClientHostOrigin = this.core.ctx.host;
1238
1238
  this.core.ctx.logRealtime &&
1239
- Helpers__NS__logInfo(`[${this.core.ctx.contextName}] USING FRONTEND HOST` +
1240
- ` ${this.core.ctx.config.frontendHost} FOR REALTIME`);
1241
- nspPath.global = new URL(`${this.core.ctx.frontendHostUri.origin}${nspPath.global.pathname}`);
1242
- nspPath.realtime = new URL(`${this.core.ctx.frontendHostUri.origin}${nspPath.realtime.pathname}`);
1239
+ Helpers__NS__logInfo(`[${this.core.ctx.contextName}] USING REMOTE FRONTEND HOST` +
1240
+ ` ${nodeClientHostOrigin} FOR REMOTE REALTIME`);
1241
+ nspPath.global = new URL(`${nodeClientHostOrigin}${nspPath.global.pathname}`);
1242
+ nspPath.realtime = new URL(`${nodeClientHostOrigin}${nspPath.realtime.pathname}`);
1243
1243
  }
1244
1244
  else {
1245
- this.core.ctx.logRealtime &&
1246
- Helpers__NS__logInfo(`[${this.core.ctx.contextName}] Not using frontend host for realtime`);
1245
+ if (this.core.ctx.config.frontendHost &&
1246
+ this.core.ctx.config.frontendHost !== '' &&
1247
+ this.core.ctx.isRunningInsideDocker) {
1248
+ this.core.ctx.logRealtime &&
1249
+ Helpers__NS__logInfo(`[${this.core.ctx.contextName}] USING FRONTEND HOST` +
1250
+ ` ${this.core.ctx.config.frontendHost} FOR REALTIME`);
1251
+ nspPath.global = new URL(`${this.core.ctx.frontendHostUri.origin}${nspPath.global.pathname}`);
1252
+ nspPath.realtime = new URL(`${this.core.ctx.frontendHostUri.origin}${nspPath.realtime.pathname}`);
1253
+ }
1254
+ else {
1255
+ this.core.ctx.logRealtime &&
1256
+ Helpers__NS__logInfo(`[${this.core.ctx.contextName}] Not using frontend host for realtime`);
1257
+ }
1247
1258
  }
1248
1259
  this.core.ctx.logRealtime &&
1249
1260
  console.info('[CLIENT] NAMESPACE GLOBAL ', nspPath.global.href + ` host: ${this.core.ctx.host}`);
@@ -1413,7 +1424,7 @@ class RealtimeServer {
1413
1424
  constructor(core) {
1414
1425
  this.core = core;
1415
1426
  this.core = core;
1416
- if (core.ctx.disabledRealtime || this.core.ctx.isRemoteHost) {
1427
+ if (core.ctx.disabledRealtime) {
1417
1428
  return;
1418
1429
  }
1419
1430
  //#region @websql
@@ -1524,7 +1535,7 @@ class RealtimeServer {
1524
1535
  // console.info('__triger entity changes');
1525
1536
  //#region @websql
1526
1537
  let roomName;
1527
- if (this.core.ctx.disabledRealtime || this.core.ctx.isRemoteHost) {
1538
+ if (this.core.ctx.disabledRealtime) {
1528
1539
  return;
1529
1540
  }
1530
1541
  if (customEvent) {
@@ -1548,6 +1559,12 @@ class RealtimeServer {
1548
1559
  ? Symbols__NS__REALTIME.ROOM_NAME_UPDATE_ENTITY_PROPERTY(this.core.ctx.contextName, ClassHelpers__NS__getName(entityFn), property, valueOfUniqueProperty)
1549
1560
  : Symbols__NS__REALTIME.ROOM_NAME_UPDATE_ENTITY(this.core.ctx.contextName, ClassHelpers__NS__getName(entityFn), valueOfUniqueProperty);
1550
1561
  }
1562
+ if (this.core.ctx.isRemoteHost) {
1563
+ // USE REMOTE HOST
1564
+ // this allows me to trigger event from other remote server!
1565
+ this.core.socketFE.emit(customEvent ? customEvent : roomName, customEvent ? customEventData : '');
1566
+ return;
1567
+ }
1551
1568
  this.core.socketBE.in(roomName).emit(roomName, // roomName == eventName in room na
1552
1569
  customEvent ? customEventData : '');
1553
1570
  //#endregion
@@ -2257,10 +2274,15 @@ class RealtimeCore {
2257
2274
  ];
2258
2275
  this.ctx = ctx;
2259
2276
  this.strategy = this.resolveStrategy();
2260
- // this.ctx.logRealtime &&
2261
- // console.log(`
2262
- // [ctx=${this.ctx.contextName}] realtime strategy: ${this.strategy}, context type: ${this.ctx.contextType}
2263
- // `);
2277
+ this.ctx.logRealtime &&
2278
+ console.log(`
2279
+
2280
+ [ctx=${this.ctx.contextName}]
2281
+ mode = ${this.ctx.mode}
2282
+ realtime strategy = ${this.strategy}
2283
+ context type = ${this.ctx.contextType}
2284
+
2285
+ `);
2264
2286
  if (UtilsOs__NS__isWebSQL) {
2265
2287
  this.server = new RealtimeServer(this);
2266
2288
  // console.log('DONE INITING SERVER');
@@ -2488,9 +2510,23 @@ class EndpointContext {
2488
2510
  get isRunOrRevertOnlyMigrationAppStart() {
2489
2511
  return !!(this.onlyMigrationRun || this.onlyMigrationRevertToTimestamp);
2490
2512
  }
2513
+ get realtime() {
2514
+ if (!this._realtime) {
2515
+ throw new Error(`Please initialize context before accessing
2516
+ .realtime.client or realtime.server properties.
2517
+
2518
+ `);
2519
+ }
2520
+ return this._realtime;
2521
+ }
2522
+ set realtime(v) {
2523
+ this._realtime = v;
2524
+ }
2525
+ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
2491
2526
  get realtimeClient() {
2492
2527
  return this.realtime.client;
2493
2528
  }
2529
+ // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
2494
2530
  get realtimeServer() {
2495
2531
  return this.realtime.server;
2496
2532
  }
@@ -3632,6 +3668,9 @@ class EndpointContext {
3632
3668
  }
3633
3669
  //#endregion
3634
3670
  //#region methods & getters / init subscribers
3671
+ /**
3672
+ * init typeorm subscribers
3673
+ */
3635
3674
  async initSubscribers() {
3636
3675
  //#region @websqlFunc
3637
3676
  if (this.isRemoteHost) {
@@ -5181,9 +5220,15 @@ const createContextFn = (configFn, cloneOptions) => {
5181
5220
  get realtime() {
5182
5221
  return {
5183
5222
  get client() {
5223
+ if (!endpointContextRef) {
5224
+ throw new Error(`Please .initialize() context before using <context>.realtime.client.<anything> `);
5225
+ }
5184
5226
  return endpointContextRef.realtimeClient;
5185
5227
  },
5186
5228
  get server() {
5229
+ if (!endpointContextRef) {
5230
+ throw new Error(`Please .initialize() context before using <context>.realtime.server.<anything> `);
5231
+ }
5187
5232
  return endpointContextRef.realtimeServer;
5188
5233
  },
5189
5234
  };
@@ -5790,287 +5835,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.0.9", ngImpor
5790
5835
  type: Injectable
5791
5836
  }], ctorParameters: () => [] });
5792
5837
 
5793
- /**
5794
- * Entity decorator
5795
- */
5796
- function TaonEntity(options) {
5797
- return function (constructor) {
5798
- options = options || {};
5799
- options.uniqueKeyProp = options.uniqueKeyProp || 'id';
5800
- if (!options.className) {
5801
- const nameForClass = constructor?.name || 'AnyClass';
5802
- throw `Please define 'classname' property inside decorator of class '${nameForClass}':
5803
-
5804
- @TaonEntity({
5805
- className: '${nameForClass}'
5806
- })
5807
- class ${constructor?.name} {
5808
- //...
5809
-
5810
- `;
5811
- }
5812
- ClassHelpers__NS__setName(constructor, options?.className);
5813
- DefaultMapping(options?.defaultModelMapping)(constructor);
5814
- DefaultModel(options.defaultModelMapping)(constructor);
5815
- Reflect.defineMetadata(Symbols__NS__metadata.options.entity, options, constructor);
5816
- Reflect.defineMetadata(Symbols__NS__metadata.className, options?.className || constructor.name, constructor);
5817
- //#region @websql
5818
- Entity(options?.className)(constructor);
5819
- //#endregion
5820
- CLASS__NS__setName(constructor, options?.className); // TODO QUICK_FIX for ng2-rest
5821
- };
5822
- }
5823
- class TaonEntityOptions extends DecoratorAbstractOpt {
5824
- }
5825
-
5826
- var TaonGlobalStateStatus;
5827
- (function (TaonGlobalStateStatus) {
5828
- TaonGlobalStateStatus["NORMAL"] = "normal";
5829
- /**
5830
- * no new transactions allowed
5831
- * existing ones may finish
5832
- */
5833
- TaonGlobalStateStatus["DRAINING"] = "draining";
5834
- /**
5835
- * DB is readonly
5836
- * app is readonly (no writes, no side effects)
5837
- */
5838
- TaonGlobalStateStatus["READONLY"] = "readonly";
5839
- /**
5840
- * Db and app still readonly - migration in progress
5841
- */
5842
- TaonGlobalStateStatus["MIGRATING"] = "migrating";
5843
- /**
5844
- * emergency stop / maintenance mode
5845
- */
5846
- TaonGlobalStateStatus["FROZEN"] = "frozen";
5847
- })(TaonGlobalStateStatus || (TaonGlobalStateStatus = {}));
5848
- const allowedTaonGlobalStatusOrders = {
5849
- [TaonGlobalStateStatus.NORMAL]: [
5850
- TaonGlobalStateStatus.DRAINING,
5851
- TaonGlobalStateStatus.FROZEN,
5852
- ],
5853
- [TaonGlobalStateStatus.DRAINING]: [
5854
- TaonGlobalStateStatus.READONLY,
5855
- TaonGlobalStateStatus.FROZEN,
5856
- ],
5857
- [TaonGlobalStateStatus.READONLY]: [
5858
- TaonGlobalStateStatus.MIGRATING,
5859
- TaonGlobalStateStatus.NORMAL,
5860
- TaonGlobalStateStatus.FROZEN,
5861
- ],
5862
- [TaonGlobalStateStatus.MIGRATING]: [
5863
- TaonGlobalStateStatus.READONLY
5864
- ],
5865
- [TaonGlobalStateStatus.FROZEN]: [
5866
- TaonGlobalStateStatus.READONLY,
5867
- TaonGlobalStateStatus.NORMAL,
5868
- ],
5869
- };
5870
-
5871
- const TaonGlobalStateDefaultsValues = {
5872
- description: '',
5873
- version: 0,
5874
- id: void 0,
5875
- status: TaonGlobalStateStatus.NORMAL,
5876
- };
5877
-
5878
- //#region imports
5879
- //#endregion
5880
- let TAON_GLOBAL_STATE = class TAON_GLOBAL_STATE extends TaonBaseAbstractEntity {
5881
- };
5882
- __decorate([
5883
- Column({
5884
- type: 'varchar',
5885
- length: 20,
5886
- nullable: false,
5887
- default: TaonGlobalStateDefaultsValues.status,
5888
- })
5889
- //#endregion
5890
- ,
5891
- __metadata("design:type", String)
5892
- ], TAON_GLOBAL_STATE.prototype, "status", void 0);
5893
- __decorate([
5894
- CreateDateColumn()
5895
- //#endregion
5896
- ,
5897
- __metadata("design:type", Date)
5898
- ], TAON_GLOBAL_STATE.prototype, "createdAt", void 0);
5899
- __decorate([
5900
- Column({
5901
- type: 'int',
5902
- nullable: true,
5903
- })
5904
- //#endregion
5905
- ,
5906
- __metadata("design:type", Date)
5907
- ], TAON_GLOBAL_STATE.prototype, "secondsBeforeReadonly", void 0);
5908
- TAON_GLOBAL_STATE = __decorate([
5909
- TaonEntity({
5910
- className: 'TAON_GLOBAL_STATE',
5911
- createTable: true,
5912
- })
5913
- ], TAON_GLOBAL_STATE);
5914
-
5915
- /**
5916
- * Controller decorator
5917
- */
5918
- function TaonController(options) {
5919
- return function (constructor) {
5920
- ClassHelpers__NS__setName(constructor, options?.className);
5921
- Reflect.defineMetadata(Symbols__NS__metadata.className, options?.className || constructor.name, constructor);
5922
- const cfg = ClassHelpers__NS__ensureClassConfig(constructor);
5923
- options = options || {};
5924
- cfg.className = options.className || constructor.name;
5925
- cfg.path = options.path || '';
5926
- cfg.realtime = options.realtime;
5927
- cfg.middlewares = options.middlewares;
5928
- };
5929
- }
5930
-
5931
- const metaReq = (method, path, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal) => {
5932
- const methodConfig = ClassHelpers__NS__ensureMethodConfig(target, propertyKey);
5933
- let options;
5934
- if (typeof pathOrOptions === 'object') {
5935
- options = pathOrOptions;
5936
- pathOrOptions = options.path;
5937
- pathIsGlobal = !!options.pathIsGlobal;
5938
- path = options.path;
5939
- }
5940
- else {
5941
- options = { pathOrOptions, pathIsGlobal };
5942
- }
5943
- const { overrideContentType, overrideResponseType, overrideExpressSendAsHtml, middlewares, } = options;
5944
- methodConfig.methodName = propertyKey;
5945
- methodConfig.middlewares = middlewares;
5946
- methodConfig.type = method;
5947
- if (!path) {
5948
- let paramsPathConcatedPath = '';
5949
- for (const key in methodConfig.parameters) {
5950
- if (methodConfig.parameters.hasOwnProperty(key)) {
5951
- const element = methodConfig.parameters[key];
5952
- if (element.paramType === 'Path' &&
5953
- ___NS__isString(element.paramName) &&
5954
- element.paramName.trim().length > 0) {
5955
- paramsPathConcatedPath += `/${element.paramName}/:${element.paramName}`;
5956
- }
5957
- }
5958
- }
5959
- methodConfig.path = `/${propertyKey}${paramsPathConcatedPath}`;
5960
- }
5961
- else {
5962
- methodConfig.path = path;
5963
- }
5964
- methodConfig.descriptor = descriptor;
5965
- methodConfig.global = pathIsGlobal;
5966
- methodConfig.contentType = overrideContentType;
5967
- methodConfig.responseType = overrideResponseType;
5968
- methodConfig.overrideExpressSendAsHtml = overrideExpressSendAsHtml;
5969
- };
5970
- function GET(pathOrOptions, pathIsGlobal = false) {
5971
- return function (target, propertyKey, descriptor) {
5972
- metaReq('get', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
5973
- };
5974
- }
5975
- /**
5976
- * Method for sending html website from text
5977
- * Example
5978
- *
5979
- * ```ts
5980
- * ...
5981
- * // in your taon controller
5982
- * ..Taon.Http.HTML()
5983
- * sendHtmlDummyWebsite(): Taon__NS__ResponseHtml {
5984
- * return `
5985
- <html>
5986
- <head>
5987
- <title>Dummy website</title>
5988
- </head>
5989
- <body>
5990
- <h1>This is dummy website</h1>
5991
- <p>Served as HTML string from Taon controller method</p>
5992
- </body>
5993
- </html>
5994
- * `; *
5995
- * }
5996
- * ...
5997
- * ```
5998
- */
5999
- function HTML(pathOrOptions) {
6000
- return function (target, propertyKey, descriptor) {
6001
- const opt = pathOrOptions;
6002
- opt.overrideExpressSendAsHtml = true;
6003
- metaReq('get', opt, target, propertyKey, descriptor, pathOrOptions, opt.pathIsGlobal);
6004
- };
6005
- }
6006
- function HEAD(pathOrOptions, pathIsGlobal = false) {
6007
- return function (target, propertyKey, descriptor) {
6008
- metaReq('head', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6009
- };
6010
- }
6011
- function POST(pathOrOptions, pathIsGlobal = false) {
6012
- return function (target, propertyKey, descriptor) {
6013
- metaReq('post', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6014
- };
6015
- }
6016
- function PUT(pathOrOptions, pathIsGlobal = false) {
6017
- return function (target, propertyKey, descriptor) {
6018
- metaReq('put', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6019
- };
6020
- }
6021
- function PATCH(pathOrOptions, pathIsGlobal = false) {
6022
- return function (target, propertyKey, descriptor) {
6023
- metaReq('patch', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6024
- };
6025
- }
6026
- function DELETE(pathOrOptions, pathIsGlobal = false) {
6027
- return function (target, propertyKey, descriptor) {
6028
- metaReq('delete', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6029
- };
6030
- }
6031
-
6032
- function metaParam(param, name, expire, defaultValue = undefined, target, propertyKey, parameterIndex) {
6033
- const methodCfg = ClassHelpers__NS__ensureMethodConfig(target, propertyKey);
6034
- const nameKey = name ? name : param;
6035
- // const key = name || `${param}_${parameterIndex}`;
6036
- methodCfg.parameters[nameKey] = {
6037
- index: parameterIndex,
6038
- paramName: name,
6039
- paramType: param,
6040
- defaultType: defaultValue,
6041
- expireInSeconds: expire,
6042
- };
6043
- // console.log('params updated', methodConfig);
6044
- }
6045
- /**
6046
- * @deprecated use Taon.Http.Param.Path (is more safe and cleaner)
6047
- */
6048
- function Path(name) {
6049
- return function (target, propertyKey, parameterIndex) {
6050
- metaParam('Path', name, undefined, {}, target, propertyKey, parameterIndex);
6051
- };
6052
- }
6053
- function Query(name) {
6054
- return function (target, propertyKey, parameterIndex) {
6055
- metaParam('Query', name, undefined, {}, target, propertyKey, parameterIndex);
6056
- };
6057
- }
6058
- function Cookie(name, expireInSecond = 3600) {
6059
- return function (target, propertyKey, parameterIndex) {
6060
- metaParam('Cookie', name, expireInSecond, {}, target, propertyKey, parameterIndex);
6061
- };
6062
- }
6063
- function Header(name) {
6064
- return function (target, propertyKey, parameterIndex) {
6065
- metaParam('Header', name, undefined, {}, target, propertyKey, parameterIndex);
6066
- };
6067
- }
6068
- function Body(name) {
6069
- return function (target, propertyKey, parameterIndex) {
6070
- metaParam('Body', name, undefined, {}, target, propertyKey, parameterIndex);
6071
- };
6072
- }
6073
-
6074
5838
  /**
6075
5839
  * Provider decorator
6076
5840
  */
@@ -6345,450 +6109,6 @@ TaonBaseFileUploadMiddleware = __decorate([
6345
6109
  })
6346
6110
  ], TaonBaseFileUploadMiddleware);
6347
6111
 
6348
- let TaonBaseController = class TaonBaseController extends TaonBaseInjector {
6349
- /**
6350
- * Hook that is called when taon app is inited
6351
- * (all contexts are created and inited)
6352
- */
6353
- async afterAllCtxInited(options) { }
6354
- //#region upload form data to server
6355
- uploadFormDataToServer(formData, queryParams) {
6356
- /* */
6357
- /* */
6358
- /* */
6359
- /* */
6360
- /* */
6361
- /* */
6362
- /* */
6363
- /* */
6364
- /* */
6365
- /* */
6366
- /* */
6367
- /* */
6368
- /* */
6369
- /* */
6370
- /* */
6371
- /* */
6372
- /* */
6373
- /* */
6374
- /* */
6375
- /* */
6376
- /* */
6377
- /* */
6378
- /* */
6379
- /* */
6380
- /* */
6381
- /* */
6382
- return (void 0);
6383
- }
6384
- //#endregion
6385
- //#region after file upload hook
6386
- /**
6387
- * Hook after file is uploaded
6388
- * through `uploadFormDataToServer` or `uploadLocalFileToServer`
6389
- */
6390
- afterFileUploadAction(file, queryParams) {
6391
- // empty
6392
- }
6393
- //#region upload local file to server
6394
- async uploadLocalFileToServer(absFilePath, options, queryParams) {
6395
- /* */
6396
- /* */
6397
- /* */
6398
- /* */
6399
- /* */
6400
- /* */
6401
- /* */
6402
- /* */
6403
- /* */
6404
- /* */
6405
- /* */
6406
- /* */
6407
- /* */
6408
- /* */
6409
- return (void 0);
6410
- }
6411
- //#endregion
6412
- // async check() {
6413
- // await this._waitForProperStatusChange({
6414
- // request: () => this.uploadFormDataToServer(void 0, void 0).request(),
6415
- // statusCheck: resp => resp.body.json[0].ok,
6416
- // });
6417
- // }
6418
- /**
6419
- * Easy way to wait for status change with http (1s default) pooling.
6420
- *
6421
- * example (in sub class):
6422
- * ```ts
6423
- async check() {
6424
- await this.waitForProperStatusChange({
6425
- request: () => this.uploadFormDataToServer(void 0, void 0).request(),
6426
- statusCheck: resp => resp.body.json[0].ok,
6427
- });
6428
- }
6429
- * ```
6430
- */
6431
- async _waitForProperStatusChange(options) {
6432
- const poolingInterval = options.poolingInterval || 1000;
6433
- const taonRequest = options.request;
6434
- let maxTries = options.maxTries || Number.POSITIVE_INFINITY;
6435
- let i = 0;
6436
- let httpErrorsCount = 0;
6437
- while (true) {
6438
- await UtilsTerminal__NS__waitMilliseconds(poolingInterval);
6439
- try {
6440
- const resp = await taonRequest({
6441
- reqIndexNum: i,
6442
- httpErrorsCount,
6443
- });
6444
- if (options.statusCheck && options.statusCheck(resp)) {
6445
- return;
6446
- }
6447
- }
6448
- catch (error) {
6449
- httpErrorsCount++;
6450
- if (options.loopRequestsOnBackendError) {
6451
- const isProperTaonError = error instanceof HttpResponseError &&
6452
- error.body.json[CoreModels__NS__TaonHttpErrorCustomProp];
6453
- const isHttpError = error instanceof HttpResponseError && !isProperTaonError;
6454
- const isUnknownError = !(error instanceof HttpResponseError);
6455
- const resBool = await options.loopRequestsOnBackendError({
6456
- taonError: isProperTaonError ? error : void 0,
6457
- unknownHttpError: isHttpError ? error : void 0,
6458
- unknownError: isUnknownError ? error : void 0,
6459
- reqIndexNum: i,
6460
- httpErrorsCount,
6461
- });
6462
- if (resBool) {
6463
- i++;
6464
- continue;
6465
- }
6466
- else {
6467
- return;
6468
- }
6469
- }
6470
- if (httpErrorsCount >
6471
- (options.allowedHttpErrors || Number.POSITIVE_INFINITY)) {
6472
- throw new Error(`Too many http errors (${httpErrorsCount}) for "${options.actionName}".`);
6473
- }
6474
- }
6475
- if (i++ > maxTries) {
6476
- throw new Error(`Timeout waiting for "${options.actionName}" to be finished. Waited for ${maxTries} seconds`);
6477
- }
6478
- }
6479
- }
6480
- };
6481
- __decorate([
6482
- POST({
6483
- overrideContentType: 'multipart/form-data',
6484
- middlewares: ({ parentMiddlewares }) => ({
6485
- ...parentMiddlewares,
6486
- TaonBaseFileUploadMiddleware,
6487
- }),
6488
- }),
6489
- __param(0, Body()),
6490
- __param(1, Query()),
6491
- __metadata("design:type", Function),
6492
- __metadata("design:paramtypes", [FormData, Object]),
6493
- __metadata("design:returntype", Object)
6494
- ], TaonBaseController.prototype, "uploadFormDataToServer", null);
6495
- TaonBaseController = __decorate([
6496
- TaonController({
6497
- className: 'TaonBaseController',
6498
- })
6499
- ], TaonBaseController);
6500
-
6501
- //#endregion
6502
- /**
6503
- * Please override property entityClassFn with entity class.
6504
- */
6505
- let TaonBaseCrudController = class TaonBaseCrudController extends TaonBaseController {
6506
- //#endregion
6507
- //#region init
6508
- async _() {
6509
- if (!___NS__isFunction(this.entityClassResolveFn)) {
6510
- Helpers__NS__warn(`Skipping initing CRUD controller ${ClassHelpers__NS__getName(this)} because entityClassResolveFn is not provided.`);
6511
- return;
6512
- }
6513
- let entityClassFn = this.entityClassResolveFn();
6514
- this.db = this.injectRepo(entityClassFn);
6515
- if (entityClassFn) {
6516
- const configEntity = Reflect.getMetadata(Symbols__NS__metadata.options.entity, ClassHelpers__NS__getClassFnFromObject(this));
6517
- if (configEntity?.createTable === false) {
6518
- Helpers__NS__warn(`Table for entity ${ClassHelpers__NS__getName(entityClassFn)} will not be created. Crud will not work properly.`);
6519
- }
6520
- }
6521
- else {
6522
- Helpers__NS__error(`Entity class not provided for controller ${ClassHelpers__NS__getName(this)}.
6523
-
6524
- Please provide entity as class property entityClassFn:
6525
-
6526
- class ${ClassHelpers__NS__getName(this)} extends TaonBaseCrudController<Entity> {
6527
- // ...
6528
- entityClassResolveFn = ()=> MyEntityClass;
6529
- // ...
6530
- }
6531
-
6532
- `);
6533
- }
6534
- await super._();
6535
- }
6536
- //#endregion
6537
- //#region bufferd changes
6538
- bufforedChanges(id, property, alreadyLength) {
6539
- //#region @websqlFunc
6540
- return async (request, response) => {
6541
- const model = await this.db.getBy(id);
6542
- if (model === void 0) {
6543
- return;
6544
- }
6545
- Validators__NS__preventUndefinedModel(model, id);
6546
- let value = model[property];
6547
- let result;
6548
- if (___NS__isString(value) || ___NS__isArray(value)) {
6549
- result = value.slice(alreadyLength);
6550
- }
6551
- return result;
6552
- };
6553
- //#endregion
6554
- }
6555
- //#endregion
6556
- //#region pagintation
6557
- pagination(pageNumber = 1, pageSize = 10, search = '') {
6558
- //#region @websqlFunc
6559
- return async (request, response) => {
6560
- if (this.db.repositoryExists) {
6561
- const query = {
6562
- page: pageNumber,
6563
- take: pageSize,
6564
- keyword: search,
6565
- };
6566
- // console.log({
6567
- // query
6568
- // })
6569
- const take = query.take || 10;
6570
- const page = query.page || 1;
6571
- const skip = (page - 1) * take;
6572
- const keyword = query.keyword || '';
6573
- const [result, total] = await this.db.findAndCount({
6574
- // where: { name: Like('%' + keyword + '%') },
6575
- // order: { name: "DESC" },
6576
- take: take,
6577
- skip: skip,
6578
- });
6579
- response?.setHeader(Symbols__NS__old.X_TOTAL_COUNT, total);
6580
- // const lastPage = Math.ceil(total / take);
6581
- // const nextPage = page + 1 > lastPage ? null : page + 1;
6582
- // const prevPage = page - 1 < 1 ? null : page - 1;
6583
- // console.log({
6584
- // result,
6585
- // total
6586
- // })
6587
- return result;
6588
- }
6589
- return [];
6590
- };
6591
- //#endregion
6592
- }
6593
- //#endregion
6594
- //#region get all
6595
- getAll() {
6596
- //#region @websqlFunc
6597
- return async (request, response) => {
6598
- if (this.db.repositoryExists) {
6599
- const { models, totalCount } = await this.db.getAll();
6600
- response?.setHeader(Symbols__NS__old.X_TOTAL_COUNT, totalCount);
6601
- return models;
6602
- }
6603
- return [];
6604
- };
6605
- //#endregion
6606
- }
6607
- //#endregion
6608
- //#region get by id
6609
- getBy(id) {
6610
- //#region @websqlFunc
6611
- return async () => {
6612
- const model = await this.db.getBy(id);
6613
- return model;
6614
- };
6615
- //#endregion
6616
- }
6617
- //#endregion
6618
- //#region update by id
6619
- updateById(id, item) {
6620
- //#region @websqlFunc
6621
- return async () => {
6622
- const model = await this.db.updateById(id, item);
6623
- return model;
6624
- };
6625
- //#endregion
6626
- }
6627
- //#endregion
6628
- //#region patch by id
6629
- patchById(id, item) {
6630
- //#region @websqlFunc
6631
- return async () => {
6632
- const model = await this.db.updateById(id, item);
6633
- return model;
6634
- };
6635
- //#endregion
6636
- }
6637
- //#endregion
6638
- //#region bulk update
6639
- bulkUpdate(items) {
6640
- //#region @websqlFunc
6641
- return async () => {
6642
- if (!Array.isArray(items) || items?.length === 0) {
6643
- return [];
6644
- }
6645
- const { models } = await this.db.bulkUpdate(items);
6646
- return models;
6647
- };
6648
- //#endregion
6649
- }
6650
- //#endregion
6651
- //#region delete by id
6652
- deleteById(id) {
6653
- //#region @websqlFunc
6654
- return async () => {
6655
- const model = await this.db.deleteById(id);
6656
- return model;
6657
- };
6658
- //#endregion
6659
- }
6660
- //#endregion
6661
- //#region bulk delete
6662
- bulkDelete(ids) {
6663
- //#region @websqlFunc
6664
- return async () => {
6665
- const models = await this.db.bulkDelete(ids);
6666
- return models;
6667
- };
6668
- //#endregion
6669
- }
6670
- //#endregion
6671
- //#region bulk delete
6672
- clearTable() {
6673
- //#region @websqlFunc
6674
- return async () => {
6675
- await this.db.clear();
6676
- };
6677
- //#endregion
6678
- }
6679
- //#endregion
6680
- //#region create
6681
- save(item) {
6682
- //#region @websqlFunc
6683
- return async () => {
6684
- const model = await this.db.save(item);
6685
- return model;
6686
- };
6687
- //#endregion
6688
- }
6689
- //#endregion
6690
- //#region bulk create
6691
- bulkCreate(items) {
6692
- //#region @websqlFunc
6693
- return async () => {
6694
- const models = await this.db.bulkCreate(items);
6695
- return models;
6696
- };
6697
- //#endregion
6698
- }
6699
- };
6700
- __decorate([
6701
- GET(),
6702
- __param(0, Query(`id`)),
6703
- __param(1, Query(`property`)),
6704
- __param(2, Query('alreadyLength')),
6705
- __metadata("design:type", Function),
6706
- __metadata("design:paramtypes", [Object, String, Number]),
6707
- __metadata("design:returntype", Object)
6708
- ], TaonBaseCrudController.prototype, "bufforedChanges", null);
6709
- __decorate([
6710
- GET(),
6711
- __param(0, Query('pageNumber')),
6712
- __param(1, Query('pageSize')),
6713
- __param(2, Query('search')),
6714
- __metadata("design:type", Function),
6715
- __metadata("design:paramtypes", [Number, Number, String]),
6716
- __metadata("design:returntype", Object)
6717
- ], TaonBaseCrudController.prototype, "pagination", null);
6718
- __decorate([
6719
- GET(),
6720
- __metadata("design:type", Function),
6721
- __metadata("design:paramtypes", []),
6722
- __metadata("design:returntype", Object)
6723
- ], TaonBaseCrudController.prototype, "getAll", null);
6724
- __decorate([
6725
- GET(),
6726
- __param(0, Query(`id`)),
6727
- __metadata("design:type", Function),
6728
- __metadata("design:paramtypes", [Object]),
6729
- __metadata("design:returntype", Object)
6730
- ], TaonBaseCrudController.prototype, "getBy", null);
6731
- __decorate([
6732
- PUT(),
6733
- __param(0, Query(`id`)),
6734
- __param(1, Body()),
6735
- __metadata("design:type", Function),
6736
- __metadata("design:paramtypes", [Object, Object]),
6737
- __metadata("design:returntype", Object)
6738
- ], TaonBaseCrudController.prototype, "updateById", null);
6739
- __decorate([
6740
- PATCH(),
6741
- __param(0, Query(`id`)),
6742
- __param(1, Body()),
6743
- __metadata("design:type", Function),
6744
- __metadata("design:paramtypes", [Object, Object]),
6745
- __metadata("design:returntype", Object)
6746
- ], TaonBaseCrudController.prototype, "patchById", null);
6747
- __decorate([
6748
- PUT(),
6749
- __param(0, Body()),
6750
- __metadata("design:type", Function),
6751
- __metadata("design:paramtypes", [Array]),
6752
- __metadata("design:returntype", Object)
6753
- ], TaonBaseCrudController.prototype, "bulkUpdate", null);
6754
- __decorate([
6755
- DELETE(),
6756
- __param(0, Query(`id`)),
6757
- __metadata("design:type", Function),
6758
- __metadata("design:paramtypes", [Object]),
6759
- __metadata("design:returntype", Object)
6760
- ], TaonBaseCrudController.prototype, "deleteById", null);
6761
- __decorate([
6762
- DELETE(),
6763
- __param(0, Query(`ids`)),
6764
- __metadata("design:type", Function),
6765
- __metadata("design:paramtypes", [Array]),
6766
- __metadata("design:returntype", Object)
6767
- ], TaonBaseCrudController.prototype, "bulkDelete", null);
6768
- __decorate([
6769
- DELETE(),
6770
- __metadata("design:type", Function),
6771
- __metadata("design:paramtypes", []),
6772
- __metadata("design:returntype", Object)
6773
- ], TaonBaseCrudController.prototype, "clearTable", null);
6774
- __decorate([
6775
- POST(),
6776
- __param(0, Body()),
6777
- __metadata("design:type", Function),
6778
- __metadata("design:paramtypes", [Object]),
6779
- __metadata("design:returntype", Object)
6780
- ], TaonBaseCrudController.prototype, "save", null);
6781
- __decorate([
6782
- POST(),
6783
- __param(0, Body()),
6784
- __metadata("design:type", Function),
6785
- __metadata("design:paramtypes", [Object]),
6786
- __metadata("design:returntype", Object)
6787
- ], TaonBaseCrudController.prototype, "bulkCreate", null);
6788
- TaonBaseCrudController = __decorate([
6789
- TaonController({ className: 'TaonBaseCrudController' })
6790
- ], TaonBaseCrudController);
6791
-
6792
6112
  /**
6793
6113
  * Repository decorator
6794
6114
  */
@@ -7274,244 +6594,792 @@ let TaonBaseRepository = class TaonBaseRepository extends TaonBaseCustomReposito
7274
6594
  findAndCountBy(where) {
7275
6595
  return this.repo.findAndCountBy(where);
7276
6596
  }
7277
- //#endregion
7278
- //#region crud operations / typeorm / find by ids
6597
+ //#endregion
6598
+ //#region crud operations / typeorm / find by ids
6599
+ /**
6600
+ * Finds entities with ids.
6601
+ * Optionally find options or conditions can be applied.
6602
+ *
6603
+ * @deprecated use `findBy` method instead in conjunction with `In` operator, for example:
6604
+ *
6605
+ * .findBy({
6606
+ * id: In([1, 2, 3])
6607
+ * })
6608
+ */
6609
+ findByIds(ids) {
6610
+ return this.repo.findByIds(ids);
6611
+ }
6612
+ //#endregion
6613
+ //#region crud operations / typeorm / find one
6614
+ /**
6615
+ * Finds first entity by a given find options.
6616
+ * If entity was not found in the database - returns null.
6617
+ */
6618
+ findOne(options) {
6619
+ return this.repo.findOne(options);
6620
+ }
6621
+ //#endregion
6622
+ //#region crud operations / typeorm / find one by
6623
+ /**
6624
+ * Finds first entity that matches given where condition.
6625
+ * If entity was not found in the database - returns null.
6626
+ */
6627
+ findOneBy(where) {
6628
+ return this.repo.findOneBy(where);
6629
+ }
6630
+ //#endregion
6631
+ //#region crud operations / typeorm / find one or fail
6632
+ /**
6633
+ * Finds first entity that matches given id.
6634
+ * If entity was not found in the database - returns null.
6635
+ *
6636
+ * @deprecated use `findOneBy` method instead in conjunction with `In` operator, for example:
6637
+ *
6638
+ * .findOneBy({
6639
+ * id: 1 // where "id" is your primary column name
6640
+ * })
6641
+ */
6642
+ findOneById(id) {
6643
+ return this.repo.findOneById(id);
6644
+ }
6645
+ //#endregion
6646
+ //#region crud operations / typeorm / find one or fail
6647
+ /**
6648
+ * Finds first entity by a given find options.
6649
+ * If entity was not found in the database - rejects with error.
6650
+ */
6651
+ findOneOrFail(options) {
6652
+ return this.repo.findOneOrFail(options);
6653
+ }
6654
+ //#endregion
6655
+ //#region crud operations / typeorm / find one by or fail
6656
+ /**
6657
+ * Finds first entity that matches given where condition.
6658
+ * If entity was not found in the database - rejects with error.
6659
+ */
6660
+ findOneByOrFail(where) {
6661
+ return this.repo.findOneByOrFail(where);
6662
+ }
6663
+ //#endregion
6664
+ //#region crud operations / typeorm / query
6665
+ /**
6666
+ * Executes a raw SQL query and returns a raw database results.
6667
+ * Raw query execution is supported only by relational databases (MongoDB is not supported).
6668
+ */
6669
+ query(query, parameters) {
6670
+ return this.repo.query(query, parameters);
6671
+ }
6672
+ //#endregion
6673
+ //#region crud operations / typeorm / query
6674
+ /**
6675
+ * Executes a raw SQL query and returns a raw database results.
6676
+ * Raw query execution is supported only by relational databases (MongoDB is not supported).
6677
+ */
6678
+ createQueryBuilder(alias, queryRunner) {
6679
+ return this.repo.createQueryBuilder(alias, queryRunner);
6680
+ }
6681
+ //#endregion
6682
+ //#region crud operations / typeorm / clear
6683
+ /**
6684
+ * Clears all the data from the given table/collection (truncates/drops it).
6685
+ *
6686
+ * Note: this method uses TRUNCATE and may not work as you expect in transactions on some platforms.
6687
+ * @see https://stackoverflow.com/a/5972738/925151
6688
+ */
6689
+ clear() {
6690
+ return this.repo.clear();
6691
+ }
6692
+ //#endregion
6693
+ //#region crud operations / typeorm / increment
6694
+ /**
6695
+ * Increments some column by provided value of the entities matched given conditions.
6696
+ */
6697
+ increment(conditions, propertyPath, value) {
6698
+ return this.repo.increment(conditions, propertyPath, value);
6699
+ }
6700
+ //#endregion
6701
+ //#region crud operations / typeorm / decrement
6702
+ /**
6703
+ * Decrements some column by provided value of the entities matched given conditions.
6704
+ */
6705
+ decrement(conditions, propertyPath, value) {
6706
+ return this.repo.decrement(conditions, propertyPath, value);
6707
+ }
6708
+ //#endregion
6709
+ //#region crud operations / get all
6710
+ /**
6711
+ * @deprecated use findAndCount instead
6712
+ */
6713
+ async getAll() {
6714
+ //#region @websqlFunc
6715
+ // console.log('repo', this.__repository);
6716
+ // console.log(
6717
+ // `repo taget name "${ClassHelpers__NS__getName(this.__repository.target)}"`,
6718
+ // );
6719
+ // debugger;
6720
+ const totalCount = await this.repo.count();
6721
+ const models = await this.repo.find();
6722
+ // console.log('models', models);
6723
+ // console.log('totalCount', totalCount);
6724
+ return { models, totalCount };
6725
+ //#endregion
6726
+ }
6727
+ //#endregion
6728
+ //#region crud operations / get by id
6729
+ async getBy(id) {
6730
+ //#region @websqlFunc
6731
+ const model = await await this.repo.findOne({
6732
+ where: { id },
6733
+ });
6734
+ return model;
6735
+ //#endregion
6736
+ }
6737
+ };
6738
+ TaonBaseRepository = __decorate([
6739
+ TaonRepository({ className: 'TaonBaseRepository' }),
6740
+ __metadata("design:paramtypes", [Function])
6741
+ ], TaonBaseRepository);
6742
+
6743
+ const TaonBaseContext = createContext(() => ({
6744
+ contextName: 'TaonBaseContext',
6745
+ abstract: true,
6746
+ contexts: {
6747
+ // TaonGlobalStateContext,
6748
+ },
6749
+ middlewares: {
6750
+ TaonBaseFileUploadMiddleware,
6751
+ },
6752
+ repositories: {
6753
+ // @ts-ignore
6754
+ TaonBaseRepository,
6755
+ },
6756
+ }));
6757
+
6758
+ var baseContext = /*#__PURE__*/Object.freeze({
6759
+ __proto__: null,
6760
+ TaonBaseContext: TaonBaseContext
6761
+ });
6762
+
6763
+ /**
6764
+ * Controller decorator
6765
+ */
6766
+ function TaonController(options) {
6767
+ return function (constructor) {
6768
+ ClassHelpers__NS__setName(constructor, options?.className);
6769
+ Reflect.defineMetadata(Symbols__NS__metadata.className, options?.className || constructor.name, constructor);
6770
+ const cfg = ClassHelpers__NS__ensureClassConfig(constructor);
6771
+ options = options || {};
6772
+ cfg.className = options.className || constructor.name;
6773
+ cfg.path = options.path || '';
6774
+ cfg.realtime = options.realtime;
6775
+ cfg.middlewares = options.middlewares;
6776
+ };
6777
+ }
6778
+
6779
+ const metaReq = (method, path, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal) => {
6780
+ const methodConfig = ClassHelpers__NS__ensureMethodConfig(target, propertyKey);
6781
+ let options;
6782
+ if (typeof pathOrOptions === 'object') {
6783
+ options = pathOrOptions;
6784
+ pathOrOptions = options.path;
6785
+ pathIsGlobal = !!options.pathIsGlobal;
6786
+ path = options.path;
6787
+ }
6788
+ else {
6789
+ options = { pathOrOptions, pathIsGlobal };
6790
+ }
6791
+ const { overrideContentType, overrideResponseType, overrideExpressSendAsHtml, middlewares, } = options;
6792
+ methodConfig.methodName = propertyKey;
6793
+ methodConfig.middlewares = middlewares;
6794
+ methodConfig.type = method;
6795
+ if (!path) {
6796
+ let paramsPathConcatedPath = '';
6797
+ for (const key in methodConfig.parameters) {
6798
+ if (methodConfig.parameters.hasOwnProperty(key)) {
6799
+ const element = methodConfig.parameters[key];
6800
+ if (element.paramType === 'Path' &&
6801
+ ___NS__isString(element.paramName) &&
6802
+ element.paramName.trim().length > 0) {
6803
+ paramsPathConcatedPath += `/${element.paramName}/:${element.paramName}`;
6804
+ }
6805
+ }
6806
+ }
6807
+ methodConfig.path = `/${propertyKey}${paramsPathConcatedPath}`;
6808
+ }
6809
+ else {
6810
+ methodConfig.path = path;
6811
+ }
6812
+ methodConfig.descriptor = descriptor;
6813
+ methodConfig.global = pathIsGlobal;
6814
+ methodConfig.contentType = overrideContentType;
6815
+ methodConfig.responseType = overrideResponseType;
6816
+ methodConfig.overrideExpressSendAsHtml = overrideExpressSendAsHtml;
6817
+ };
6818
+ function GET(pathOrOptions, pathIsGlobal = false) {
6819
+ return function (target, propertyKey, descriptor) {
6820
+ metaReq('get', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6821
+ };
6822
+ }
6823
+ /**
6824
+ * Method for sending html website from text
6825
+ * Example
6826
+ *
6827
+ * ```ts
6828
+ * ...
6829
+ * // in your taon controller
6830
+ * ..Taon.Http.HTML()
6831
+ * sendHtmlDummyWebsite(): Taon__NS__ResponseHtml {
6832
+ * return `
6833
+ <html>
6834
+ <head>
6835
+ <title>Dummy website</title>
6836
+ </head>
6837
+ <body>
6838
+ <h1>This is dummy website</h1>
6839
+ <p>Served as HTML string from Taon controller method</p>
6840
+ </body>
6841
+ </html>
6842
+ * `; *
6843
+ * }
6844
+ * ...
6845
+ * ```
6846
+ */
6847
+ function HTML(pathOrOptions) {
6848
+ return function (target, propertyKey, descriptor) {
6849
+ const opt = pathOrOptions;
6850
+ opt.overrideExpressSendAsHtml = true;
6851
+ metaReq('get', opt, target, propertyKey, descriptor, pathOrOptions, opt.pathIsGlobal);
6852
+ };
6853
+ }
6854
+ function HEAD(pathOrOptions, pathIsGlobal = false) {
6855
+ return function (target, propertyKey, descriptor) {
6856
+ metaReq('head', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6857
+ };
6858
+ }
6859
+ function POST(pathOrOptions, pathIsGlobal = false) {
6860
+ return function (target, propertyKey, descriptor) {
6861
+ metaReq('post', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6862
+ };
6863
+ }
6864
+ function PUT(pathOrOptions, pathIsGlobal = false) {
6865
+ return function (target, propertyKey, descriptor) {
6866
+ metaReq('put', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6867
+ };
6868
+ }
6869
+ function PATCH(pathOrOptions, pathIsGlobal = false) {
6870
+ return function (target, propertyKey, descriptor) {
6871
+ metaReq('patch', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6872
+ };
6873
+ }
6874
+ function DELETE(pathOrOptions, pathIsGlobal = false) {
6875
+ return function (target, propertyKey, descriptor) {
6876
+ metaReq('delete', pathOrOptions, target, propertyKey, descriptor, pathOrOptions, pathIsGlobal);
6877
+ };
6878
+ }
6879
+
6880
+ function metaParam(param, name, expire, defaultValue = undefined, target, propertyKey, parameterIndex) {
6881
+ const methodCfg = ClassHelpers__NS__ensureMethodConfig(target, propertyKey);
6882
+ const nameKey = name ? name : param;
6883
+ // const key = name || `${param}_${parameterIndex}`;
6884
+ methodCfg.parameters[nameKey] = {
6885
+ index: parameterIndex,
6886
+ paramName: name,
6887
+ paramType: param,
6888
+ defaultType: defaultValue,
6889
+ expireInSeconds: expire,
6890
+ };
6891
+ // console.log('params updated', methodConfig);
6892
+ }
6893
+ /**
6894
+ * @deprecated use Taon.Http.Param.Path (is more safe and cleaner)
6895
+ */
6896
+ function Path(name) {
6897
+ return function (target, propertyKey, parameterIndex) {
6898
+ metaParam('Path', name, undefined, {}, target, propertyKey, parameterIndex);
6899
+ };
6900
+ }
6901
+ function Query(name) {
6902
+ return function (target, propertyKey, parameterIndex) {
6903
+ metaParam('Query', name, undefined, {}, target, propertyKey, parameterIndex);
6904
+ };
6905
+ }
6906
+ function Cookie(name, expireInSecond = 3600) {
6907
+ return function (target, propertyKey, parameterIndex) {
6908
+ metaParam('Cookie', name, expireInSecond, {}, target, propertyKey, parameterIndex);
6909
+ };
6910
+ }
6911
+ function Header(name) {
6912
+ return function (target, propertyKey, parameterIndex) {
6913
+ metaParam('Header', name, undefined, {}, target, propertyKey, parameterIndex);
6914
+ };
6915
+ }
6916
+ function Body(name) {
6917
+ return function (target, propertyKey, parameterIndex) {
6918
+ metaParam('Body', name, undefined, {}, target, propertyKey, parameterIndex);
6919
+ };
6920
+ }
6921
+
6922
+ let TaonBaseController = class TaonBaseController extends TaonBaseInjector {
7279
6923
  /**
7280
- * Finds entities with ids.
7281
- * Optionally find options or conditions can be applied.
7282
- *
7283
- * @deprecated use `findBy` method instead in conjunction with `In` operator, for example:
7284
- *
7285
- * .findBy({
7286
- * id: In([1, 2, 3])
7287
- * })
6924
+ * Hook that is called when taon app is inited
6925
+ * (all contexts are created and inited)
7288
6926
  */
7289
- findByIds(ids) {
7290
- return this.repo.findByIds(ids);
6927
+ async afterAllCtxInited(options) { }
6928
+ //#region upload form data to server
6929
+ uploadFormDataToServer(formData, queryParams) {
6930
+ /* */
6931
+ /* */
6932
+ /* */
6933
+ /* */
6934
+ /* */
6935
+ /* */
6936
+ /* */
6937
+ /* */
6938
+ /* */
6939
+ /* */
6940
+ /* */
6941
+ /* */
6942
+ /* */
6943
+ /* */
6944
+ /* */
6945
+ /* */
6946
+ /* */
6947
+ /* */
6948
+ /* */
6949
+ /* */
6950
+ /* */
6951
+ /* */
6952
+ /* */
6953
+ /* */
6954
+ /* */
6955
+ /* */
6956
+ return (void 0);
7291
6957
  }
7292
6958
  //#endregion
7293
- //#region crud operations / typeorm / find one
6959
+ //#region after file upload hook
7294
6960
  /**
7295
- * Finds first entity by a given find options.
7296
- * If entity was not found in the database - returns null.
6961
+ * Hook after file is uploaded
6962
+ * through `uploadFormDataToServer` or `uploadLocalFileToServer`
7297
6963
  */
7298
- findOne(options) {
7299
- return this.repo.findOne(options);
6964
+ afterFileUploadAction(file, queryParams) {
6965
+ // empty
7300
6966
  }
7301
- //#endregion
7302
- //#region crud operations / typeorm / find one by
7303
- /**
7304
- * Finds first entity that matches given where condition.
7305
- * If entity was not found in the database - returns null.
7306
- */
7307
- findOneBy(where) {
7308
- return this.repo.findOneBy(where);
6967
+ //#region upload local file to server
6968
+ async uploadLocalFileToServer(absFilePath, options, queryParams) {
6969
+ /* */
6970
+ /* */
6971
+ /* */
6972
+ /* */
6973
+ /* */
6974
+ /* */
6975
+ /* */
6976
+ /* */
6977
+ /* */
6978
+ /* */
6979
+ /* */
6980
+ /* */
6981
+ /* */
6982
+ /* */
6983
+ return (void 0);
7309
6984
  }
7310
6985
  //#endregion
7311
- //#region crud operations / typeorm / find one or fail
6986
+ // async check() {
6987
+ // await this._waitForProperStatusChange({
6988
+ // request: () => this.uploadFormDataToServer(void 0, void 0).request(),
6989
+ // statusCheck: resp => resp.body.json[0].ok,
6990
+ // });
6991
+ // }
7312
6992
  /**
7313
- * Finds first entity that matches given id.
7314
- * If entity was not found in the database - returns null.
7315
- *
7316
- * @deprecated use `findOneBy` method instead in conjunction with `In` operator, for example:
6993
+ * Easy way to wait for status change with http (1s default) pooling.
7317
6994
  *
7318
- * .findOneBy({
7319
- * id: 1 // where "id" is your primary column name
7320
- * })
7321
- */
7322
- findOneById(id) {
7323
- return this.repo.findOneById(id);
7324
- }
7325
- //#endregion
7326
- //#region crud operations / typeorm / find one or fail
7327
- /**
7328
- * Finds first entity by a given find options.
7329
- * If entity was not found in the database - rejects with error.
6995
+ * example (in sub class):
6996
+ * ```ts
6997
+ async check() {
6998
+ await this.waitForProperStatusChange({
6999
+ request: () => this.uploadFormDataToServer(void 0, void 0).request(),
7000
+ statusCheck: resp => resp.body.json[0].ok,
7001
+ });
7002
+ }
7003
+ * ```
7330
7004
  */
7331
- findOneOrFail(options) {
7332
- return this.repo.findOneOrFail(options);
7005
+ async _waitForProperStatusChange(options) {
7006
+ const poolingInterval = options.poolingInterval || 1000;
7007
+ const taonRequest = options.request;
7008
+ let maxTries = options.maxTries || Number.POSITIVE_INFINITY;
7009
+ let i = 0;
7010
+ let httpErrorsCount = 0;
7011
+ while (true) {
7012
+ await UtilsTerminal__NS__waitMilliseconds(poolingInterval);
7013
+ try {
7014
+ const resp = await taonRequest({
7015
+ reqIndexNum: i,
7016
+ httpErrorsCount,
7017
+ });
7018
+ if (options.statusCheck && options.statusCheck(resp)) {
7019
+ return;
7020
+ }
7021
+ }
7022
+ catch (error) {
7023
+ httpErrorsCount++;
7024
+ if (options.loopRequestsOnBackendError) {
7025
+ const isProperTaonError = error instanceof HttpResponseError &&
7026
+ error.body.json[CoreModels__NS__TaonHttpErrorCustomProp];
7027
+ const isHttpError = error instanceof HttpResponseError && !isProperTaonError;
7028
+ const isUnknownError = !(error instanceof HttpResponseError);
7029
+ const resBool = await options.loopRequestsOnBackendError({
7030
+ taonError: isProperTaonError ? error : void 0,
7031
+ unknownHttpError: isHttpError ? error : void 0,
7032
+ unknownError: isUnknownError ? error : void 0,
7033
+ reqIndexNum: i,
7034
+ httpErrorsCount,
7035
+ });
7036
+ if (resBool) {
7037
+ i++;
7038
+ continue;
7039
+ }
7040
+ else {
7041
+ return;
7042
+ }
7043
+ }
7044
+ if (httpErrorsCount >
7045
+ (options.allowedHttpErrors || Number.POSITIVE_INFINITY)) {
7046
+ throw new Error(`Too many http errors (${httpErrorsCount}) for "${options.actionName}".`);
7047
+ }
7048
+ }
7049
+ if (i++ > maxTries) {
7050
+ throw new Error(`Timeout waiting for "${options.actionName}" to be finished. Waited for ${maxTries} seconds`);
7051
+ }
7052
+ }
7333
7053
  }
7054
+ };
7055
+ __decorate([
7056
+ POST({
7057
+ overrideContentType: 'multipart/form-data',
7058
+ middlewares: ({ parentMiddlewares }) => ({
7059
+ ...parentMiddlewares,
7060
+ TaonBaseFileUploadMiddleware,
7061
+ }),
7062
+ }),
7063
+ __param(0, Body()),
7064
+ __param(1, Query()),
7065
+ __metadata("design:type", Function),
7066
+ __metadata("design:paramtypes", [FormData, Object]),
7067
+ __metadata("design:returntype", Object)
7068
+ ], TaonBaseController.prototype, "uploadFormDataToServer", null);
7069
+ TaonBaseController = __decorate([
7070
+ TaonController({
7071
+ className: 'TaonBaseController',
7072
+ })
7073
+ ], TaonBaseController);
7074
+
7075
+ //#endregion
7076
+ /**
7077
+ * Please override property entityClassFn with entity class.
7078
+ */
7079
+ let TaonBaseCrudController = class TaonBaseCrudController extends TaonBaseController {
7334
7080
  //#endregion
7335
- //#region crud operations / typeorm / find one by or fail
7336
- /**
7337
- * Finds first entity that matches given where condition.
7338
- * If entity was not found in the database - rejects with error.
7339
- */
7340
- findOneByOrFail(where) {
7341
- return this.repo.findOneByOrFail(where);
7081
+ //#region init
7082
+ async _() {
7083
+ if (!___NS__isFunction(this.entityClassResolveFn)) {
7084
+ Helpers__NS__warn(`Skipping initing CRUD controller ${ClassHelpers__NS__getName(this)} because entityClassResolveFn is not provided.`);
7085
+ return;
7086
+ }
7087
+ let entityClassFn = this.entityClassResolveFn();
7088
+ this.db = this.injectRepo(entityClassFn);
7089
+ if (entityClassFn) {
7090
+ const configEntity = Reflect.getMetadata(Symbols__NS__metadata.options.entity, ClassHelpers__NS__getClassFnFromObject(this));
7091
+ if (configEntity?.createTable === false) {
7092
+ Helpers__NS__warn(`Table for entity ${ClassHelpers__NS__getName(entityClassFn)} will not be created. Crud will not work properly.`);
7093
+ }
7094
+ }
7095
+ else {
7096
+ Helpers__NS__error(`Entity class not provided for controller ${ClassHelpers__NS__getName(this)}.
7097
+
7098
+ Please provide entity as class property entityClassFn:
7099
+
7100
+ class ${ClassHelpers__NS__getName(this)} extends TaonBaseCrudController<Entity> {
7101
+ // ...
7102
+ entityClassResolveFn = ()=> MyEntityClass;
7103
+ // ...
7104
+ }
7105
+
7106
+ `);
7107
+ }
7108
+ await super._();
7342
7109
  }
7343
7110
  //#endregion
7344
- //#region crud operations / typeorm / query
7345
- /**
7346
- * Executes a raw SQL query and returns a raw database results.
7347
- * Raw query execution is supported only by relational databases (MongoDB is not supported).
7348
- */
7349
- query(query, parameters) {
7350
- return this.repo.query(query, parameters);
7111
+ //#region bufferd changes
7112
+ bufforedChanges(id, property, alreadyLength) {
7113
+ //#region @websqlFunc
7114
+ return async (request, response) => {
7115
+ const model = await this.db.getBy(id);
7116
+ if (model === void 0) {
7117
+ return;
7118
+ }
7119
+ Validators__NS__preventUndefinedModel(model, id);
7120
+ let value = model[property];
7121
+ let result;
7122
+ if (___NS__isString(value) || ___NS__isArray(value)) {
7123
+ result = value.slice(alreadyLength);
7124
+ }
7125
+ return result;
7126
+ };
7127
+ //#endregion
7351
7128
  }
7352
7129
  //#endregion
7353
- //#region crud operations / typeorm / query
7354
- /**
7355
- * Executes a raw SQL query and returns a raw database results.
7356
- * Raw query execution is supported only by relational databases (MongoDB is not supported).
7357
- */
7358
- createQueryBuilder(alias, queryRunner) {
7359
- return this.repo.createQueryBuilder(alias, queryRunner);
7130
+ //#region pagintation
7131
+ pagination(pageNumber = 1, pageSize = 10, search = '') {
7132
+ //#region @websqlFunc
7133
+ return async (request, response) => {
7134
+ if (this.db.repositoryExists) {
7135
+ const query = {
7136
+ page: pageNumber,
7137
+ take: pageSize,
7138
+ keyword: search,
7139
+ };
7140
+ // console.log({
7141
+ // query
7142
+ // })
7143
+ const take = query.take || 10;
7144
+ const page = query.page || 1;
7145
+ const skip = (page - 1) * take;
7146
+ const keyword = query.keyword || '';
7147
+ const [result, total] = await this.db.findAndCount({
7148
+ // where: { name: Like('%' + keyword + '%') },
7149
+ // order: { name: "DESC" },
7150
+ take: take,
7151
+ skip: skip,
7152
+ });
7153
+ response?.setHeader(Symbols__NS__old.X_TOTAL_COUNT, total);
7154
+ // const lastPage = Math.ceil(total / take);
7155
+ // const nextPage = page + 1 > lastPage ? null : page + 1;
7156
+ // const prevPage = page - 1 < 1 ? null : page - 1;
7157
+ // console.log({
7158
+ // result,
7159
+ // total
7160
+ // })
7161
+ return result;
7162
+ }
7163
+ return [];
7164
+ };
7165
+ //#endregion
7360
7166
  }
7361
7167
  //#endregion
7362
- //#region crud operations / typeorm / clear
7363
- /**
7364
- * Clears all the data from the given table/collection (truncates/drops it).
7365
- *
7366
- * Note: this method uses TRUNCATE and may not work as you expect in transactions on some platforms.
7367
- * @see https://stackoverflow.com/a/5972738/925151
7368
- */
7369
- clear() {
7370
- return this.repo.clear();
7168
+ //#region get all
7169
+ getAll() {
7170
+ //#region @websqlFunc
7171
+ return async (request, response) => {
7172
+ if (this.db.repositoryExists) {
7173
+ const { models, totalCount } = await this.db.getAll();
7174
+ response?.setHeader(Symbols__NS__old.X_TOTAL_COUNT, totalCount);
7175
+ return models;
7176
+ }
7177
+ return [];
7178
+ };
7179
+ //#endregion
7371
7180
  }
7372
7181
  //#endregion
7373
- //#region crud operations / typeorm / increment
7374
- /**
7375
- * Increments some column by provided value of the entities matched given conditions.
7376
- */
7377
- increment(conditions, propertyPath, value) {
7378
- return this.repo.increment(conditions, propertyPath, value);
7182
+ //#region get by id
7183
+ getBy(id) {
7184
+ //#region @websqlFunc
7185
+ return async () => {
7186
+ const model = await this.db.getBy(id);
7187
+ return model;
7188
+ };
7189
+ //#endregion
7379
7190
  }
7380
7191
  //#endregion
7381
- //#region crud operations / typeorm / decrement
7382
- /**
7383
- * Decrements some column by provided value of the entities matched given conditions.
7384
- */
7385
- decrement(conditions, propertyPath, value) {
7386
- return this.repo.decrement(conditions, propertyPath, value);
7192
+ //#region update by id
7193
+ updateById(id, item) {
7194
+ //#region @websqlFunc
7195
+ return async () => {
7196
+ const model = await this.db.updateById(id, item);
7197
+ return model;
7198
+ };
7199
+ //#endregion
7387
7200
  }
7388
7201
  //#endregion
7389
- //#region crud operations / get all
7390
- /**
7391
- * @deprecated use findAndCount instead
7392
- */
7393
- async getAll() {
7202
+ //#region patch by id
7203
+ patchById(id, item) {
7394
7204
  //#region @websqlFunc
7395
- // console.log('repo', this.__repository);
7396
- // console.log(
7397
- // `repo taget name "${ClassHelpers__NS__getName(this.__repository.target)}"`,
7398
- // );
7399
- // debugger;
7400
- const totalCount = await this.repo.count();
7401
- const models = await this.repo.find();
7402
- // console.log('models', models);
7403
- // console.log('totalCount', totalCount);
7404
- return { models, totalCount };
7205
+ return async () => {
7206
+ const model = await this.db.updateById(id, item);
7207
+ return model;
7208
+ };
7405
7209
  //#endregion
7406
7210
  }
7407
7211
  //#endregion
7408
- //#region crud operations / get by id
7409
- async getBy(id) {
7212
+ //#region bulk update
7213
+ bulkUpdate(items) {
7410
7214
  //#region @websqlFunc
7411
- const model = await await this.repo.findOne({
7412
- where: { id },
7413
- });
7414
- return model;
7215
+ return async () => {
7216
+ if (!Array.isArray(items) || items?.length === 0) {
7217
+ return [];
7218
+ }
7219
+ const { models } = await this.db.bulkUpdate(items);
7220
+ return models;
7221
+ };
7415
7222
  //#endregion
7416
7223
  }
7417
- };
7418
- TaonBaseRepository = __decorate([
7419
- TaonRepository({ className: 'TaonBaseRepository' }),
7420
- __metadata("design:paramtypes", [Function])
7421
- ], TaonBaseRepository);
7422
-
7423
- //namespace TaonGlobalStateUtils
7424
- // export function isActive(state: string): state is TaonGlobalStateStatus {
7425
- // return state === 'active';
7426
- // }
7427
- const TaonGlobalStateUtils__NS__assertAllowedTransition = (from, to) => {
7428
- if (!allowedTaonGlobalStatusOrders[from]?.includes(to)) {
7429
- throw new Error(`Invalid state transition: ${from} → ${to}`);
7430
- }
7431
- };
7432
- //end of namespace TaonGlobalStateUtils
7433
-
7434
- //#region imports
7435
- //#endregion
7436
- let TaonGlobalStateRepository = class TaonGlobalStateRepository extends TaonBaseRepository {
7437
- constructor() {
7438
- super(...arguments);
7439
- this.entityClassResolveFn = () => TAON_GLOBAL_STATE;
7440
- }
7441
- async getLastStatus() {
7224
+ //#endregion
7225
+ //#region delete by id
7226
+ deleteById(id) {
7442
7227
  //#region @websqlFunc
7443
- const lastStatus = await this.findOne({
7444
- order: { createdAt: 'DESC' },
7445
- });
7446
- return lastStatus;
7228
+ return async () => {
7229
+ const model = await this.db.deleteById(id);
7230
+ return model;
7231
+ };
7447
7232
  //#endregion
7448
7233
  }
7449
- async setDraining(secondsBeforeReadonly = 0) {
7234
+ //#endregion
7235
+ //#region bulk delete
7236
+ bulkDelete(ids) {
7450
7237
  //#region @websqlFunc
7451
- await this.transitionTo(TaonGlobalStateStatus.DRAINING);
7452
- if (secondsBeforeReadonly > 0) {
7453
- setTimeout(async () => {
7454
- await this.transitionTo(TaonGlobalStateStatus.READONLY);
7455
- }, secondsBeforeReadonly);
7456
- }
7238
+ return async () => {
7239
+ const models = await this.db.bulkDelete(ids);
7240
+ return models;
7241
+ };
7457
7242
  //#endregion
7458
7243
  }
7459
- async transitionTo(next) {
7244
+ //#endregion
7245
+ //#region bulk delete
7246
+ clearTable() {
7460
7247
  //#region @websqlFunc
7461
- const current = await this.getLastStatus();
7462
- TaonGlobalStateUtils__NS__assertAllowedTransition(current.status, next);
7463
- const newState = this.create({ status: next });
7464
- await this.save(newState);
7465
- return newState;
7248
+ return async () => {
7249
+ await this.db.clear();
7250
+ };
7466
7251
  //#endregion
7467
7252
  }
7468
- };
7469
- TaonGlobalStateRepository = __decorate([
7470
- TaonRepository({
7471
- className: 'TaonGlobalStateRepository',
7472
- })
7473
- ], TaonGlobalStateRepository);
7474
-
7475
- //#region imports
7476
- //#endregion
7477
- let TaonGlobalStateController = class TaonGlobalStateController extends TaonBaseCrudController {
7478
- constructor() {
7479
- super(...arguments);
7480
- this.entityClassResolveFn = () => TAON_GLOBAL_STATE;
7481
- this.taonGlobalStateRepository = this.injectCustomRepo(TaonGlobalStateRepository);
7482
- }
7483
- getStatus() {
7253
+ //#endregion
7254
+ //#region create
7255
+ save(item) {
7256
+ //#region @websqlFunc
7484
7257
  return async () => {
7485
- //#region @websqlFunc
7486
- const stateEntity = await this.taonGlobalStateRepository.getLastStatus();
7487
- return stateEntity.status;
7488
- //#endregion
7258
+ const model = await this.db.save(item);
7259
+ return model;
7489
7260
  };
7261
+ //#endregion
7490
7262
  }
7491
- setDraining(secondsBeforeReadonly = 0) {
7263
+ //#endregion
7264
+ //#region bulk create
7265
+ bulkCreate(items) {
7266
+ //#region @websqlFunc
7492
7267
  return async () => {
7493
- await this.taonGlobalStateRepository.setDraining(secondsBeforeReadonly);
7268
+ const models = await this.db.bulkCreate(items);
7269
+ return models;
7494
7270
  };
7271
+ //#endregion
7495
7272
  }
7496
7273
  };
7497
7274
  __decorate([
7498
7275
  GET(),
7276
+ __param(0, Query(`id`)),
7277
+ __param(1, Query(`property`)),
7278
+ __param(2, Query('alreadyLength')),
7279
+ __metadata("design:type", Function),
7280
+ __metadata("design:paramtypes", [Object, String, Number]),
7281
+ __metadata("design:returntype", Object)
7282
+ ], TaonBaseCrudController.prototype, "bufforedChanges", null);
7283
+ __decorate([
7284
+ GET(),
7285
+ __param(0, Query('pageNumber')),
7286
+ __param(1, Query('pageSize')),
7287
+ __param(2, Query('search')),
7288
+ __metadata("design:type", Function),
7289
+ __metadata("design:paramtypes", [Number, Number, String]),
7290
+ __metadata("design:returntype", Object)
7291
+ ], TaonBaseCrudController.prototype, "pagination", null);
7292
+ __decorate([
7293
+ GET(),
7294
+ __metadata("design:type", Function),
7295
+ __metadata("design:paramtypes", []),
7296
+ __metadata("design:returntype", Object)
7297
+ ], TaonBaseCrudController.prototype, "getAll", null);
7298
+ __decorate([
7299
+ GET(),
7300
+ __param(0, Query(`id`)),
7301
+ __metadata("design:type", Function),
7302
+ __metadata("design:paramtypes", [Object]),
7303
+ __metadata("design:returntype", Object)
7304
+ ], TaonBaseCrudController.prototype, "getBy", null);
7305
+ __decorate([
7306
+ PUT(),
7307
+ __param(0, Query(`id`)),
7308
+ __param(1, Body()),
7309
+ __metadata("design:type", Function),
7310
+ __metadata("design:paramtypes", [Object, Object]),
7311
+ __metadata("design:returntype", Object)
7312
+ ], TaonBaseCrudController.prototype, "updateById", null);
7313
+ __decorate([
7314
+ PATCH(),
7315
+ __param(0, Query(`id`)),
7316
+ __param(1, Body()),
7317
+ __metadata("design:type", Function),
7318
+ __metadata("design:paramtypes", [Object, Object]),
7319
+ __metadata("design:returntype", Object)
7320
+ ], TaonBaseCrudController.prototype, "patchById", null);
7321
+ __decorate([
7322
+ PUT(),
7323
+ __param(0, Body()),
7324
+ __metadata("design:type", Function),
7325
+ __metadata("design:paramtypes", [Array]),
7326
+ __metadata("design:returntype", Object)
7327
+ ], TaonBaseCrudController.prototype, "bulkUpdate", null);
7328
+ __decorate([
7329
+ DELETE(),
7330
+ __param(0, Query(`id`)),
7331
+ __metadata("design:type", Function),
7332
+ __metadata("design:paramtypes", [Object]),
7333
+ __metadata("design:returntype", Object)
7334
+ ], TaonBaseCrudController.prototype, "deleteById", null);
7335
+ __decorate([
7336
+ DELETE(),
7337
+ __param(0, Query(`ids`)),
7338
+ __metadata("design:type", Function),
7339
+ __metadata("design:paramtypes", [Array]),
7340
+ __metadata("design:returntype", Object)
7341
+ ], TaonBaseCrudController.prototype, "bulkDelete", null);
7342
+ __decorate([
7343
+ DELETE(),
7499
7344
  __metadata("design:type", Function),
7500
7345
  __metadata("design:paramtypes", []),
7501
7346
  __metadata("design:returntype", Object)
7502
- ], TaonGlobalStateController.prototype, "getStatus", null);
7347
+ ], TaonBaseCrudController.prototype, "clearTable", null);
7503
7348
  __decorate([
7504
7349
  POST(),
7505
- __param(0, Query('secondsBeforeReadonly')),
7350
+ __param(0, Body()),
7506
7351
  __metadata("design:type", Function),
7507
7352
  __metadata("design:paramtypes", [Object]),
7508
7353
  __metadata("design:returntype", Object)
7509
- ], TaonGlobalStateController.prototype, "setDraining", null);
7510
- TaonGlobalStateController = __decorate([
7511
- TaonController({
7512
- className: 'TaonGlobalStateController',
7513
- })
7514
- ], TaonGlobalStateController);
7354
+ ], TaonBaseCrudController.prototype, "save", null);
7355
+ __decorate([
7356
+ POST(),
7357
+ __param(0, Body()),
7358
+ __metadata("design:type", Function),
7359
+ __metadata("design:paramtypes", [Object]),
7360
+ __metadata("design:returntype", Object)
7361
+ ], TaonBaseCrudController.prototype, "bulkCreate", null);
7362
+ TaonBaseCrudController = __decorate([
7363
+ TaonController({ className: 'TaonBaseCrudController' })
7364
+ ], TaonBaseCrudController);
7365
+
7366
+ class TaonBaseMigration extends TaonBaseInjector {
7367
+ /**
7368
+ * by default is READY to run
7369
+ */
7370
+ isReadyToRun() {
7371
+ return true;
7372
+ }
7373
+ getDescription() {
7374
+ return ___NS__startCase(ClassHelpers__NS__getName(this));
7375
+ }
7376
+ async up(queryRunner) {
7377
+ console.log(`[TaonBaseMigration] Running migration UP "${ClassHelpers__NS__getName(this)}"`);
7378
+ }
7379
+ async down(queryRunner) {
7380
+ console.log(`[TaonBaseMigration] Running migration DOWN "${ClassHelpers__NS__getName(this)}"`);
7381
+ }
7382
+ }
7515
7383
 
7516
7384
  /**
7517
7385
  * TODO
@@ -7521,39 +7389,6 @@ TaonGlobalStateController = __decorate([
7521
7389
  class TaonBaseProvider extends TaonBaseInjector {
7522
7390
  }
7523
7391
 
7524
- /**
7525
- * Provider decorator
7526
- */
7527
- function TaonProvider(options) {
7528
- return function (constructor) {
7529
- Reflect.defineMetadata(Symbols__NS__metadata.options.provider, options, constructor);
7530
- Reflect.defineMetadata(Symbols__NS__metadata.className, options?.className || constructor.name, constructor);
7531
- ClassHelpers__NS__setName(constructor, options?.className || constructor.name);
7532
- };
7533
- }
7534
- class TaonProviderOptions extends DecoratorAbstractOpt {
7535
- }
7536
-
7537
- //#region imports
7538
- //#endregion
7539
- let TaonGlobalStateProvider = class TaonGlobalStateProvider extends TaonBaseProvider {
7540
- };
7541
- TaonGlobalStateProvider = __decorate([
7542
- TaonProvider({
7543
- className: 'TaonGlobalStateProvider',
7544
- })
7545
- ], TaonGlobalStateProvider);
7546
-
7547
- //#region imports
7548
- //#endregion
7549
- let TaonGlobalStateMiddleware = class TaonGlobalStateMiddleware extends TaonBaseMiddleware {
7550
- };
7551
- TaonGlobalStateMiddleware = __decorate([
7552
- TaonMiddleware({
7553
- className: 'TaonGlobalStateMiddleware',
7554
- })
7555
- ], TaonGlobalStateMiddleware);
7556
-
7557
7392
  /**
7558
7393
  * Subscriber decorator
7559
7394
  */
@@ -7710,75 +7545,6 @@ TaonBaseSubscriberForEntity = __decorate([
7710
7545
  })
7711
7546
  ], TaonBaseSubscriberForEntity);
7712
7547
 
7713
- //#region imports
7714
- //#endregion
7715
- let TaonGlobalStateSubscriber = class TaonGlobalStateSubscriber extends TaonBaseSubscriberForEntity {
7716
- constructor() {
7717
- super(...arguments);
7718
- this.taonGlobalStateProvider = this.injectProvider(TaonGlobalStateProvider);
7719
- }
7720
- listenTo() {
7721
- return TAON_GLOBAL_STATE;
7722
- }
7723
- };
7724
- TaonGlobalStateSubscriber = __decorate([
7725
- TaonSubscriber({
7726
- className: 'TaonGlobalStateSubscriber',
7727
- // allowedEvents: ['afterUpdate'],
7728
- })
7729
- ], TaonGlobalStateSubscriber);
7730
-
7731
- //#region imports
7732
- //#endregion
7733
- const TaonGlobalStateContext = createContext(() => ({
7734
- contextName: 'TaonGlobalStateContext',
7735
- abstract: true,
7736
- entities: { TAON_GLOBAL_STATE },
7737
- controllers: { TaonGlobalStateController },
7738
- repositories: { TaonGlobalStateRepository },
7739
- providers: { TaonGlobalStateProvider },
7740
- middlewares: { TaonGlobalStateMiddleware },
7741
- subscribers: { TaonGlobalStateSubscriber },
7742
- }));
7743
-
7744
- const TaonBaseContext = createContext(() => ({
7745
- contextName: 'TaonBaseContext',
7746
- abstract: true,
7747
- contexts: {
7748
- TaonGlobalStateContext,
7749
- },
7750
- middlewares: {
7751
- TaonBaseFileUploadMiddleware,
7752
- },
7753
- repositories: {
7754
- // @ts-ignore
7755
- TaonBaseRepository,
7756
- },
7757
- }));
7758
-
7759
- var baseContext = /*#__PURE__*/Object.freeze({
7760
- __proto__: null,
7761
- TaonBaseContext: TaonBaseContext
7762
- });
7763
-
7764
- class TaonBaseMigration extends TaonBaseInjector {
7765
- /**
7766
- * by default is READY to run
7767
- */
7768
- isReadyToRun() {
7769
- return true;
7770
- }
7771
- getDescription() {
7772
- return ___NS__startCase(ClassHelpers__NS__getName(this));
7773
- }
7774
- async up(queryRunner) {
7775
- console.log(`[TaonBaseMigration] Running migration UP "${ClassHelpers__NS__getName(this)}"`);
7776
- }
7777
- async down(queryRunner) {
7778
- console.log(`[TaonBaseMigration] Running migration DOWN "${ClassHelpers__NS__getName(this)}"`);
7779
- }
7780
- }
7781
-
7782
7548
  //#region models / method config
7783
7549
  /**
7784
7550
  * @link './decorators/http/http-methods-decorators.ts' TaonHttpDecoratorOptions
@@ -8177,6 +7943,39 @@ function getFromlyConfigFor(target, options = {}) {
8177
7943
 
8178
7944
  //end of namespace RealtimeModels
8179
7945
 
7946
+ /**
7947
+ * Entity decorator
7948
+ */
7949
+ function TaonEntity(options) {
7950
+ return function (constructor) {
7951
+ options = options || {};
7952
+ options.uniqueKeyProp = options.uniqueKeyProp || 'id';
7953
+ if (!options.className) {
7954
+ const nameForClass = constructor?.name || 'AnyClass';
7955
+ throw `Please define 'classname' property inside decorator of class '${nameForClass}':
7956
+
7957
+ @TaonEntity({
7958
+ className: '${nameForClass}'
7959
+ })
7960
+ class ${constructor?.name} {
7961
+ //...
7962
+
7963
+ `;
7964
+ }
7965
+ ClassHelpers__NS__setName(constructor, options?.className);
7966
+ DefaultMapping(options?.defaultModelMapping)(constructor);
7967
+ DefaultModel(options.defaultModelMapping)(constructor);
7968
+ Reflect.defineMetadata(Symbols__NS__metadata.options.entity, options, constructor);
7969
+ Reflect.defineMetadata(Symbols__NS__metadata.className, options?.className || constructor.name, constructor);
7970
+ //#region @websql
7971
+ Entity(options?.className)(constructor);
7972
+ //#endregion
7973
+ CLASS__NS__setName(constructor, options?.className); // TODO QUICK_FIX for ng2-rest
7974
+ };
7975
+ }
7976
+ class TaonEntityOptions extends DecoratorAbstractOpt {
7977
+ }
7978
+
8180
7979
  /**
8181
7980
  * Migration decorator
8182
7981
  */
@@ -8190,6 +7989,19 @@ function TaonMigration(options) {
8190
7989
  class TaonMigrationOptions extends DecoratorAbstractOpt {
8191
7990
  }
8192
7991
 
7992
+ /**
7993
+ * Provider decorator
7994
+ */
7995
+ function TaonProvider(options) {
7996
+ return function (constructor) {
7997
+ Reflect.defineMetadata(Symbols__NS__metadata.options.provider, options, constructor);
7998
+ Reflect.defineMetadata(Symbols__NS__metadata.className, options?.className || constructor.name, constructor);
7999
+ ClassHelpers__NS__setName(constructor, options?.className || constructor.name);
8000
+ };
8001
+ }
8002
+ class TaonProviderOptions extends DecoratorAbstractOpt {
8003
+ }
8004
+
8193
8005
  // TODO export all things
8194
8006
  //namespace Taon
8195
8007
  /**