taon 21.0.52 → 21.0.54

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 (193) hide show
  1. package/browser/package.json +1 -1
  2. package/browser-prod/package.json +1 -1
  3. package/icon-menu-taon.svg +15 -15
  4. package/lib/build-info._auto-generated_.d.ts +1 -1
  5. package/lib/build-info._auto-generated_.js +1 -1
  6. package/lib/package.json +1 -1
  7. package/lib/ui/index.js +2 -2
  8. package/lib/ui/taon-admin-mode-configuration/index.js +2 -2
  9. package/lib-prod/base-classes/base-abstract-entity.js +19 -0
  10. package/lib-prod/base-classes/base-angular-service.js +84 -0
  11. package/lib-prod/base-classes/base-class.js +35 -0
  12. package/lib-prod/base-classes/{base-context.ts → base-context.js} +13 -15
  13. package/lib-prod/base-classes/base-controller.js +154 -0
  14. package/lib-prod/base-classes/base-crud-controller.js +264 -0
  15. package/lib-prod/base-classes/base-custom-repository.js +9 -0
  16. package/lib-prod/base-classes/{base-electron-service.ts → base-electron-service.js} +1 -12
  17. package/lib-prod/base-classes/base-entity.js +22 -0
  18. package/lib-prod/base-classes/base-file-upload.middleware.js +75 -0
  19. package/lib-prod/base-classes/base-injector.js +184 -0
  20. package/lib-prod/base-classes/base-middleware.js +9 -0
  21. package/lib-prod/base-classes/base-migration.js +20 -0
  22. package/lib-prod/base-classes/{base-provider.ts → base-provider.js} +2 -2
  23. package/lib-prod/base-classes/base-repository.js +617 -0
  24. package/lib-prod/base-classes/base-subscriber-for-entity.js +145 -0
  25. package/lib-prod/base-classes/{base.ts → base.js} +2 -15
  26. package/lib-prod/{build-info._auto-generated_.ts → build-info._auto-generated_.js} +1 -2
  27. package/lib-prod/config/controller-config.js +28 -0
  28. package/lib-prod/config/controller-options.js +3 -0
  29. package/lib-prod/config/method-config.js +7 -0
  30. package/lib-prod/config/param-config.js +3 -0
  31. package/lib-prod/constants.js +33 -0
  32. package/lib-prod/context-db-migrations.js +342 -0
  33. package/lib-prod/create-context.js +217 -0
  34. package/lib-prod/decorators/classes/controller-decorator.js +17 -0
  35. package/lib-prod/decorators/classes/entity-decorator.js +28 -0
  36. package/lib-prod/decorators/classes/middleware-decorator.js +16 -0
  37. package/lib-prod/decorators/classes/migration-decorator.js +15 -0
  38. package/lib-prod/decorators/classes/provider-decorator.js +15 -0
  39. package/lib-prod/decorators/classes/repository-decorator.js +15 -0
  40. package/lib-prod/decorators/classes/subscriber-decorator.js +15 -0
  41. package/lib-prod/decorators/decorator-abstract-opt.js +2 -0
  42. package/lib-prod/decorators/http/http-decorators.js +20 -0
  43. package/lib-prod/decorators/http/http-methods-decorators.js +102 -0
  44. package/lib-prod/decorators/http/http-params-decorators.js +42 -0
  45. package/lib-prod/dependency-injection/di-container.js +30 -0
  46. package/lib-prod/endpoint-context-storage.js +31 -0
  47. package/lib-prod/endpoint-context.js +2397 -0
  48. package/lib-prod/entity-process.js +225 -0
  49. package/lib-prod/env/{env.angular-node-app.ts → env.angular-node-app.js} +1 -1
  50. package/lib-prod/env/{env.docs-webapp.ts → env.docs-webapp.js} +1 -1
  51. package/lib-prod/env/{env.electron-app.ts → env.electron-app.js} +1 -1
  52. package/lib-prod/env/{env.mobile-app.ts → env.mobile-app.js} +1 -1
  53. package/lib-prod/env/{env.npm-lib-and-cli-tool.ts → env.npm-lib-and-cli-tool.js} +1 -1
  54. package/lib-prod/env/{env.vscode-plugin.ts → env.vscode-plugin.js} +1 -1
  55. package/lib-prod/express-types.js +1 -0
  56. package/lib-prod/formly/formly.models.js +1 -0
  57. package/lib-prod/formly/fromly.js +205 -0
  58. package/lib-prod/formly/type-from-entity.js +51 -0
  59. package/lib-prod/get-response-value.js +22 -0
  60. package/lib-prod/global-state/taon-global-state/{index.ts → index.js} +2 -2
  61. package/lib-prod/global-state/taon-global-state/{taon-global-state.abstract.context.ts → taon-global-state.abstract.context.js} +9 -11
  62. package/lib-prod/global-state/taon-global-state/taon-global-state.constants.js +7 -0
  63. package/lib-prod/global-state/taon-global-state/taon-global-state.controller.js +42 -0
  64. package/lib-prod/global-state/taon-global-state/taon-global-state.entity.js +35 -0
  65. package/lib-prod/global-state/taon-global-state/taon-global-state.middleware.js +12 -0
  66. package/lib-prod/global-state/taon-global-state/taon-global-state.models.js +44 -0
  67. package/lib-prod/global-state/taon-global-state/taon-global-state.provider.js +12 -0
  68. package/lib-prod/global-state/taon-global-state/taon-global-state.repository.js +46 -0
  69. package/lib-prod/global-state/taon-global-state/taon-global-state.subscriber.js +22 -0
  70. package/lib-prod/global-state/taon-global-state/taon-global-state.utils.js +11 -0
  71. package/lib-prod/global-state/taon-transaction-registry/{index.ts → index.js} +2 -2
  72. package/lib-prod/global-state/taon-transaction-registry/{taon-transaction-registry.abstract.context.ts → taon-transaction-registry.abstract.context.js} +10 -12
  73. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.constants.js +5 -0
  74. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.controller.js +36 -0
  75. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.entity.js +36 -0
  76. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.middleware.js +12 -0
  77. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.models.js +7 -0
  78. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.provider.js +12 -0
  79. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.repository.js +31 -0
  80. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.subscriber.js +22 -0
  81. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.utils.js +5 -0
  82. package/lib-prod/helpers/class-helpers.js +228 -0
  83. package/lib-prod/helpers/clone-obj.js +17 -0
  84. package/lib-prod/helpers/taon-helpers.js +147 -0
  85. package/lib-prod/{index._auto-generated_.ts → index._auto-generated_.js} +1 -1
  86. package/lib-prod/index.js +252 -0
  87. package/lib-prod/{inject.ts → inject.js} +35 -57
  88. package/lib-prod/migrations/index.js +2 -0
  89. package/lib-prod/migrations/{migrations_index._auto-generated_.ts → migrations_index._auto-generated_.js} +0 -2
  90. package/lib-prod/models.js +78 -0
  91. package/lib-prod/orm/columns.js +64 -0
  92. package/lib-prod/orm/index.js +56 -0
  93. package/lib-prod/package.json +1 -1
  94. package/lib-prod/realtime/realtime-client.js +198 -0
  95. package/lib-prod/realtime/realtime-core.js +81 -0
  96. package/lib-prod/realtime/realtime-server.js +237 -0
  97. package/lib-prod/realtime/realtime-strategy/{index.ts → index.js} +1 -1
  98. package/lib-prod/realtime/realtime-strategy/realtime-strategy-ipc.js +280 -0
  99. package/lib-prod/realtime/realtime-strategy/realtime-strategy-mock.js +289 -0
  100. package/lib-prod/realtime/realtime-strategy/realtime-strategy-socket-io.js +27 -0
  101. package/lib-prod/realtime/realtime-strategy/realtime-strategy.js +11 -0
  102. package/lib-prod/realtime/realtime-subs-manager.js +88 -0
  103. package/lib-prod/realtime/realtime.models.js +2 -0
  104. package/lib-prod/symbols.js +108 -0
  105. package/lib-prod/ui/index.js +1 -0
  106. package/lib-prod/ui/taon-admin-mode-configuration/index.js +1 -0
  107. package/lib-prod/validators.js +80 -0
  108. package/lib-prod.split-namespaces.json +31 -91
  109. package/package.json +1 -1
  110. package/websql/package.json +1 -1
  111. package/websql-prod/package.json +1 -1
  112. package/lib-prod/base-classes/base-abstract-entity.ts +0 -34
  113. package/lib-prod/base-classes/base-angular-service.ts +0 -107
  114. package/lib-prod/base-classes/base-class.ts +0 -46
  115. package/lib-prod/base-classes/base-controller.ts +0 -240
  116. package/lib-prod/base-classes/base-crud-controller.ts +0 -298
  117. package/lib-prod/base-classes/base-custom-repository.ts +0 -10
  118. package/lib-prod/base-classes/base-entity.ts +0 -28
  119. package/lib-prod/base-classes/base-file-upload.middleware.ts +0 -92
  120. package/lib-prod/base-classes/base-injector.ts +0 -278
  121. package/lib-prod/base-classes/base-middleware.ts +0 -71
  122. package/lib-prod/base-classes/base-migration.ts +0 -26
  123. package/lib-prod/base-classes/base-repository.ts +0 -942
  124. package/lib-prod/base-classes/base-subscriber-for-entity.ts +0 -196
  125. package/lib-prod/config/controller-config.ts +0 -58
  126. package/lib-prod/config/controller-options.ts +0 -19
  127. package/lib-prod/config/method-config.ts +0 -55
  128. package/lib-prod/config/param-config.ts +0 -16
  129. package/lib-prod/constants.ts +0 -63
  130. package/lib-prod/context-db-migrations.ts +0 -488
  131. package/lib-prod/create-context.ts +0 -345
  132. package/lib-prod/decorators/classes/controller-decorator.ts +0 -25
  133. package/lib-prod/decorators/classes/entity-decorator.ts +0 -57
  134. package/lib-prod/decorators/classes/middleware-decorator.ts +0 -29
  135. package/lib-prod/decorators/classes/migration-decorator.ts +0 -27
  136. package/lib-prod/decorators/classes/provider-decorator.ts +0 -28
  137. package/lib-prod/decorators/classes/repository-decorator.ts +0 -26
  138. package/lib-prod/decorators/classes/subscriber-decorator.ts +0 -28
  139. package/lib-prod/decorators/decorator-abstract-opt.ts +0 -4
  140. package/lib-prod/decorators/http/http-decorators.ts +0 -26
  141. package/lib-prod/decorators/http/http-methods-decorators.ts +0 -275
  142. package/lib-prod/decorators/http/http-params-decorators.ts +0 -105
  143. package/lib-prod/dependency-injection/di-container.ts +0 -39
  144. package/lib-prod/endpoint-context-storage.ts +0 -47
  145. package/lib-prod/endpoint-context.ts +0 -3110
  146. package/lib-prod/entity-process.ts +0 -286
  147. package/lib-prod/express-types.ts +0 -4
  148. package/lib-prod/formly/formly.models.ts +0 -7
  149. package/lib-prod/formly/fromly.ts +0 -261
  150. package/lib-prod/formly/type-from-entity.ts +0 -80
  151. package/lib-prod/get-response-value.ts +0 -30
  152. package/lib-prod/global-state/taon-global-state/taon-global-state.constants.ts +0 -9
  153. package/lib-prod/global-state/taon-global-state/taon-global-state.controller.ts +0 -44
  154. package/lib-prod/global-state/taon-global-state/taon-global-state.entity.ts +0 -40
  155. package/lib-prod/global-state/taon-global-state/taon-global-state.middleware.ts +0 -12
  156. package/lib-prod/global-state/taon-global-state/taon-global-state.models.ts +0 -48
  157. package/lib-prod/global-state/taon-global-state/taon-global-state.provider.ts +0 -16
  158. package/lib-prod/global-state/taon-global-state/taon-global-state.repository.ts +0 -47
  159. package/lib-prod/global-state/taon-global-state/taon-global-state.subscriber.ts +0 -18
  160. package/lib-prod/global-state/taon-global-state/taon-global-state.utils.ts +0 -21
  161. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.constants.ts +0 -7
  162. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.controller.ts +0 -38
  163. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.entity.ts +0 -54
  164. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.middleware.ts +0 -12
  165. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.models.ts +0 -6
  166. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.provider.ts +0 -16
  167. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.repository.ts +0 -29
  168. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.subscriber.ts +0 -20
  169. package/lib-prod/global-state/taon-transaction-registry/taon-transaction-registry.utils.ts +0 -9
  170. package/lib-prod/helpers/class-helpers.ts +0 -315
  171. package/lib-prod/helpers/clone-obj.ts +0 -24
  172. package/lib-prod/helpers/taon-helpers.ts +0 -181
  173. package/lib-prod/index.ts +0 -323
  174. package/lib-prod/lib-info.md +0 -8
  175. package/lib-prod/migrations/index.ts +0 -2
  176. package/lib-prod/migrations/migrations-info.md +0 -6
  177. package/lib-prod/models.ts +0 -427
  178. package/lib-prod/orm/columns.ts +0 -121
  179. package/lib-prod/orm/index.ts +0 -62
  180. package/lib-prod/realtime/realtime-client.ts +0 -288
  181. package/lib-prod/realtime/realtime-core.ts +0 -134
  182. package/lib-prod/realtime/realtime-server.ts +0 -398
  183. package/lib-prod/realtime/realtime-strategy/realtime-strategy-ipc.ts +0 -344
  184. package/lib-prod/realtime/realtime-strategy/realtime-strategy-mock.ts +0 -349
  185. package/lib-prod/realtime/realtime-strategy/realtime-strategy-socket-io.ts +0 -30
  186. package/lib-prod/realtime/realtime-strategy/realtime-strategy.ts +0 -21
  187. package/lib-prod/realtime/realtime-subs-manager.ts +0 -127
  188. package/lib-prod/realtime/realtime.models.ts +0 -33
  189. package/lib-prod/symbols.ts +0 -136
  190. package/lib-prod/ui/index.ts +0 -1
  191. package/lib-prod/ui/taon-admin-mode-configuration/index.ts +0 -1
  192. package/lib-prod/validators.ts +0 -103
  193. /package/lib-prod/env/{index.ts → index.js} +0 -0
@@ -1,3110 +0,0 @@
1
- //#region imports
2
- import type { Server } from 'http';
3
- import { Http2Server } from 'http2'; // @backend
4
- import { URL } from 'url'; // @backend
5
-
6
- import axios from 'axios';
7
- import { ipcMain } from 'electron'; // @backend
8
- import type { Application } from 'express';
9
- // multer in taon middleware will do better job than express-fileupload
10
- // import * as fileUpload from 'express-fileupload'; // @backend
11
- import type * as expressType from 'express';
12
- import { JSON10 } from 'json10/lib-prod';
13
- import { walk } from 'lodash-walk-object/lib-prod';
14
- import { Resource, RestErrorResponseWrapper, RestHeaders, Mapping__NS__decode, Mapping__NS__DefaultModelWithMapping, Mapping__NS__encode, Mapping__NS__getModelsMapping, Mapping__NS__Mapping, Mapping__NS__ModelValue, Models__NS__BackendError as ModelsNg2Rest__NS__BackendError, Models__NS__BaseBody as ModelsNg2Rest__NS__BaseBody, Models__NS__BaseResponse as ModelsNg2Rest__NS__BaseResponse, Models__NS__ErrorBody as ModelsNg2Rest__NS__ErrorBody, Models__NS__FnMethodsHttp as ModelsNg2Rest__NS__FnMethodsHttp, Models__NS__FnMethodsHttpWithMock as ModelsNg2Rest__NS__FnMethodsHttpWithMock, Models__NS__HandleResultOptions as ModelsNg2Rest__NS__HandleResultOptions, Models__NS__HandleResultSourceRequestOptions as ModelsNg2Rest__NS__HandleResultSourceRequestOptions, Models__NS__HttpBody as ModelsNg2Rest__NS__HttpBody, Models__NS__HttpCode as ModelsNg2Rest__NS__HttpCode, Models__NS__HttpResponse as ModelsNg2Rest__NS__HttpResponse, Models__NS__MetaRequest as ModelsNg2Rest__NS__MetaRequest, Models__NS__MethodWithBody as ModelsNg2Rest__NS__MethodWithBody, Models__NS__MockController as ModelsNg2Rest__NS__MockController, Models__NS__MockHttp as ModelsNg2Rest__NS__MockHttp, Models__NS__MockResponse as ModelsNg2Rest__NS__MockResponse, Models__NS__NestedParams as ModelsNg2Rest__NS__NestedParams, Models__NS__Ng2RestAxiosRequestConfig as ModelsNg2Rest__NS__Ng2RestAxiosRequestConfig, Models__NS__Ng2RestMethods as ModelsNg2Rest__NS__Ng2RestMethods, Models__NS__PromiseObservableMix as ModelsNg2Rest__NS__PromiseObservableMix, Models__NS__ReplayData as ModelsNg2Rest__NS__ReplayData, Models__NS__ReqParams as ModelsNg2Rest__NS__ReqParams, Models__NS__ResourceModel as ModelsNg2Rest__NS__ResourceModel, Models__NS__ResponseTypeAxios as ModelsNg2Rest__NS__ResponseTypeAxios, Models__NS__UrlParams as ModelsNg2Rest__NS__UrlParams } from 'ng2-rest/lib-prod';
15
- import { from, Subject } from 'rxjs';
16
- import type {
17
- TransactionRollbackEvent,
18
- TransactionCommitEvent,
19
- TransactionStartEvent,
20
- RecoverEvent,
21
- SoftRemoveEvent,
22
- RemoveEvent,
23
- UpdateEvent,
24
- InsertEvent,
25
- Repository,
26
- } from 'taon-typeorm/lib-prod'; // @websql
27
- import { EventSubscriber } from 'taon-typeorm/lib-prod'; // @websql
28
- import { Entity as TypeormEntity, Tree } from 'taon-typeorm/lib-prod'; // @websql
29
- import {
30
- DataSource,
31
- DataSourceOptions,
32
- getMetadataArgsStorage,
33
- } from 'taon-typeorm/lib-prod';
34
- import { path, requireDefault } from 'tnp-core/lib-prod';
35
- import { config } from 'tnp-core/lib-prod';
36
- import { CoreModels__NS__BaseProjectType, CoreModels__NS__BaseProjectTypeArr, CoreModels__NS__CfontAlign, CoreModels__NS__CfontStyle, CoreModels__NS__ClassNameStaticProperty, CoreModels__NS__ContentType, CoreModels__NS__ContentTypeKeys, CoreModels__NS__CoreLibCategory, CoreModels__NS__CutableFileExt, CoreModels__NS__DatabaseType, CoreModels__NS__EnvironmentName, CoreModels__NS__EnvironmentNameTaon, CoreModels__NS__ExecuteOptions, CoreModels__NS__FileEvent, CoreModels__NS__FileExtension, CoreModels__NS__FrameworkVersion, CoreModels__NS__GlobalDependencies, CoreModels__NS__HttpMethod, CoreModels__NS__ImageFileExtension, CoreModels__NS__ImageFileExtensionArr, CoreModels__NS__InstalationType, CoreModels__NS__InstalationTypeArr, CoreModels__NS__LibType, CoreModels__NS__localhostDomain, CoreModels__NS__localhostIp127, CoreModels__NS__ManifestIcon, CoreModels__NS__MediaType, CoreModels__NS__MediaTypeAllArr, CoreModels__NS__MimeType, CoreModels__NS__mimeTypes, CoreModels__NS__MimeTypesObj, CoreModels__NS__NewFactoryType, CoreModels__NS__NpmInstallOptions, CoreModels__NS__NpmSpecialVersions, CoreModels__NS__OrignalClassKey, CoreModels__NS__OutFolder, CoreModels__NS__Package, CoreModels__NS__ParamType, CoreModels__NS__parentLocation, CoreModels__NS__pathToChildren, CoreModels__NS__Position, CoreModels__NS__PreReleaseVersionTag, CoreModels__NS__PROGRESS_DATA_TYPE, CoreModels__NS__PUSHTYPE, CoreModels__NS__PwaManifest, CoreModels__NS__ReleaseVersionType, CoreModels__NS__ReleaseVersionTypeEnum, CoreModels__NS__RunOptions, CoreModels__NS__Size, CoreModels__NS__SPECIAL_APP_READY_MESSAGE, CoreModels__NS__SPECIAL_WORKER_READY_MESSAGE, CoreModels__NS__tagForTaskName, CoreModels__NS__TaonHttpErrorCustomProp, CoreModels__NS__TsUsage, CoreModels__NS__UIFramework, CoreModels__NS__UploadedBackendFile, CoreModels__NS__VSCodeSettings } from 'tnp-core/lib-prod';
37
- import { fse, http, https, os } from 'tnp-core/lib-prod'; // @backend
38
- import { Utils__NS__binary__NS__base64toBlob, Utils__NS__binary__NS__base64toBuffer, Utils__NS__binary__NS__base64toDbBinaryFormat, Utils__NS__binary__NS__blobToArrayBuffer, Utils__NS__binary__NS__blobToBase64, Utils__NS__binary__NS__blobToBuffer, Utils__NS__binary__NS__blobToFile, Utils__NS__binary__NS__blobToJson, Utils__NS__binary__NS__blobToText, Utils__NS__binary__NS__bufferToBase64, Utils__NS__binary__NS__bufferToBlob, Utils__NS__binary__NS__bufferToText, Utils__NS__binary__NS__dbBinaryFormatToBase64, Utils__NS__binary__NS__dbBinaryFormatToText, Utils__NS__binary__NS__fileToBlob, Utils__NS__binary__NS__fileToText, Utils__NS__binary__NS__getBlobFrom, Utils__NS__binary__NS__jsonToBlob, Utils__NS__binary__NS__textToBlob, Utils__NS__binary__NS__textToBuffer, Utils__NS__binary__NS__textToDbBinaryFormat, Utils__NS__binary__NS__textToFile, Utils__NS__camelize, Utils__NS__css__NS__numValue, Utils__NS__DbBinaryFormat, Utils__NS__DbBinaryFormatEnum, Utils__NS__DbBinaryFormatForBackend, Utils__NS__DbBinaryFormatForBrowser, Utils__NS__escapeStringForRegEx, Utils__NS__fullDate, Utils__NS__fullDateTime, Utils__NS__getFreePort, Utils__NS__removeChalkSpecialChars, Utils__NS__requireUncached, Utils__NS__sortKeys, Utils__NS__uniqArray, Utils__NS__wait, Utils__NS__waitMilliseconds, UtilsOs__NS__commandExistsAsync, UtilsOs__NS__commandExistsSync, UtilsOs__NS__detectEditor, UtilsOs__NS__Editor, UtilsOs__NS__EDITOR_PROCESSES, UtilsOs__NS__EditorArr, UtilsOs__NS__EditorProcess, UtilsOs__NS__getEditorSettingsJsonPath, UtilsOs__NS__getRealHomeDir, UtilsOs__NS__isBrowser, UtilsOs__NS__isDockerAvailable, UtilsOs__NS__isElectron, UtilsOs__NS__isNode, UtilsOs__NS__isNodeVersionOk, UtilsOs__NS__isPortInUse, UtilsOs__NS__isRunningInBrowser, UtilsOs__NS__isRunningInCliMode, UtilsOs__NS__isRunningInDocker, UtilsOs__NS__isRunningInElectron, UtilsOs__NS__isRunningInLinuxGraphicsCapableEnvironment, UtilsOs__NS__isRunningInMochaTest, UtilsOs__NS__isRunningInNode, UtilsOs__NS__isRunningInOsWithGraphicsCapableEnvironment, UtilsOs__NS__isRunningInSSRMode, UtilsOs__NS__isRunningInVscodeExtension, UtilsOs__NS__isRunningInWebSQL, UtilsOs__NS__isRunningInWindows, UtilsOs__NS__isRunningInWindowsCmd, UtilsOs__NS__isRunningInWindowsPowerShell, UtilsOs__NS__isRunningInWsl, UtilsOs__NS__isRunningNodeDebugger, UtilsOs__NS__isSSRMode, UtilsOs__NS__isVscodeExtension, UtilsOs__NS__isWebSQL, UtilsOs__NS__killAllEditor, UtilsOs__NS__openFolderInFileExplorer, UtilsOs__NS__openFolderInVSCode, UtilsOs__NS__pipxNestedPackageExists, UtilsOs__NS__pipxPackageExists, UtilsOs__NS__pythonModuleExists, UtilsOs__NS__UnknownEditor } from 'tnp-core/lib-prod';
39
- import { crossPlatformPath } from 'tnp-core/lib-prod';
40
- import { ___NS__add, ___NS__after, ___NS__ary, ___NS__assign, ___NS__assignIn, ___NS__assignInWith, ___NS__assignWith, ___NS__at, ___NS__attempt, ___NS__before, ___NS__bind, ___NS__bindAll, ___NS__bindKey, ___NS__camelCase, ___NS__capitalize, ___NS__castArray, ___NS__ceil, ___NS__chain, ___NS__chunk, ___NS__clamp, ___NS__clone, ___NS__cloneDeep, ___NS__cloneDeepWith, ___NS__cloneWith, ___NS__compact, ___NS__concat, ___NS__cond, ___NS__conforms, ___NS__conformsTo, ___NS__constant, ___NS__countBy, ___NS__create, ___NS__curry, ___NS__curryRight, ___NS__debounce, ___NS__deburr, ___NS__defaults, ___NS__defaultsDeep, ___NS__defaultTo, ___NS__defer, ___NS__delay, ___NS__difference, ___NS__differenceBy, ___NS__differenceWith, ___NS__divide, ___NS__drop, ___NS__dropRight, ___NS__dropRightWhile, ___NS__dropWhile, ___NS__each, ___NS__eachRight, ___NS__endsWith, ___NS__entries, ___NS__entriesIn, ___NS__eq, ___NS__escape, ___NS__escapeRegExp, ___NS__every, ___NS__extend, ___NS__extendWith, ___NS__fill, ___NS__filter, ___NS__find, ___NS__findIndex, ___NS__findKey, ___NS__findLast, ___NS__findLastIndex, ___NS__findLastKey, ___NS__first, ___NS__flatMap, ___NS__flatMapDeep, ___NS__flatMapDepth, ___NS__flatten, ___NS__flattenDeep, ___NS__flattenDepth, ___NS__flip, ___NS__floor, ___NS__flow, ___NS__flowRight, ___NS__forEach, ___NS__forEachRight, ___NS__forIn, ___NS__forInRight, ___NS__forOwn, ___NS__forOwnRight, ___NS__fromPairs, ___NS__functions, ___NS__functionsIn, ___NS__get, ___NS__groupBy, ___NS__gt, ___NS__gte, ___NS__has, ___NS__hasIn, ___NS__head, ___NS__identity, ___NS__includes, ___NS__indexOf, ___NS__initial, ___NS__inRange, ___NS__intersection, ___NS__intersectionBy, ___NS__intersectionWith, ___NS__invert, ___NS__invertBy, ___NS__invoke, ___NS__invokeMap, ___NS__isArguments, ___NS__isArray, ___NS__isArrayBuffer, ___NS__isArrayLike, ___NS__isArrayLikeObject, ___NS__isBoolean, ___NS__isBuffer, ___NS__isDate, ___NS__isElement, ___NS__isEmpty, ___NS__isEqual, ___NS__isEqualWith, ___NS__isError, ___NS__isFinite, ___NS__isFunction, ___NS__isInteger, ___NS__isLength, ___NS__isMap, ___NS__isMatch, ___NS__isMatchWith, ___NS__isNaN, ___NS__isNative, ___NS__isNil, ___NS__isNull, ___NS__isNumber, ___NS__isObject, ___NS__isObjectLike, ___NS__isPlainObject, ___NS__isRegExp, ___NS__isSafeInteger, ___NS__isSet, ___NS__isString, ___NS__isSymbol, ___NS__isTypedArray, ___NS__isUndefined, ___NS__isWeakMap, ___NS__isWeakSet, ___NS__iteratee, ___NS__join, ___NS__kebabCase, ___NS__keyBy, ___NS__keys, ___NS__keysIn, ___NS__last, ___NS__lastIndexOf, ___NS__lowerCase, ___NS__lowerFirst, ___NS__lt, ___NS__lte, ___NS__map, ___NS__mapKeys, ___NS__mapValues, ___NS__matches, ___NS__matchesProperty, ___NS__max, ___NS__maxBy, ___NS__mean, ___NS__meanBy, ___NS__memoize, ___NS__merge, ___NS__mergeWith, ___NS__method, ___NS__methodOf, ___NS__min, ___NS__minBy, ___NS__mixin, ___NS__multiply, ___NS__negate, ___NS__noop, ___NS__now, ___NS__nth, ___NS__nthArg, ___NS__omit, ___NS__omitBy, ___NS__once, ___NS__orderBy, ___NS__over, ___NS__overArgs, ___NS__overEvery, ___NS__overSome, ___NS__pad, ___NS__padEnd, ___NS__padStart, ___NS__parseInt, ___NS__partial, ___NS__partialRight, ___NS__partition, ___NS__pick, ___NS__pickBy, ___NS__property, ___NS__propertyOf, ___NS__pull, ___NS__pullAll, ___NS__pullAllBy, ___NS__pullAllWith, ___NS__pullAt, ___NS__random, ___NS__range, ___NS__rangeRight, ___NS__rearg, ___NS__reduce, ___NS__reduceRight, ___NS__reject, ___NS__remove, ___NS__repeat, ___NS__replace, ___NS__rest, ___NS__result, ___NS__reverse, ___NS__round, ___NS__sample, ___NS__sampleSize, ___NS__set, ___NS__setWith, ___NS__shuffle, ___NS__size, ___NS__slice, ___NS__snakeCase, ___NS__some, ___NS__sortBy, ___NS__sortedIndex, ___NS__sortedIndexBy, ___NS__sortedIndexOf, ___NS__sortedLastIndex, ___NS__sortedLastIndexBy, ___NS__sortedLastIndexOf, ___NS__sortedUniq, ___NS__sortedUniqBy, ___NS__split, ___NS__spread, ___NS__startCase, ___NS__startsWith, ___NS__stubArray, ___NS__stubFalse, ___NS__stubObject, ___NS__stubString, ___NS__stubTrue, ___NS__subtract, ___NS__sum, ___NS__sumBy, ___NS__tail, ___NS__take, ___NS__takeRight, ___NS__takeRightWhile, ___NS__takeWhile, ___NS__tap, ___NS__template, ___NS__templateSettings, ___NS__throttle, ___NS__thru, ___NS__times, ___NS__toArray, ___NS__toFinite, ___NS__toInteger, ___NS__toLength, ___NS__toLower, ___NS__toNumber, ___NS__toPairs, ___NS__toPairsIn, ___NS__toPath, ___NS__toPlainObject, ___NS__toSafeInteger, ___NS__toString, ___NS__toUpper, ___NS__transform, ___NS__trim, ___NS__trimEnd, ___NS__trimStart, ___NS__truncate, ___NS__unary, ___NS__unescape, ___NS__union, ___NS__unionBy, ___NS__unionWith, ___NS__uniq, ___NS__uniqBy, ___NS__uniqueId, ___NS__uniqWith, ___NS__unset, ___NS__unzip, ___NS__unzipWith, ___NS__update, ___NS__updateWith, ___NS__upperCase, ___NS__upperFirst, ___NS__values, ___NS__valuesIn, ___NS__without, ___NS__words, ___NS__wrap, ___NS__xor, ___NS__xorBy, ___NS__xorWith, ___NS__zip, ___NS__zipObject, ___NS__zipObjectDeep, ___NS__zipWith, Helpers__NS___fixCommand, Helpers__NS__bigMaxBuffer, Helpers__NS__checkProcess, Helpers__NS__cleanExit, Helpers__NS__clearConsole, Helpers__NS__command, Helpers__NS__commandOutputAsString, Helpers__NS__commandOutputAsStringAsync, Helpers__NS__compilationWrapper, Helpers__NS__contain, Helpers__NS__createFolder, Helpers__NS__createSymLink, Helpers__NS__error, Helpers__NS__execute, Helpers__NS__exists, Helpers__NS__filesFrom, Helpers__NS__foldersFrom, Helpers__NS__getFilesFrom, Helpers__NS__getFoldersFrom, Helpers__NS__getIsBrowser, Helpers__NS__getIsElectron, Helpers__NS__getIsNode, Helpers__NS__getIsRunningInGitBash, Helpers__NS__getIsSupportedTaonTerminal, Helpers__NS__getIsVerboseMode, Helpers__NS__getIsWebSQL, Helpers__NS__getIsWsl, Helpers__NS__getStdio, Helpers__NS__hideNodeWarnings, Helpers__NS__info, Helpers__NS__isBlob, Helpers__NS__isBuffer, Helpers__NS__isClass, Helpers__NS__isExistedSymlink, Helpers__NS__isFile, Helpers__NS__isFolder, Helpers__NS__isRunningInDocker, Helpers__NS__isRunningInLinuxGraphicsCapableEnvironment, Helpers__NS__isSymlinkFileExitedOrUnexisted, Helpers__NS__isSymlinkThatMatchesUrl, Helpers__NS__isUnexistedLink, Helpers__NS__killOnPort, Helpers__NS__killProcess, Helpers__NS__killProcessByPort, Helpers__NS__linksToFolderFrom, Helpers__NS__linksToFoldersFrom, Helpers__NS__log, Helpers__NS__logError, Helpers__NS__logInfo, Helpers__NS__logProc, Helpers__NS__logSuccess, Helpers__NS__logWarn, Helpers__NS__mediaTypeFromSrc, Helpers__NS__mkdirp, Helpers__NS__modifyLineByLine, Helpers__NS__msgCacheClear, Helpers__NS__openFolderInFileExplorer, Helpers__NS__parse, Helpers__NS__pathContainLink, Helpers__NS__questionYesNo, Helpers__NS__readFile, Helpers__NS__readJson, Helpers__NS__readJson5, Helpers__NS__readJsonC, Helpers__NS__relative, Helpers__NS__remove, Helpers__NS__removeEmptyLineFromString, Helpers__NS__removeFileIfExists, Helpers__NS__removeFolderIfExists, Helpers__NS__removeIfExists, Helpers__NS__removeSlashAtBegin, Helpers__NS__removeSlashAtEnd, Helpers__NS__removeSymlinks, Helpers__NS__renderError, Helpers__NS__replaceLinesInFile, Helpers__NS__run, Helpers__NS__runAsyncIn, Helpers__NS__runSyncIn, Helpers__NS__runSyncOrAsync, Helpers__NS__sleep, Helpers__NS__stopApplication, Helpers__NS__stringify, Helpers__NS__success, Helpers__NS__taskDone, Helpers__NS__taskStarted, Helpers__NS__throwError, Helpers__NS__timeout, Helpers__NS__tryCatchError, Helpers__NS__tryReadFile, Helpers__NS__tryRemoveDir, Helpers__NS__values, Helpers__NS__wait, Helpers__NS__warn, Helpers__NS__writeFile, Helpers__NS__writeJson, Helpers__NS__writeJson5, Helpers__NS__writeJsonC } from 'tnp-core/lib-prod';
41
-
42
- import type { TaonBaseClass } from './base-classes/base-class';
43
- import type { TaonBaseController } from './base-classes/base-controller';
44
- import type { TaonBaseInjector } from './base-classes/base-injector';
45
- import type { TaonBaseMiddleware } from './base-classes/base-middleware';
46
- import type { TaonBaseMigration } from './base-classes/base-migration';
47
- import { TaonBaseSubscriberForEntity } from './base-classes/base-subscriber-for-entity';
48
- import type { ControllerConfig } from './config/controller-config';
49
- import { MethodConfig } from './config/method-config';
50
- import { ParamConfig } from './config/param-config';
51
- import { apiPrefix } from './constants';
52
- import { ContextDbMigrations } from './context-db-migrations';
53
- import { createContext } from './create-context';
54
- import { TaonEntityOptions } from './decorators/classes/entity-decorator';
55
- import { TaonSubscriberOptions } from './decorators/classes/subscriber-decorator';
56
- import { DITaonContainer } from './dependency-injection/di-container';
57
- import type { ContextsEndpointStorage } from './endpoint-context-storage';
58
- import { EntityProcess } from './entity-process';
59
- import { getResponseValue } from './get-response-value';
60
- import { ClassHelpers__NS__asyncHandler, ClassHelpers__NS__ensureClassConfig, ClassHelpers__NS__ensureMethodConfig, ClassHelpers__NS__getClassConfig, ClassHelpers__NS__getClassFnFromObject, ClassHelpers__NS__getControllerConfigs, ClassHelpers__NS__getFullInternalName, ClassHelpers__NS__getMethodsNames, ClassHelpers__NS__getName, ClassHelpers__NS__getOrginalClass, ClassHelpers__NS__getUniqueKey, ClassHelpers__NS__hasParentClassWithName, ClassHelpers__NS__isContextClassObject, ClassHelpers__NS__setName } from './helpers/class-helpers';
61
- import { TaonHelpers__NS__defaultType, TaonHelpers__NS__fillUpTo, TaonHelpers__NS__firstStringOrElemFromArray, TaonHelpers__NS__getExpressPath, TaonHelpers__NS__ipcKeyNameRequest, TaonHelpers__NS__ipcKeyNameResponse, TaonHelpers__NS__isGoodPath, TaonHelpers__NS__isPlainFileOrFolder, TaonHelpers__NS__parseJSONwithStringJSONs, TaonHelpers__NS__tryTransformParam, TaonHelpers__NS__websqlMocks } from './helpers/taon-helpers';
62
- import { Models__NS__ClassType, Models__NS__ClassTypeKey, Models__NS__ConnectionOptionsLogs, Models__NS__ContextOptions, Models__NS__DatabaseConfig, Models__NS__DatabaseConfigTypeOrm, Models__NS__DatabasesFolder, Models__NS__DBRecreateMode, Models__NS__FrameworkMode, Models__NS__Http__NS__AsyncResponse, Models__NS__Http__NS__AuthCallBack, Models__NS__Http__NS__ClientAction, Models__NS__Http__NS__ContextENDPOINT, Models__NS__Http__NS__ExpressContext, Models__NS__Http__NS__FormlyFromType, Models__NS__Http__NS__MixResponse, Models__NS__Http__NS__Response, Models__NS__Http__NS__ResponseFuncOpt, Models__NS__Http__NS__SyncResponse, Models__NS__Http__NS__SyncResponseFunc, Models__NS__ISession, Models__NS__MiddlewareType, Models__NS__StartParams, Models__NS__TaonCtxCloneParams, Models__NS__TaonInitializeParams } from './models';
63
- import { RealtimeCore } from './realtime/realtime-core';
64
- import { Symbols__NS__classMethodsNames, Symbols__NS__classNameStaticProperty, Symbols__NS__ctxInClassOrClassObj, Symbols__NS__fullClassNameStaticProperty, Symbols__NS__metadata, Symbols__NS__old, Symbols__NS__orignalClass, Symbols__NS__orignalClassClonesObj, Symbols__NS__REALTIME } from './symbols';
65
- /* */
66
- //#endregion
67
-
68
- let bodyParser: typeof import('body-parser');
69
- let cookieParser: typeof import('cookie-parser');
70
- let cors: typeof import('cors');
71
- let express: typeof import('express');
72
- let methodOverride: typeof import('method-override');
73
- let expressSession: typeof import('express-session');
74
- //#region @backend
75
- bodyParser = requireDefault('body-parser');
76
- cookieParser = requireDefault('cookie-parser');
77
- cors = requireDefault('cors');
78
- express = requireDefault('express');
79
- methodOverride = requireDefault('method-override');
80
- expressSession = requireDefault('express-session');
81
- //#endregion
82
-
83
- export class EndpointContext {
84
- //#region fields
85
-
86
- //#region fields / use mariadb mysql in docker
87
- /**
88
- * JUST FOR TESTING PURPOSES
89
- */
90
- public readonly USE_MARIADB_MYSQL_IN_DOCKER: boolean = false;
91
- //#endregion
92
-
93
- //#region fields / flags
94
- disabledRealtime: boolean = false;
95
-
96
- /**
97
- * check whether context is inited
98
- * (with init() function )
99
- */
100
- public inited: boolean = false;
101
- //#endregion
102
-
103
- //#region fields / db migrations
104
- readonly dbMigrations = new ContextDbMigrations(this);
105
- //#endregion
106
-
107
- //#region fields / local instance obj symbol
108
- private readonly localInstaceObjSymbol = Symbol('localInstaceObjSymbol');
109
- //#endregion
110
-
111
- //#region fields / all instances of classes from context
112
- /**
113
- * all instances of classes from context
114
- * key is class name
115
- */
116
- public readonly allClassesInstances = {};
117
- //#endregion
118
-
119
- //#region fields / class instances by name
120
- private readonly classInstancesByNameObj = {};
121
- //#endregion
122
-
123
- //#region fields / obj with classes instances arr
124
- private readonly objWithClassesInstancesArr = {};
125
- //#endregion
126
-
127
- //#region fields / active routes
128
- public readonly activeRoutes: {
129
- expressPath: string;
130
- method: CoreModels__NS__HttpMethod;
131
- }[] = [];
132
- //#endregion
133
-
134
- //#region fields / typeorm repositories
135
- //#region @websql
136
- public repos = new Map<string, Repository<any>>();
137
- //#endregion
138
- //#endregion
139
-
140
- //#region fields / source context
141
- get sourceContext(): EndpointContext | undefined {
142
- return this.cloneOptions?.sourceContext;
143
- }
144
- //#endregion
145
-
146
- //#region fields / skip writing server routes
147
- public readonly skipWritingServerRoutes: boolean = false;
148
- //#endregion
149
-
150
- //#region fields / types from contexts
151
- private injectableTypesfromContexts = [
152
- Models__NS__ClassType.CONTROLLER,
153
- Models__NS__ClassType.PROVIDER,
154
- Models__NS__ClassType.MIDDLEWARE,
155
- Models__NS__ClassType.REPOSITORY,
156
- Models__NS__ClassType.SUBSCRIBER,
157
- Models__NS__ClassType.MIGRATION,
158
- ];
159
- //#endregion
160
-
161
- //#region fields / all types from contexts
162
- private allTypesfromContexts = [
163
- ...this.injectableTypesfromContexts,
164
- Models__NS__ClassType.ENTITY,
165
- ];
166
- //#endregion
167
-
168
- //#region fields / express app
169
- public expressApp: Application = {} as any;
170
- //#endregion
171
-
172
- //#region fields / server tcp udp
173
- public serverTcpUdp: Server;
174
- //#endregion
175
-
176
- //#region fields / database config
177
- databaseConfig?: Models__NS__DatabaseConfigTypeOrm;
178
- //#endregion
179
-
180
- //#region fields / mode
181
- mode: Models__NS__FrameworkMode;
182
- //#endregion
183
-
184
- //#region fields / only migration start
185
- readonly onlyMigrationRun?: boolean = false;
186
-
187
- readonly onlyMigrationRevertToTimestamp?: number = undefined;
188
-
189
- get isRunOrRevertOnlyMigrationAppStart(): boolean {
190
- return !!(this.onlyMigrationRun || this.onlyMigrationRevertToTimestamp);
191
- }
192
- //#endregion
193
-
194
- //#region fields / session
195
- session?: Models__NS__ISession;
196
- //#endregion
197
-
198
- //#region fields / connection
199
- public connection: DataSource;
200
- //#endregion
201
-
202
- //#region fields / entities triggers
203
- private entitiesTriggers = {};
204
- //#endregion
205
-
206
- //#region fields / realtime
207
- private realtime: RealtimeCore;
208
-
209
- get realtimeClient() {
210
- return this.realtime.client;
211
- }
212
-
213
- get realtimeServer() {
214
- return this.realtime.server;
215
- }
216
- //#endregion
217
-
218
- //#region fields / config
219
- /**
220
- * available after init()
221
- */
222
- public config: Models__NS__ContextOptions<any, any, any, any, any, any, any, any>;
223
- //#endregion
224
-
225
- //#region fields / logs
226
- get logHttp(): boolean {
227
- if (___NS__isObject(this.config?.logs)) {
228
- return !!(this.config.logs as Models__NS__ConnectionOptionsLogs).http;
229
- }
230
- return this.config?.logs === true;
231
- }
232
-
233
- get logRealtime(): boolean {
234
- if (___NS__isObject(this.config?.logs)) {
235
- return !!(this.config.logs as Models__NS__ConnectionOptionsLogs).realtime;
236
- }
237
- return this.config?.logs === true;
238
- }
239
-
240
- get logFramework(): boolean {
241
- if (___NS__isObject(this.config?.logs)) {
242
- return !!(this.config.logs as Models__NS__ConnectionOptionsLogs).framework;
243
- }
244
- return this.config?.logs === true;
245
- }
246
-
247
- get logRoutes(): boolean {
248
- if (___NS__isObject(this.config?.logs)) {
249
- return !!(this.config.logs as Models__NS__ConnectionOptionsLogs).routes;
250
- }
251
- return this.config?.logs === true;
252
- }
253
-
254
- get logDb(): boolean {
255
- if (___NS__isObject(this.config?.logs)) {
256
- return !!(this.config.logs as Models__NS__ConnectionOptionsLogs).db;
257
- }
258
- return this.config?.logs === true;
259
- }
260
-
261
- get logMigrations(): boolean {
262
- if (___NS__isObject(this.config?.logs)) {
263
- return !!(this.config.logs as Models__NS__ConnectionOptionsLogs).migrations;
264
- }
265
- return this.config?.logs === true;
266
- }
267
- //#endregion
268
-
269
- //#endregion
270
-
271
- //#region constructor
272
- /**
273
- * Inside docker there is not need for https secure server
274
- */
275
- public readonly isRunningInsideDocker: boolean = false;
276
-
277
- constructor(
278
- private originalConfig: Models__NS__ContextOptions<
279
- any,
280
- any,
281
- any,
282
- any,
283
- any,
284
- any,
285
- any,
286
- any
287
- >,
288
- private configFn: (
289
- env: any,
290
- ) => Models__NS__ContextOptions<any, any, any, any, any, any, any, any>,
291
- /**
292
- * (@default: false)
293
- * If TRUE context is NOT going to create db/express server/http endpoints
294
- * PURPOSE OF THIS PROPERTY
295
- * -> ONLY remote access from backend or frontend to specific backend
296
- */
297
- private readonly cloneOptions: Models__NS__TaonCtxCloneParams,
298
- ) {
299
- this.cloneOptions = this.cloneOptions || {};
300
- this.isRunningInsideDocker = UtilsOs__NS__isRunningInDocker();
301
- }
302
- //#endregion
303
-
304
- //#region methods & getters / init
305
- public async init(options?: {
306
- initFromRecrusiveContextResovle?: boolean;
307
- onlyMigrationRun?: boolean;
308
- onlyMigrationRevertToTimestamp?: number;
309
- }) {
310
- const {
311
- initFromRecrusiveContextResovle,
312
- onlyMigrationRun,
313
- onlyMigrationRevertToTimestamp,
314
- } = options || {}; // TODO use it ?
315
-
316
- this.inited = true;
317
- // @ts-ignore
318
- this.onlyMigrationRun = onlyMigrationRun;
319
- // @ts-ignore
320
- this.onlyMigrationRevertToTimestamp = onlyMigrationRevertToTimestamp;
321
- this.config = this.configFn({});
322
- if (___NS__isObject(this.config.database)) {
323
- this.config.database = Models__NS__DatabaseConfig.from(
324
- this.config.database as Models__NS__DatabaseConfig,
325
- ).databaseConfigTypeORM;
326
- }
327
-
328
- this.config.host = this.host === null ? void 0 : this.host;
329
-
330
- if (
331
- this.cloneOptions.overrideHost &&
332
- !this.cloneOptions.useAsRemoteContext
333
- ) {
334
- this.config.host = this.cloneOptions.overrideHost;
335
- }
336
-
337
- if (
338
- this.cloneOptions.overrideRemoteHost &&
339
- this.cloneOptions.useAsRemoteContext
340
- ) {
341
- this.config.host = this.cloneOptions.overrideRemoteHost;
342
- }
343
-
344
- if (
345
- this.config.host &&
346
- !this.config.host.startsWith('http://') &&
347
- !this.config.host.startsWith('https://')
348
- ) {
349
- Helpers__NS__throwError(
350
- `[taon-config] Your${this.host ? ' remote' : ''} 'host' must start with http:// or https://`,
351
- );
352
- }
353
-
354
- if (___NS__isUndefined(this.config.useIpcWhenElectron)) {
355
- this.config.useIpcWhenElectron = true;
356
- }
357
- // console.log(`config for ${this.contextName}`, this.config);
358
-
359
- //#region resolve if skipping writing server routes
360
- //@ts-expect-error overriding readonly
361
- this.skipWritingServerRoutes = ___NS__isBoolean(
362
- this.config.skipWritingServerRoutes,
363
- )
364
- ? this.config.skipWritingServerRoutes
365
- : false;
366
- //#endregion
367
-
368
- //#region resolve mode
369
- if (this.config.host) {
370
- this.mode = 'backend-frontend(tcp+udp)';
371
- /* */
372
- /* */
373
-
374
- }
375
-
376
- if (this.isRemoteHost) {
377
- this.mode = 'remote-backend(tcp+udp)';
378
- }
379
-
380
- // console.log(`
381
-
382
- // useIpcWhenElectron: ${this.config.useIpcWhenElectron}
383
- // UtilsOs__NS__isElectron: ${UtilsOs__NS__isElectron}
384
-
385
- // `)
386
- if (this.config.useIpcWhenElectron && UtilsOs__NS__isElectron) {
387
- if (UtilsOs__NS__isWebSQL) {
388
- this.mode = 'backend-frontend(websql-electron)';
389
- } else {
390
- this.mode = 'backend-frontend(ipc-electron)';
391
- }
392
- }
393
-
394
- // mode === undefined for TaonBaseContext => ok behavior
395
- // console.log(`Mode for BE/FE communication: ${this.mode}`);
396
- // if(!this.mode) {
397
- // console.log(this.config)
398
- // }
399
-
400
- if (!this.mode && !this.config.abstract) {
401
- const errMsg =
402
- `You need to provide host property or ` +
403
- `useIpcWhenElectron or mark it as abstract`;
404
- Helpers__NS__error(
405
- `[taon][Context=${this.contextName}]: ${errMsg}`,
406
- false,
407
- true,
408
- );
409
- //#region @backend
410
- process.exit(1);
411
- //#endregion
412
- }
413
- //#endregion
414
-
415
- //#region resolve database config
416
- if (this.config.database === true) {
417
- this.logFramework &&
418
- console.log(`
419
-
420
- ASSIGNING AUTO GENERATED DATABASE CONFIG
421
-
422
- `);
423
- this.databaseConfig = this.getAutoGeneratedConfig();
424
- } else if (___NS__isObject(this.config.database)) {
425
- this.logFramework &&
426
- console.log(`
427
-
428
- OVERRIDE DATABASE CONFIG FROM CONFIGURATION
429
-
430
- `);
431
- this.databaseConfig = this.getAutoGeneratedConfig();
432
- walk.Object(
433
- this.config.database,
434
- (value, lodashPath) => {
435
- if (___NS__isNil(value) || ___NS__isFunction(value) || ___NS__isObject(value)) {
436
- // skipping
437
- } else {
438
- this.logFramework &&
439
- console.info(
440
- `Overriding database config: ${lodashPath}=${value}`,
441
- );
442
- ___NS__set(this.databaseConfig, lodashPath, value);
443
- }
444
- },
445
- {
446
- walkGetters: false,
447
- },
448
- );
449
- }
450
- //#endregion
451
-
452
- //#region resolve session
453
- if (this.config.session) {
454
- this.session = ___NS__cloneDeep(this.config.session);
455
- const oneHour = 1000 * 60 * 60 * 1; // 24;
456
- if (!this.session.cookieMaxAge) {
457
- this.session.cookieMaxAge = oneHour;
458
- }
459
- // serever and browser cookie authentication
460
- axios.defaults.withCredentials = true;
461
- }
462
- //#endregion
463
-
464
- //#region prepare & gather all classes recursively
465
- this.config.contexts = this.config.contexts || {};
466
- this.config.entities = this.config.entities || {};
467
- this.config.controllers = this.config.controllers || {};
468
- this.config.repositories = this.config.repositories || {};
469
- this.config.providers = this.config.providers || {};
470
- this.config.subscribers = this.config.subscribers || {};
471
- this.config.migrations = this.config.migrations || {};
472
-
473
- this.config.entities = {
474
- ...(await this.getRecrusiveClassesfromContextsObj(
475
- Models__NS__ClassType.ENTITY,
476
- )),
477
- ...this.config.entities,
478
- };
479
-
480
- this.config.controllers = {
481
- ...(await this.getRecrusiveClassesfromContextsObj(
482
- Models__NS__ClassType.CONTROLLER,
483
- )),
484
- ...this.config.controllers,
485
- };
486
-
487
- this.config.providers = {
488
- ...(await this.getRecrusiveClassesfromContextsObj(
489
- Models__NS__ClassType.PROVIDER,
490
- )),
491
- ...this.config.providers,
492
- };
493
-
494
- this.config.middlewares = {
495
- ...(await this.getRecrusiveClassesfromContextsObj(
496
- Models__NS__ClassType.MIDDLEWARE,
497
- )),
498
- ...this.config.middlewares,
499
- };
500
-
501
- this.config.subscribers = {
502
- ...(await this.getRecrusiveClassesfromContextsObj(
503
- Models__NS__ClassType.SUBSCRIBER,
504
- )),
505
- ...this.config.subscribers,
506
- };
507
-
508
- this.config.repositories = {
509
- ...(await this.getRecrusiveClassesfromContextsObj(
510
- Models__NS__ClassType.REPOSITORY,
511
- )),
512
- ...this.config.repositories,
513
- };
514
-
515
- this.config.migrations = {
516
- ...(await this.getRecrusiveClassesfromContextsObj(
517
- Models__NS__ClassType.MIGRATION,
518
- )),
519
- ...this.config.migrations,
520
- };
521
-
522
- // console.log(this.config);
523
- // debugger;
524
- //#endregion
525
-
526
- //#region prepare classes instances/functions clones
527
- this.config.controllers = this.cloneClassesObjWithNewMetadata({
528
- classesInput: this.config.controllers,
529
- config: this.config,
530
- ctx: this,
531
- classType: Models__NS__ClassType.CONTROLLER,
532
- });
533
- this.config.repositories = this.cloneClassesObjWithNewMetadata({
534
- classesInput: this.config.repositories,
535
- config: this.config,
536
- ctx: this,
537
- classType: Models__NS__ClassType.REPOSITORY,
538
- });
539
- this.config.providers = this.cloneClassesObjWithNewMetadata({
540
- classesInput: this.config.providers,
541
- config: this.config,
542
- ctx: this,
543
- classType: Models__NS__ClassType.PROVIDER,
544
- });
545
- this.config.middlewares = this.cloneClassesObjWithNewMetadata({
546
- classesInput: this.config.middlewares,
547
- config: this.config,
548
- ctx: this,
549
- classType: Models__NS__ClassType.MIDDLEWARE,
550
- });
551
-
552
- this.config.subscribers = this.cloneClassesObjWithNewMetadata({
553
- classesInput: this.config.subscribers,
554
- config: this.config,
555
- ctx: this,
556
- classType: Models__NS__ClassType.SUBSCRIBER,
557
- });
558
-
559
- this.config.migrations = this.cloneClassesObjWithNewMetadata({
560
- classesInput: this.config.migrations,
561
- config: this.config,
562
- ctx: this,
563
- classType: Models__NS__ClassType.MIGRATION,
564
- });
565
- //#endregion
566
-
567
- //#region prepare instances
568
- for (const classTypeName of this.injectableTypesfromContexts) {
569
- this.classInstancesByNameObj[classTypeName] = {};
570
- this.objWithClassesInstancesArr[classTypeName] = [];
571
- }
572
-
573
- for (const classTypeName of this.injectableTypesfromContexts) {
574
- await this.createInstances(
575
- this.config[Models__NS__ClassTypeKey[classTypeName]],
576
- classTypeName,
577
- );
578
- }
579
- //#endregion
580
-
581
- if (!this.isRunOrRevertOnlyMigrationAppStart) {
582
- //#region prepares server
583
- if (this.mode === 'backend-frontend(tcp+udp)' && !this.config.abstract) {
584
- //#region @backend
585
- this.expressApp = express();
586
-
587
- if (process.env.NODE_ENV === 'production') {
588
- this.expressApp.set('trust proxy', 1);
589
- }
590
-
591
- await this.initBackendMiddlewares();
592
- await this.initCustomBackendMiddlewares();
593
- const shouldStartHttpsSecureServer =
594
- this.isHttpServer && !this.isRunningInsideDocker;
595
- this.logFramework &&
596
- Helpers__NS__info(`
597
-
598
- Starting server ${
599
- shouldStartHttpsSecureServer ? 'with' : 'without'
600
- } HTTPS secure server
601
-
602
- `);
603
- this.serverTcpUdp = shouldStartHttpsSecureServer
604
- ? new https.Server(
605
- {
606
- key: this.config.https?.key,
607
- cert: this.config.https?.cert,
608
- },
609
- this.expressApp,
610
- )
611
- : new http.Server(this.expressApp);
612
- this.publicAssets.forEach(asset => {
613
- this.expressApp.use(
614
- asset.serverPath,
615
- express.static(asset.locationOnDisk),
616
- );
617
- });
618
- //#endregion
619
-
620
- await this.initCustomClientMiddlewares();
621
- }
622
- //#endregion
623
-
624
- //#region prepare realtime
625
- if (!this.config.abstract) {
626
- this.disabledRealtime = this.config.disabledRealtime;
627
- if (!this.host) {
628
- throw `
629
-
630
- host is required for context initialization..
631
- (Or maybe you forgot mark ${this.config.contextName} context as abstract?)
632
-
633
- `;
634
- }
635
-
636
- //#region @backend
637
- // if (UtilsOs__NS__isRunningInCliMode() && !___NS__isNil(this.config.disabledRealtime)) {
638
- // // TODO for now...
639
- // Helpers__NS__logInfo(`Realtime disable on backend for cli mode`);
640
- // this.disabledRealtime = true;
641
- // } else {
642
- // Helpers__NS__logInfo(`Realtime enabled on backend`);
643
- // }
644
- //#endregion
645
-
646
- this.logRealtime &&
647
- Helpers__NS__info(
648
- `[ctx=${this.contextName}] Init Realtime for ${this.mode}`,
649
- );
650
-
651
- this.realtime = new RealtimeCore(this);
652
- }
653
- //#endregion
654
- }
655
-
656
- //#region show context info
657
- // console.log({ ref })
658
- if (this.config.abstract) {
659
- this.logFramework &&
660
- Helpers__NS__info(
661
- `[taon] Create abstract context: ${this.config.contextName}`,
662
- );
663
- } else {
664
- if (this.isRemoteHost) {
665
- this.logFramework &&
666
- Helpers__NS__info(
667
- `[taon] Create context for remote host: ${this.config.host}`,
668
- );
669
- } else {
670
- this.logFramework &&
671
- Helpers__NS__info(`[taon] Create context for host: ${this.config.host}`);
672
- }
673
- }
674
- //#endregion
675
-
676
- // update first exposed config
677
- Object.keys(this.config).forEach(key => {
678
- this.originalConfig[key] = this.config[key];
679
- });
680
- }
681
- //#endregion
682
-
683
- //#region methods & getters / get auto generated config
684
- private getAutoGeneratedConfig(): Models__NS__DatabaseConfigTypeOrm {
685
- this.logFramework &&
686
- console.log(`
687
-
688
-
689
- IS RUNNING IN DOCKER: ${this.isRunningInsideDocker}
690
-
691
- `);
692
- //#region @websqlFunc
693
- let databaseConfig: Models__NS__DatabaseConfig = Models__NS__DatabaseConfig.from({});
694
- const tcpUdpDatabaseSqliteRelativeFileLocation = `${Models__NS__DatabasesFolder}/db-${this.contextName}.sqlite`;
695
- if (this.isRunningInsideDocker) {
696
- if (this.USE_MARIADB_MYSQL_IN_DOCKER) {
697
- // Helpers__NS__info('Running in docker, using in mysql database');
698
- // // TODO auto resolve database config in docker
699
- // databaseConfig = Models__NS__DatabaseConfig.from({
700
- // database: `db-${this.contextName}.sqlite`,
701
- // type: 'mysql',
702
- // recreateMode: 'PRESERVE_DATA+MIGRATIONS',
703
- // logging: this.logDb,
704
- // databasePort: 3306,
705
- // databaseHost: 'localhost',
706
- // databaseUsername: 'root',
707
- // databasePassword: 'admin',
708
- // });
709
- } else {
710
- // TOOD @LAST for now.. just use sqljs in docker
711
- this.logFramework &&
712
- console.log(`
713
-
714
- USING GENERATED CONFIG FOR SQLJS IN DOCKER
715
-
716
- `);
717
-
718
- //#region @backend
719
- const locationOfTheDatabase = crossPlatformPath([
720
- process.cwd(),
721
- `db-${this.contextName}.sqlite`,
722
- ]);
723
- //#endregion
724
-
725
- databaseConfig = databaseConfig = Models__NS__DatabaseConfig.from({
726
- location: tcpUdpDatabaseSqliteRelativeFileLocation,
727
- type: 'sqljs',
728
- useLocalForage: false,
729
- recreateMode: 'PRESERVE_DATA+MIGRATIONS',
730
- logging: true,
731
- });
732
-
733
- //#region @backend
734
- if (!fse.existsSync(locationOfTheDatabase)) {
735
- databaseConfig.recreateMode = 'DROP_DB+MIGRATIONS';
736
- }
737
- // TODO @LAST add same thing for mariadb/mysql
738
- this.logFramework &&
739
- console.log(`
740
- location of database: ${locationOfTheDatabase}
741
- db file exists: ${fse.existsSync(locationOfTheDatabase)}
742
- synchronize: ${databaseConfig.synchronize}
743
- dropSchema: ${databaseConfig.dropSchema}
744
- `);
745
- //#endregion
746
- }
747
- } else {
748
- //#region auto resolve db config
749
- this.logFramework &&
750
- Helpers__NS__info(
751
- `[taon][database] Automatically resolving database config for mode ${this.mode}`,
752
- );
753
- switch (this.mode) {
754
- //#region resolve database config for backend-frontend(ipc-electron)
755
- case 'backend-frontend(ipc-electron)':
756
- let dbLocationInOs: string;
757
- //#region @backend
758
- if (UtilsOs__NS__isElectron) {
759
- dbLocationInOs = crossPlatformPath([
760
- UtilsOs__NS__getRealHomeDir(),
761
- `.taon/databases-for-electron-apps/${
762
- this.appId || ___NS__snakeCase(process.cwd()).replace(/\_/, '.')
763
- }/${this.contextName}.sqlite`,
764
- ]);
765
- if (!Helpers__NS__exists(path.dirname(dbLocationInOs))) {
766
- Helpers__NS__mkdirp(path.dirname(dbLocationInOs));
767
- }
768
- }
769
- //#endregion
770
-
771
- databaseConfig = Models__NS__DatabaseConfig.from({
772
- location: UtilsOs__NS__isElectron
773
- ? dbLocationInOs
774
- : `db-${this.contextName}.sqlite`,
775
- type: 'sqljs',
776
- recreateMode: 'DROP_DB+MIGRATIONS',
777
- logging: this.logDb,
778
- });
779
- break;
780
- //#endregion
781
-
782
- //#region resolve database config for mode backend-frontend(websql)
783
- case 'backend-frontend(websql-electron)':
784
- case 'backend-frontend(websql)':
785
- let keepWebsqlDbDataAfterReload = false;
786
- /* */
787
- /* */
788
- /* */
789
-
790
-
791
- databaseConfig = databaseConfig = Models__NS__DatabaseConfig.from({
792
- location: `db-${this.contextName}.sqlite`,
793
- type: 'sqljs',
794
- useLocalForage: true, // !!window['localforage'], // TODO this need to be checked in runtime
795
- recreateMode: keepWebsqlDbDataAfterReload
796
- ? 'PRESERVE_DATA+MIGRATIONS'
797
- : 'DROP_DB+MIGRATIONS',
798
- logging: this.logDb,
799
- });
800
- break;
801
- //#endregion
802
-
803
- //#region resolve database config for mode backend-frontend(tcp+udp)
804
- case 'backend-frontend(tcp+udp)':
805
- databaseConfig = Models__NS__DatabaseConfig.from({
806
- database: `context-db-${this.contextName}`,
807
- location: tcpUdpDatabaseSqliteRelativeFileLocation,
808
- type: 'sqljs',
809
- recreateMode: 'DROP_DB+MIGRATIONS',
810
- logging: this.logDb,
811
- });
812
- break;
813
- //#endregion
814
- }
815
- //#endregion
816
- }
817
- return databaseConfig.databaseConfigTypeORM;
818
- //#endregion
819
- }
820
- //#endregion
821
-
822
- //#region methods & getters / start server
823
- async startServer(): Promise<void> {
824
- //#region @backendFunc
825
- if (this.isRemoteHost || this.isRunOrRevertOnlyMigrationAppStart) {
826
- return;
827
- }
828
- if (this.mode === 'backend-frontend(tcp+udp)') {
829
- return await new Promise(resolve => {
830
- if (this.isRunningInsideDocker) {
831
- // this.displayRoutes(this.expressApp);
832
- this.serverTcpUdp.listen(Number(this.uriPort), '0.0.0.0', () => {
833
- this.logFramework &&
834
- Helpers__NS__log(
835
- `[ctx=${this.contextName}] Express server (inside docker) started 0.0.0.0:${this.uriPort}`,
836
- );
837
- this.logFramework &&
838
- Helpers__NS__log(`[taon][express-server]listening on port: ${this.uriPort}, hostname: ${this.uriPathname},
839
- address: ${this.uriProtocol}//localhost:${this.uriPort}${this.uriPathname}
840
- ExpressJS mode: ${this.expressApp.settings.env}
841
- `);
842
- resolve(void 0);
843
- });
844
- } else {
845
- // this.displayRoutes(this.expressApp);
846
- this.serverTcpUdp.listen(Number(this.uriPort), () => {
847
- this.logFramework &&
848
- Helpers__NS__log(
849
- `[ctx=${this.contextName}] Express server (inside nodejs app) started on localhost:${this.uriPort}`,
850
- );
851
- this.logFramework &&
852
- Helpers__NS__log(`[taon][express-server]listening on port: ${this.uriPort}, hostname: ${this.uriPathname},
853
- address: ${this.uriProtocol}//localhost:${this.uriPort}${this.uriPathname}
854
- expressJS mode: ${this.expressApp.settings.env}
855
- `);
856
- resolve(void 0);
857
- });
858
- }
859
- });
860
- } else {
861
- this.logFramework &&
862
- Helpers__NS__info('Ipc communication enable instead tcp/upd');
863
- }
864
- //#endregion
865
- }
866
- //#endregion
867
-
868
- //#region methods & getters / display express routes
869
- displayRoutes(app) {
870
- //#region @backend
871
- const routes = [];
872
-
873
- app._router?.stack.forEach(function (middleware) {
874
- if (middleware.route) {
875
- // routes registered directly on the app
876
- const methods = [];
877
- for (let method in middleware.route.methods) {
878
- if (middleware.route.methods[method]) {
879
- methods.push(method.toUpperCase());
880
- }
881
- }
882
- routes.push({ path: middleware.route.path, methods: methods });
883
- } else if (middleware.name === 'router') {
884
- // router middleware
885
- middleware.handle.stack.forEach(function (handler) {
886
- const methods = [];
887
- for (let method in handler.route.methods) {
888
- if (handler.route.methods[method]) {
889
- methods.push(method.toUpperCase());
890
- }
891
- }
892
- routes.push({ path: handler.route.path, methods: methods });
893
- });
894
- }
895
- });
896
-
897
- console.log(routes);
898
- //#endregion
899
- }
900
- //#endregion
901
-
902
- //#region methods & getters / mode allows database creation
903
- get modeAllowsDatabaseCreation() {
904
- return (
905
- this.mode === 'backend-frontend(tcp+udp)' ||
906
- this.mode === 'backend-frontend(websql)' ||
907
- this.mode === 'backend-frontend(ipc-electron)'
908
- );
909
- }
910
- //#endregion
911
-
912
- //#region methods & getters / clone class
913
- private cloneClassWithNewMetadata = <
914
- T extends { new (...args: any[]): any },
915
- >({
916
- TaonBaseClass,
917
- className,
918
- config,
919
- ctx,
920
- classType,
921
- }: {
922
- TaonBaseClass: T;
923
- className: string;
924
- config: Models__NS__ContextOptions<any, any, any, any, any, any, any, any>;
925
- ctx: EndpointContext;
926
- classType: Models__NS__ClassType;
927
- }): T => {
928
- // Return a new class that extends the base class
929
- const cloneClass = () => {
930
- if (
931
- TaonBaseClass[Symbols__NS__fullClassNameStaticProperty] ===
932
- `${ctx.contextName}.${className}`
933
- ) {
934
- return TaonBaseClass;
935
- }
936
- return class extends TaonBaseClass {
937
- // static ['_'] = TaonBaseClass['_'];
938
-
939
- // @ts-ignore
940
- static [Symbols__NS__orignalClass] = TaonBaseClass;
941
-
942
- // @ts-ignore
943
- static [Symbols__NS__fullClassNameStaticProperty] = `${ctx.contextName}.${className}`;
944
-
945
- // @ts-ignore
946
- static [Symbols__NS__classNameStaticProperty] = className;
947
-
948
- static [Symbols__NS__ctxInClassOrClassObj] = ctx;
949
-
950
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
951
- static __getFullPathForClass__(arr = []) {
952
- const name = this[Symbols__NS__fullClassNameStaticProperty];
953
- arr.push(name);
954
- // @ts-ignore
955
- if (
956
- this[Symbols__NS__orignalClass] && // @ts-ignore
957
- this[Symbols__NS__orignalClass].__getFullPathForClass__
958
- ) {
959
- // @ts-ignore
960
- this[Symbols__NS__orignalClass].__getFullPathForClass__(arr);
961
- }
962
- return arr.join('/');
963
- }
964
-
965
- static get fullPathForClass(): string {
966
- return this.__getFullPathForClass__();
967
- }
968
-
969
- [Symbols__NS__ctxInClassOrClassObj] = ctx;
970
- // You can override prototype properties or methods here if needed
971
- // static properties override allowed
972
- };
973
- };
974
-
975
- const cloneClassFunction = cloneClass();
976
-
977
- //#region gather all instances for all contexts
978
- // TODO this is not needed anymore - for typeorm I use normal entities
979
- // this thinng belowe is nice for debugging purpose
980
- // if (___NS__isUndefined(cloneClassFunction[Symbols__NS__orignalClassClonesObj])) {
981
- // cloneClassFunction[Symbols__NS__orignalClassClonesObj] = {};
982
- // }
983
- // if (___NS__isUndefined(TaonBaseClass[Symbols__NS__orignalClassClonesObj])) {
984
- // TaonBaseClass[Symbols__NS__orignalClassClonesObj] = {};
985
- // }
986
- // const all = {
987
- // ...TaonBaseClass[Symbols__NS__orignalClassClonesObj],
988
- // ...cloneClassFunction[Symbols__NS__orignalClassClonesObj],
989
- // };
990
- // all[ctx.contextName] = cloneClassFunction;
991
- // cloneClassFunction[Symbols__NS__orignalClassClonesObj] = all;
992
- // TaonBaseClass[Symbols__NS__orignalClassClonesObj] = all;
993
- //#endregion
994
-
995
- return cloneClassFunction;
996
- };
997
-
998
- //#endregion
999
-
1000
- //#region methods & getters / clone classes obj with new metadata
1001
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
1002
- private cloneClassesObjWithNewMetadata = ({
1003
- classesInput,
1004
- config,
1005
- ctx,
1006
- classType,
1007
- }: {
1008
- classesInput: any;
1009
- config: Models__NS__ContextOptions<any, any, any, any, any, any, any, any>;
1010
- ctx: EndpointContext;
1011
- classType: Models__NS__ClassType;
1012
- }) => {
1013
- const classes = {};
1014
- // console.log(Object.keys(classesInput))
1015
- for (const key of Object.keys(classesInput || {})) {
1016
- const TaonBaseClass = classesInput[key];
1017
-
1018
- if (!TaonBaseClass) {
1019
- Helpers__NS__error(`Class ${key} is not defined in context ${ctx.contextName}
1020
-
1021
- Please check if you have correct import in context file
1022
-
1023
- `);
1024
- }
1025
-
1026
- var className = Reflect.getMetadata(
1027
- Symbols__NS__metadata.className,
1028
- TaonBaseClass,
1029
- );
1030
-
1031
- // console.log('Metadata className', className, TaonBaseClass);
1032
- // if (!className) {
1033
- // console.warn(`Please provide className for ${TaonBaseClass.name} class`);
1034
- // }
1035
- className = className || key;
1036
- TaonBaseClass[Symbols__NS__classNameStaticProperty] = className;
1037
-
1038
- const clonedClass = this.cloneClassWithNewMetadata({
1039
- TaonBaseClass,
1040
- className,
1041
- config,
1042
- ctx,
1043
- classType,
1044
- });
1045
- classes[className] = clonedClass;
1046
- }
1047
- return classes;
1048
- };
1049
- //#endregion
1050
-
1051
- //#region methods & getters / get recursive classes from contexts
1052
- private async getRecrusiveClassesfromContextsObj(
1053
- classType: Models__NS__ClassType,
1054
- ) {
1055
- const arr = await this.getRecrusiveClassesfromContexts(classType);
1056
- return arr.reduce((acc, c) => {
1057
- acc[ClassHelpers__NS__getName(c)] = c;
1058
- return acc;
1059
- }, {});
1060
- }
1061
-
1062
- private async getRecrusiveClassesfromContexts(
1063
- classType: Models__NS__ClassType,
1064
- arr = [],
1065
- ) {
1066
- const contexts = Object.values(this.config.contexts || {}) as ReturnType<
1067
- typeof createContext
1068
- >[];
1069
- // console.log({
1070
- // contexts,
1071
- // });
1072
- for (const ctx of contexts) {
1073
- // console.log(`STARTING ${ctx.contextName}`);
1074
- const ref = await ctx.__ref();
1075
- // console.log(`CTX FROM ${ctx.contextName}`, ref.contextName);
1076
- const classesInput = ref.getClassFunBy(classType);
1077
- // console.log(`${ref.contextName} - ${classType}`, { classesInput });
1078
-
1079
- const clonedClasses = Object.values(
1080
- this.cloneClassesObjWithNewMetadata({
1081
- classesInput,
1082
- config: this.config,
1083
- ctx: this,
1084
- classType,
1085
- }),
1086
- );
1087
- // console.log(`${classType} clonedClasses`, clonedClasses);
1088
- clonedClasses.forEach(c => arr.push(c));
1089
-
1090
- await ref.getRecrusiveClassesfromContexts(classType, arr);
1091
- }
1092
- return arr as Function[];
1093
- }
1094
- //#endregion
1095
-
1096
- //#region methods & getters / get class instances by class type
1097
- getClassInstanceObjBy(classType: Models__NS__ClassType): any {
1098
- return this.classInstancesByNameObj[classType];
1099
- }
1100
- //#endregion
1101
-
1102
- //#region methods & getters / get class instances arr
1103
- private getClassesInstancesArrBy(classType: Models__NS__ClassType): any[] {
1104
- return this.objWithClassesInstancesArr[classType];
1105
- }
1106
- //#endregion
1107
-
1108
- //#region methods & getters / inject
1109
- inject<T>(
1110
- ctor: new (...args: any[]) => T,
1111
- options: {
1112
- localInstance?: boolean;
1113
- contextClassInstance?: TaonBaseInjector;
1114
- locaInstanceConstructorArgs?: ConstructorParameters<typeof ctor>;
1115
- parentInstanceThatWillGetInjectedStuff: object;
1116
- },
1117
- ): T {
1118
- const className = ClassHelpers__NS__getName(ctor);
1119
-
1120
- const locaInstanceConstructorArgs =
1121
- options.locaInstanceConstructorArgs || [];
1122
-
1123
- if (this.isCLassType(Models__NS__ClassType.REPOSITORY, ctor)) {
1124
- options.localInstance = true;
1125
- }
1126
-
1127
- if (options?.localInstance) {
1128
- const ctxClassFn = this.getClassFunByClassName(className);
1129
- let entityName: string = '';
1130
-
1131
- // entity thing is only for repositories local repositories
1132
- // if (className === 'TaonBaseRepository') {
1133
- const entityFn = ___NS__first(locaInstanceConstructorArgs);
1134
- const entity = entityFn && entityFn();
1135
- entityName = (entity && ClassHelpers__NS__getName(entity)) || '';
1136
- // console.log(`entityName `, entityName);
1137
- // }
1138
-
1139
- if (!options.contextClassInstance[this.localInstaceObjSymbol]) {
1140
- options.contextClassInstance[this.localInstaceObjSymbol] = {};
1141
- }
1142
- const instanceKey = className + (entityName ? `.${entityName}` : '');
1143
-
1144
- const existed =
1145
- options.contextClassInstance[this.localInstaceObjSymbol][instanceKey];
1146
-
1147
- if (existed) {
1148
- // console.log(
1149
- // `EXISTED ${ClassHelpers__NS__getName(options.parentInstanceThatWillGetInjectedStuff)} Inject ${className} instanceKey "${instanceKey}"`,
1150
- // );
1151
- return existed;
1152
- }
1153
-
1154
- // console.log(
1155
- // `NEW ${ClassHelpers__NS__getName(options.parentInstanceThatWillGetInjectedStuff)} Inject ${className} instanceKey "${instanceKey}"`,
1156
- // );
1157
-
1158
- if (!ctxClassFn) {
1159
- throw new Error(`Not able to inject "${className}" inside context "${this.contextName}"
1160
-
1161
- Make sure they share the same context or import context where "${className}" is defined.
1162
-
1163
- `);
1164
- }
1165
-
1166
- const injectedInstance = new (ctxClassFn as any)(
1167
- ...locaInstanceConstructorArgs,
1168
- );
1169
- options.contextClassInstance[this.localInstaceObjSymbol][instanceKey] =
1170
- injectedInstance;
1171
- // console.log(`injectedInstance `, existed)
1172
- return injectedInstance;
1173
- }
1174
-
1175
- const contextScopeInstance = this.allClassesInstances[className];
1176
- // if (className === 'TopicController') {
1177
- // debugger;
1178
- // }
1179
- return contextScopeInstance;
1180
- }
1181
-
1182
- /**
1183
- * alias for inject
1184
- */
1185
- getInstanceBy<T>(ctor: new (...args: any[]) => T): T {
1186
- // if (!!this.__contextForControllerInstanceAccess) {
1187
- // const className = ClassHelpers__NS__getName(ctor);
1188
- // const allControllers = this.getClassFunByArr(Models__NS__ClassType.CONTROLLER);
1189
-
1190
- // // TODO QUICK_FIX cache controllers
1191
- // for (const ctrl of allControllers) {
1192
- // if (ClassHelpers__NS__getName(ctrl) === className) {
1193
- // // console.log('injecting from contextForControllerInstanceAcesss', className);
1194
- // return this.__contextForControllerInstanceAccess.inject(ctor, {
1195
- // localInstance: false,
1196
- // });
1197
- // }
1198
- // }
1199
- // }
1200
-
1201
- return this.inject(ctor, {
1202
- localInstance: false,
1203
- parentInstanceThatWillGetInjectedStuff: this,
1204
- });
1205
- }
1206
- //#endregion
1207
-
1208
- //#region methods & getters / check if context initialized
1209
- checkIfContextInitialized() {
1210
- if (___NS__isUndefined(this.config)) {
1211
- throw new Error(`Please check if your context has been initialized.
1212
-
1213
- // ...
1214
- await Context.initialize();
1215
- // ...
1216
-
1217
-
1218
- `);
1219
- }
1220
- }
1221
- //#endregion
1222
-
1223
- //#region methods & getters / get class function by class type name
1224
- getClassFunBy(classType: Models__NS__ClassType) {
1225
- this.checkIfContextInitialized();
1226
- switch (classType) {
1227
- case Models__NS__ClassType.CONTROLLER:
1228
- return this.config.controllers;
1229
- case Models__NS__ClassType.ENTITY:
1230
- return this.config.entities;
1231
- case Models__NS__ClassType.PROVIDER:
1232
- return this.config.providers;
1233
- case Models__NS__ClassType.MIDDLEWARE:
1234
- return this.config.middlewares;
1235
- case Models__NS__ClassType.REPOSITORY:
1236
- return this.config.repositories;
1237
- case Models__NS__ClassType.SUBSCRIBER:
1238
- return this.config.subscribers;
1239
- case Models__NS__ClassType.MIGRATION:
1240
- return this.config.migrations;
1241
- }
1242
- }
1243
-
1244
- isCLassType(classType: Models__NS__ClassType, classFn: Function): boolean {
1245
- return !!this.getClassFunBy(classType)[ClassHelpers__NS__getName(classFn)];
1246
- }
1247
-
1248
- /**
1249
- * Only for injectable types
1250
- * Only for classType: CONTROLLER, REPOSITORY, PROVIDER, MIDDLEWARES
1251
- */
1252
- getClassFunByClassName(className: string): Function {
1253
- for (const classTypeName of this.allTypesfromContexts) {
1254
- const classesForInjectableType =
1255
- this.config[Models__NS__ClassTypeKey[classTypeName]];
1256
-
1257
- if (classesForInjectableType[className]) {
1258
- return classesForInjectableType[className];
1259
- }
1260
- }
1261
- }
1262
-
1263
- getClassFunByClass(classFunction: Function): Function {
1264
- const className = ClassHelpers__NS__getName(classFunction);
1265
- return this.getClassFunByClassName(className);
1266
- }
1267
-
1268
- getClassFunByArr(classType: Models__NS__ClassType) {
1269
- return Object.values(this.getClassFunBy(classType) || {}) as Function[];
1270
- }
1271
- //#endregion
1272
-
1273
- //#region methods & getters / create class instances
1274
- private async createInstances(classes: any, classType: Models__NS__ClassType) {
1275
- // const recrusiveValuesFromContext =
1276
- // await this.getRecrusiveClassesfromContexts(classType);
1277
- // console.log(this.config.contexts);
1278
- // console.log('recrusiveValuesFromContext', recrusiveValuesFromContext);
1279
-
1280
- for (const classFn of [
1281
- // ...recrusiveValuesFromContext,
1282
- ...Object.values(classes),
1283
- ]) {
1284
- const instance = DITaonContainer.resolve(classFn as any) as any;
1285
- const classInstancesByNameObj = this.classInstancesByNameObj[classType];
1286
- const className = ClassHelpers__NS__getName(classFn);
1287
- // console.log({ classFn, classType, instance, place, className, 'classInstancesByNameObj': this.classInstancesByNameObj });
1288
- classInstancesByNameObj[className] = instance;
1289
- // update config
1290
- this.config[Models__NS__ClassTypeKey[classType]][className] = classFn;
1291
- this.objWithClassesInstancesArr[classType].push(instance);
1292
- this.allClassesInstances[className] = instance;
1293
- }
1294
- }
1295
- //#endregion
1296
-
1297
- //#region methods & getters / init classes
1298
- async initClasses(): Promise<void> {
1299
- if (this.isRemoteHost) {
1300
- return;
1301
- }
1302
-
1303
- //#region @websql
1304
- for (const classFun of this.getClassFunByArr(
1305
- Models__NS__ClassType.ENTITY,
1306
- ) as any[]) {
1307
- const repo = (await this.connection.getRepository(
1308
- ClassHelpers__NS__getOrginalClass(classFun),
1309
- )) as any;
1310
- this.repos.set(ClassHelpers__NS__getName(classFun), repo);
1311
- }
1312
- //#endregion
1313
-
1314
- for (const classTypeName of [
1315
- Models__NS__ClassType.MIDDLEWARE,
1316
- Models__NS__ClassType.PROVIDER,
1317
- Models__NS__ClassType.REPOSITORY,
1318
- Models__NS__ClassType.CONTROLLER,
1319
- Models__NS__ClassType.ENTITY,
1320
- Models__NS__ClassType.MIGRATION,
1321
- ]) {
1322
- //#region init class static _ property
1323
- for (const classFun of this.getClassFunByArr(classTypeName) as any[]) {
1324
- if (___NS__isFunction(classFun._)) {
1325
- await classFun._();
1326
- }
1327
- }
1328
- //#endregion
1329
- }
1330
-
1331
- for (const classTypeName of [
1332
- Models__NS__ClassType.MIDDLEWARE,
1333
- Models__NS__ClassType.PROVIDER,
1334
- Models__NS__ClassType.REPOSITORY,
1335
- Models__NS__ClassType.CONTROLLER,
1336
- Models__NS__ClassType.MIGRATION,
1337
- ]) {
1338
- //#region init providers, repositories _ property
1339
- // Helpers__NS__taskStarted(
1340
- // `[taon] REINITING _ INS FN ${classTypeName} ${this.contextName} STARTED`,
1341
- // );
1342
- for (const ctrl of this.getClassesInstancesArrBy(classTypeName)) {
1343
- if (___NS__isFunction(ctrl._)) {
1344
- await ctrl._();
1345
- }
1346
- }
1347
- // Helpers__NS__taskStarted(
1348
- // `[taon] REINITING _ INS FN ${classTypeName} ${this.contextName} DONE`,
1349
- // );
1350
- //#endregion
1351
- }
1352
- }
1353
- //#endregion
1354
-
1355
- //#region methods & getters / is active on
1356
- isActiveOn(classInstance: object): boolean {
1357
- let contextRef: EndpointContext =
1358
- classInstance[Symbols__NS__ctxInClassOrClassObj];
1359
- return this === contextRef;
1360
- }
1361
- //#endregion
1362
-
1363
- //#region methods & getters / uri
1364
- get frontendHostUri() {
1365
- const url = this.config?.frontendHost?.startsWith('http')
1366
- ? this.config.frontendHost
1367
- : `${globalThis?.location?.protocol || 'http:'}//${
1368
- this.config?.frontendHost
1369
- }`;
1370
- const uri = new URL(url.replace(/\/$/, ''));
1371
- return uri;
1372
- }
1373
-
1374
- get uri(): URL | undefined {
1375
- const url = this.host ? new URL(this.host) : void 0;
1376
- return url;
1377
- }
1378
- //#endregion
1379
-
1380
- //#region methods & getters / host uri protocol
1381
- get uriProtocol(): string | undefined {
1382
- return this.uri?.protocol;
1383
- }
1384
- //#endregion
1385
-
1386
- //#region methods & getters / host uri origin
1387
- /**
1388
- * Examples
1389
- * http://localhost:3000
1390
- * https://localhost (from localhost:80) *
1391
- */
1392
- get uriOrigin(): string | undefined {
1393
- return this.uri?.origin;
1394
- }
1395
- //#endregion
1396
-
1397
- //#region methods & getters / host uri pathname
1398
- /**
1399
- * Exampels
1400
- * http://localhost:3000/path/to/somewhere
1401
- * https://localhost/path/to/somewhere (from localhost:80)
1402
- */
1403
- // get uriOriginWithPathname(): string | undefined {
1404
- // return this.uri?.origin
1405
- // ? this.uri?.origin + this.uriPathnameOrNothingIfRoot.replace(/\/$/, '')
1406
- // : undefined;
1407
- // }
1408
-
1409
- get uriPathname(): string | undefined {
1410
- return this.uri?.pathname;
1411
- }
1412
- //#endregion
1413
-
1414
- //#region methods & getters / uri pathname or nothing if root
1415
- /**
1416
- * Examples
1417
- * http://localhost:3000/path/to/somewhere -> '/path/to/somewhere'
1418
- * http://localhost:3000 -> '' #
1419
- * https://localhost/path/to/ -> '/path/to/somewhere' # remove last slash
1420
- */
1421
- get uriPathnameOrNothingIfRoot(): string {
1422
- const isNonRootProperPathName =
1423
- this.uri?.pathname && this.uri.pathname !== '/';
1424
- return isNonRootProperPathName ? this.uri.pathname.replace(/\/$/, '') : '';
1425
- }
1426
- //#endregion
1427
-
1428
- //#region methods & getters / port from uri
1429
- get uriPort(): string | undefined {
1430
- if (!this.uri?.origin?.includes('localhost')) {
1431
- return this.config?.hostPortNumber?.toString();
1432
- }
1433
- return this.uri?.port;
1434
- }
1435
- // TODO do i need 2 getters for port?
1436
-
1437
- /**
1438
- * Port from uri as number
1439
- * @returns {Number | undefined}
1440
- */
1441
- get port(): Number | undefined {
1442
- return this.uri?.port ? Number(this.uriPort) : undefined;
1443
- }
1444
- //#endregion
1445
-
1446
- //#region methods & getters / is https server
1447
- get isHttpServer() {
1448
- return this.uriProtocol === 'https:';
1449
- }
1450
- //#endregion
1451
-
1452
- //#region methods & getters / is remote host
1453
- /**
1454
- * Check if context is for remote only
1455
- */
1456
- public get isRemoteHost(): boolean {
1457
- return !!this.cloneOptions?.useAsRemoteContext;
1458
- }
1459
- //#endregion
1460
-
1461
- //#region methods & getters / context name
1462
- /**
1463
- * ipc/udp needs this
1464
- */
1465
- public get contextName(): string {
1466
- // console.log(this.originalConfig);
1467
- return this.config?.contextName || this.originalConfig?.contextName;
1468
- }
1469
- //#endregion
1470
-
1471
- //#region methods & getters / context name for communication
1472
- /**
1473
- * ipc/udp needs this
1474
- */
1475
- public get contextNameForCommunication(): string {
1476
- let contextName = this.contextName;
1477
- if (this.isRemoteHost) {
1478
- if (this.sourceContext?.contextName) {
1479
- contextName = this.sourceContext?.contextName;
1480
- } else {
1481
- // console.log(
1482
- // `CANT GET SOURCE CONTEXT NAME FOR REMOTE CONTEXT ${this.contextName}`,
1483
- // );
1484
- }
1485
- }
1486
- return contextName;
1487
- }
1488
- //#endregion
1489
-
1490
- //#region methods & getters / get context type
1491
- /**
1492
- * Check context type
1493
- */
1494
- public get contextType(): 'normal' | 'remote' | 'abstract' | 'invalid' {
1495
- if (this.config.abstract) {
1496
- return 'abstract';
1497
- }
1498
- if (this.host) {
1499
- return this.isRemoteHost ? 'remote' : 'normal';
1500
- }
1501
- return 'invalid';
1502
- }
1503
- //#endregion
1504
-
1505
- //#region methods & getters / current working directory
1506
- public get cwd(): string {
1507
- return this.config.cwd || process.cwd();
1508
- }
1509
- //#endregion
1510
-
1511
- //#region methods & getters / active context
1512
- public get activeContext(): string | null {
1513
- return this.config.activeContext || null;
1514
- }
1515
- //#endregion
1516
-
1517
- //#region methods & getters / app id
1518
- public get appId(): string {
1519
- return this.config.appId;
1520
- }
1521
- //#endregion
1522
-
1523
- //#region methods & getters / public assets
1524
- public get publicAssets() {
1525
- return this.config?.publicAssets || [];
1526
- }
1527
- //#endregion
1528
-
1529
- //#region methods & getters / is production mode
1530
- get isProductionMode() {
1531
- return this.config.productionMode;
1532
- }
1533
- //#endregion
1534
-
1535
- //#region methods & getters / host
1536
- get host(): string | undefined {
1537
- return this.config.host;
1538
- }
1539
- //#endregion
1540
-
1541
- //#region methods & getters / origin
1542
- get origin(): string | undefined {
1543
- return this.uri?.origin;
1544
- }
1545
- //#endregion
1546
-
1547
- //#region methods & getters / init subscribers
1548
- async initSubscribers() {
1549
- //#region @websqlFunc
1550
- if (this.isRemoteHost) {
1551
- return;
1552
- }
1553
- const subscriberClasses = this.getClassFunByArr(
1554
- Models__NS__ClassType.SUBSCRIBER,
1555
- );
1556
- for (const subscriberClassFn of subscriberClasses) {
1557
- const options = Reflect.getMetadata(
1558
- Symbols__NS__metadata.options.subscriber,
1559
- subscriberClassFn,
1560
- ) as TaonSubscriberOptions;
1561
- // console.log('subscriber options', options);
1562
- // const nameForSubscriber = ClassHelpers__NS__getName(subscriber);
1563
- EventSubscriber()(subscriberClassFn);
1564
- }
1565
- //#endregion
1566
- }
1567
- //#endregion
1568
-
1569
- //#region methods & getters / init entities
1570
- async initEntities() {
1571
- //#region @websql
1572
- if (this.isRemoteHost) {
1573
- return;
1574
- }
1575
- const entities = this.getClassFunByArr(Models__NS__ClassType.ENTITY);
1576
-
1577
- for (const entity of entities) {
1578
- const options = Reflect.getMetadata(
1579
- Symbols__NS__metadata.options.entity,
1580
- entity,
1581
- ) as TaonEntityOptions;
1582
- const createTable = ___NS__isUndefined(options.createTable)
1583
- ? true
1584
- : options.createTable;
1585
-
1586
- const nameForEntity = ClassHelpers__NS__getName(entity);
1587
-
1588
- if (createTable) {
1589
- this.logDb &&
1590
- console.info(
1591
- `[taon][typeorm] create table for entity "${nameForEntity}" ? '${createTable}'`,
1592
- );
1593
- // console.log('TypeormEntity', { TypeormEntity });
1594
- TypeormEntity(nameForEntity)(entity);
1595
- } else {
1596
- this.logDb &&
1597
- console.info(
1598
- `[taon][typeorm] create table for entity "${nameForEntity}" ? '${createTable}'`,
1599
- );
1600
- }
1601
- }
1602
- //#endregion
1603
- }
1604
-
1605
- //#endregion
1606
-
1607
- //#region methods & getters / destroy
1608
- async destroy(): Promise<void> {
1609
- //#region @websqlFunc
1610
- if (this.connection) {
1611
- await this.connection?.destroy();
1612
- delete this.connection;
1613
- }
1614
-
1615
- if (this.serverTcpUdp) {
1616
- await new Promise(resolve => {
1617
- this.serverTcpUdp?.close(() => {
1618
- resolve(true);
1619
- });
1620
- });
1621
- delete this.serverTcpUdp;
1622
- }
1623
- delete this.expressApp;
1624
- //#endregion
1625
- }
1626
- //#endregion
1627
-
1628
- //#region methods & getters / init connection
1629
- async initDatabaseConnection(): Promise<void> {
1630
- //#region @websqlFunc
1631
- if (this.isRemoteHost || !this.databaseConfig) {
1632
- return;
1633
- }
1634
- const entities = this.getClassFunByArr(Models__NS__ClassType.ENTITY).map(
1635
- entityFn => {
1636
- return ClassHelpers__NS__getOrginalClass(entityFn);
1637
- },
1638
- );
1639
-
1640
- const subscribers = this.getClassFunByArr(Models__NS__ClassType.SUBSCRIBER);
1641
-
1642
- let autoSave = false;
1643
- if (!___NS__isNil(this.databaseConfig.autoSave)) {
1644
- autoSave = this.databaseConfig.autoSave;
1645
- } else {
1646
- if (this.USE_MARIADB_MYSQL_IN_DOCKER) {
1647
- autoSave = !this.isRunningInsideDocker; // in docker I am using mysql or posgress
1648
- } else {
1649
- autoSave = true; // on docker with sqljs I need to save db
1650
- }
1651
- }
1652
-
1653
- const dataSourceDbConfig = ___NS__isObject(this.databaseConfig)
1654
- ? ({
1655
- type: this.databaseConfig.type,
1656
- port: this.databaseConfig.databasePort,
1657
- host: this.databaseConfig.databaseHost,
1658
- database: this.databaseConfig.database as any,
1659
- username: this.databaseConfig.databaseUsername,
1660
- password: this.databaseConfig.databasePassword,
1661
- useLocalForage: this.databaseConfig.useLocalForage,
1662
- // I am not using typeorm migration system
1663
- entities,
1664
- subscribers,
1665
- synchronize: this.isRunOrRevertOnlyMigrationAppStart
1666
- ? false
1667
- : this.databaseConfig.synchronize,
1668
- autoSave,
1669
- dropSchema: this.isRunOrRevertOnlyMigrationAppStart
1670
- ? false
1671
- : this.databaseConfig.dropSchema,
1672
- logging: !!this.databaseConfig.logging,
1673
- location: this.databaseConfig.location,
1674
- } as DataSourceOptions)
1675
- : ({} as DataSourceOptions);
1676
-
1677
- // debugger;
1678
- this.logFramework &&
1679
- console.log(
1680
- `[Context: "${this.contextName}"] dataSourceDbConfig`,
1681
- dataSourceDbConfig,
1682
- );
1683
-
1684
- if (this.modeAllowsDatabaseCreation && this.databaseConfig) {
1685
- this.logDb &&
1686
- this.logFramework &&
1687
- Helpers__NS__info('[taon][database] prepare typeorm connection...');
1688
- try {
1689
- const connection = new DataSource(dataSourceDbConfig);
1690
- this.connection = connection;
1691
- await this.connection.initialize();
1692
- } catch (error) {
1693
- console.error(
1694
- `[taon][typeorm] Error while initializing connection for ${this.contextName}, ERROR STARTED `,
1695
- );
1696
- console.error(error?.stack || '< No stack trace > ');
1697
- console.error(error?.message || error);
1698
- console.error(
1699
- `[taon][typeorm] Error while initializing connection for ${this.contextName}, ERROR ENDS `,
1700
- );
1701
- }
1702
-
1703
- if (!this.connection?.isInitialized) {
1704
- console.log('WRONG CONFIG', dataSourceDbConfig);
1705
- throw new Error(`Something wrong with connection init in ${this.mode}`);
1706
- //#region @backend
1707
- process.exit(1);
1708
- //#endregion
1709
- }
1710
-
1711
- if (this.logDb || this.logFramework) {
1712
- console.info(
1713
- `
1714
-
1715
- CONTECTION OK for ${this.contextName} - ${this.mode}
1716
-
1717
- [taon][typeorm] db prepration done.. db initialize=${this.connection?.isInitialized}
1718
-
1719
-
1720
- `,
1721
- // dataSourceDbConfig,
1722
- { 'this.connection': !!this.connection },
1723
- );
1724
- console.log(
1725
- `Database file location: ${this.connection.options.database}`,
1726
- );
1727
- }
1728
- // const entityMetadata = getMetadataArgsStorage();
1729
- // console.log(
1730
- // `
1731
-
1732
- // entityMetadata after connection init for ${this.contextName} - ${this.mode}
1733
-
1734
- // `,
1735
- // entityMetadata,
1736
- // );
1737
- // debugger;
1738
- } else {
1739
- Helpers__NS__info(`[taon][typeorm] Not initing db for mode ${this.mode}`);
1740
- }
1741
- //#endregion
1742
- }
1743
-
1744
- //#endregion
1745
-
1746
- //#region methods & getters / initialize metadata
1747
-
1748
- //#region methods & getters / update class calculate path
1749
- private updateCalculatedPathsForControllers(
1750
- rawConfigs: ControllerConfig[],
1751
- classConfig: ControllerConfig,
1752
- controllerClassFn: Function,
1753
- ): void {
1754
- const parentsCalculatedPath = ___NS__slice(rawConfigs, 1)
1755
- .reverse()
1756
- .map(bc => {
1757
- if (TaonHelpers__NS__isGoodPath(bc.path)) {
1758
- return bc.path;
1759
- }
1760
- return bc.className;
1761
- })
1762
- .join('/');
1763
-
1764
- const contextNameForCommunication = this.contextNameForCommunication;
1765
-
1766
- if (TaonHelpers__NS__isGoodPath(classConfig.path)) {
1767
- classConfig.calculatedPath = classConfig.path;
1768
- } else {
1769
- classConfig.calculatedPath = (
1770
- `${this.uriPathnameOrNothingIfRoot}` +
1771
- `/${apiPrefix}/${contextNameForCommunication}/tcp${parentsCalculatedPath}/` +
1772
- `${ClassHelpers__NS__getName(controllerClassFn)}`
1773
- )
1774
- .replace(/\/\//g, '/')
1775
- .split('/')
1776
- .reduce((acc, bc) => {
1777
- return ___NS__last(acc) === bc ? acc : [...acc, bc];
1778
- }, [])
1779
- .join('/');
1780
- }
1781
-
1782
- // console.log('calculatedPath', classConfig.calculatedPath);
1783
- }
1784
- //#endregion
1785
-
1786
- //#region methods & getters / dedupe class configs
1787
- private mergeControllerMethodsConfigs(
1788
- rawConfigs: ControllerConfig[],
1789
- classConfig: ControllerConfig,
1790
- controllerClassFn: Function,
1791
- ): void {
1792
- const currentControllerMethodsConfig = classConfig.methods;
1793
-
1794
- ___NS__slice(rawConfigs, 1).forEach(bc => {
1795
- const parentControllerMethods = ___NS__cloneDeep(bc.methods);
1796
-
1797
- for (const methodsName in parentControllerMethods) {
1798
- if (parentControllerMethods.hasOwnProperty(methodsName)) {
1799
- if (!currentControllerMethodsConfig[methodsName]) {
1800
- //#region add non existed method
1801
- const methodConfig = parentControllerMethods[methodsName];
1802
- currentControllerMethodsConfig[methodsName] = methodConfig;
1803
- //#endregion
1804
- }
1805
- }
1806
- }
1807
- });
1808
- }
1809
-
1810
- //#endregion
1811
- async initControllersHook(
1812
- ctxStorage: ContextsEndpointStorage,
1813
- ): Promise<void> {
1814
- if (this.isRunOrRevertOnlyMigrationAppStart) {
1815
- return;
1816
- }
1817
- const allControllers = this.getClassFunByArr(Models__NS__ClassType.CONTROLLER);
1818
- for (const controllerClassFn of allControllers) {
1819
- const instance = this.getInstanceBy(
1820
- controllerClassFn as any,
1821
- ) as TaonBaseController;
1822
- if (___NS__isFunction(instance.afterAllCtxInited)) {
1823
- await instance.afterAllCtxInited({ ctxStorage });
1824
- }
1825
- }
1826
- }
1827
-
1828
- async initControllers(): Promise<void> {
1829
- if (this.isRunOrRevertOnlyMigrationAppStart) {
1830
- return;
1831
- }
1832
- const allControllers = this.getClassFunByArr(Models__NS__ClassType.CONTROLLER);
1833
- // debugger
1834
- // console.log('allControllers', allControllers);
1835
- for (const controllerClassFn of allControllers) {
1836
- // console.log(ClassHelpers__NS__getClassConfig(controllerClassFn));
1837
-
1838
- // const controllerName = ClassHelpers__NS__getName(controllerClassFn);
1839
-
1840
- // console.log(
1841
- // `for ${controllerName}`,
1842
- // ClassHelpers__NS__getClassConfig(controllerClassFn),
1843
- // );
1844
-
1845
- controllerClassFn[Symbols__NS__classMethodsNames] =
1846
- ClassHelpers__NS__getMethodsNames(controllerClassFn);
1847
-
1848
- const rawConfigs = ClassHelpers__NS__getControllerConfigs(controllerClassFn);
1849
- // console.log(controllerName, { rawConfigs });
1850
- // console.log(`Class config for ${ClassHelpers__NS__getName(controllerClassFn)}`, configs)
1851
- const classConfig: ControllerConfig = rawConfigs[0];
1852
-
1853
- this.updateCalculatedPathsForControllers(
1854
- rawConfigs,
1855
- classConfig,
1856
- controllerClassFn,
1857
- );
1858
- this.mergeControllerMethodsConfigs(
1859
- rawConfigs,
1860
- classConfig,
1861
- controllerClassFn,
1862
- );
1863
-
1864
- //#region combine middlewares from controllers
1865
- classConfig.calculatedMiddlewaresControllerObj = {};
1866
- [...rawConfigs].reverse().forEach(rc => {
1867
- if (___NS__isFunction(rc.middlewares)) {
1868
- classConfig.calculatedMiddlewaresControllerObj = rc.middlewares({
1869
- parentMiddlewares: classConfig.calculatedMiddlewaresControllerObj,
1870
- className(middlewareClass) {
1871
- return ClassHelpers__NS__getName(controllerClassFn);
1872
- },
1873
- });
1874
- }
1875
- });
1876
- //#endregion
1877
-
1878
- //#region group start
1879
- //#region @backend
1880
- if (!UtilsOs__NS__isRunningInCliMode()) {
1881
- //#endregion
1882
- this.logHttp &&
1883
- console.groupCollapsed(
1884
- `[taon][express-server] routes [${classConfig.className}]`,
1885
- );
1886
- //#region @backend
1887
- }
1888
- //#endregion
1889
- //#endregion
1890
-
1891
- //#region init client or server methods
1892
- const methodNames = Object.keys(classConfig.methods);
1893
- for (const methodName of methodNames) {
1894
- const methodConfig: Partial<MethodConfig> =
1895
- classConfig.methods[methodName];
1896
-
1897
- //#region combine all class methods middlewares
1898
- let calculatedMiddlewaresMethodObj = {};
1899
-
1900
- [...rawConfigs].reverse().forEach(rc => {
1901
- if (rc.methods[methodName]) {
1902
- const parentMethodConfig = rc.methods[methodName];
1903
-
1904
- if (___NS__isFunction(parentMethodConfig.middlewares)) {
1905
- calculatedMiddlewaresMethodObj = parentMethodConfig.middlewares({
1906
- parentMiddlewares: calculatedMiddlewaresMethodObj,
1907
- className(middlewareClass) {
1908
- return ClassHelpers__NS__getName(controllerClassFn);
1909
- },
1910
- });
1911
- }
1912
- }
1913
- });
1914
-
1915
- // add class middlewares to method middlewares
1916
- methodConfig.calculatedMiddlewaresMethodObj = {
1917
- ...calculatedMiddlewaresMethodObj,
1918
- ...classConfig.calculatedMiddlewaresControllerObj,
1919
- };
1920
- methodConfig.calculatedMiddlewares = Object.values(
1921
- methodConfig.calculatedMiddlewaresMethodObj || {},
1922
- );
1923
- //#endregion
1924
-
1925
- // methodConfig.calculatedMiddlewares = TODO
1926
-
1927
- //#region initialized method express path
1928
- const httpMethodType: CoreModels__NS__HttpMethod = methodConfig.type;
1929
-
1930
- // this is quick fix - in docker global path should not be used
1931
- const globalPathPart =
1932
- this.isRunningInsideDocker ||
1933
- !this.frontendHostUri?.origin?.includes('localhost') // fe with domain -> is in docker
1934
- ? `${this.uriPathnameOrNothingIfRoot.replace(
1935
- /\/$/,
1936
- '',
1937
- )}/${apiPrefix}/${this.contextName}`.replace(/\/\//, '/')
1938
- : '';
1939
- const expressPath = methodConfig.global
1940
- ? `${globalPathPart}/${methodConfig.path?.replace(
1941
- /\/$/,
1942
- '',
1943
- )}`.replace(/\/\//, '/')
1944
- : TaonHelpers__NS__getExpressPath(classConfig, methodConfig);
1945
-
1946
- //#endregion
1947
-
1948
- //#region init server
1949
- // console.log({ expressPath });
1950
- if (UtilsOs__NS__isNode || UtilsOs__NS__isWebSQL) {
1951
- //#region @websql
1952
-
1953
- const route = this.initServer(
1954
- httpMethodType,
1955
- methodConfig,
1956
- classConfig,
1957
- expressPath,
1958
- controllerClassFn,
1959
- );
1960
-
1961
- this.activeRoutes.push({
1962
- expressPath: route.expressPath,
1963
- method: route.method,
1964
- });
1965
- //#endregion
1966
- }
1967
- //#endregion
1968
-
1969
- //#region init client
1970
- const shouldInitClient =
1971
- UtilsOs__NS__isBrowser || this.isRemoteHost || UtilsOs__NS__isWebSQL;
1972
- // console.log('shouldInitClient', shouldInitClient);
1973
- if (shouldInitClient) {
1974
- // console.log(
1975
- // 'initClient',
1976
- // ClassHelpers__NS__getFullInternalName(controllerClassFn),
1977
- // type,
1978
- // methodConfig,
1979
- // expressPath,
1980
- // );
1981
- await this.initClient(
1982
- controllerClassFn,
1983
- httpMethodType,
1984
- methodConfig as any,
1985
- expressPath,
1986
- );
1987
- }
1988
- //#endregion
1989
- }
1990
- //#endregion
1991
-
1992
- //#region group end
1993
- //#region @backend
1994
- if (!UtilsOs__NS__isRunningInCliMode()) {
1995
- //#endregion
1996
- this.logHttp && console.groupEnd();
1997
- //#region @backend
1998
- }
1999
- //#endregion
2000
- //#endregion
2001
- }
2002
- }
2003
- //#endregion
2004
-
2005
- //#region methods & getters / write active routes
2006
- public writeActiveRoutes(): void {
2007
- if (this.isRemoteHost || this.isRunOrRevertOnlyMigrationAppStart) {
2008
- return;
2009
- }
2010
- // const contexts: EndpointContext[] = [this];
2011
- //#region @websql
2012
-
2013
- const troutes = Utils__NS__uniqArray(
2014
- this.activeRoutes.map(f => {
2015
- return `${f.method} ${f.expressPath}`;
2016
- }),
2017
- ).map(f => {
2018
- const [method, expressPath] = f.split(' ');
2019
- return (
2020
- `\n### ${___NS__startCase(___NS__last(expressPath.split('/')))}\n` +
2021
- TaonHelpers__NS__fillUpTo(method.toUpperCase() + ' ', 10) +
2022
- this.uriOrigin +
2023
- expressPath
2024
- );
2025
-
2026
- // return `${TaonHelpers.string(method.toUpperCase() + ':')
2027
- // .fillUpTo(10)}${context.uriHref.replace(/\/$/, '')}${expressPath}`
2028
- });
2029
- const routes = [
2030
- ...['', `# ROUTES FOR HOST ${this.uriOrigin} `],
2031
- ...troutes,
2032
- ].join('\n');
2033
-
2034
- const fileName = crossPlatformPath([
2035
- //#region @backend
2036
- process.cwd(),
2037
- //#endregion
2038
- `routes/routes-${this.config.contextName}.rest`,
2039
- ]);
2040
-
2041
- this.logFramework && console.log(`[taon] routes file: ${fileName} `);
2042
- this.logRoutes && console.log(routes);
2043
- //#region @backend
2044
- if (!UtilsOs__NS__isElectron && !this.skipWritingServerRoutes) {
2045
- Helpers__NS__writeFile(fileName, routes);
2046
- }
2047
- //#endregion
2048
- //#endregion
2049
- }
2050
- //#endregion
2051
-
2052
- //#region methods & getters / middlewares
2053
- public get middlewares(): Models__NS__MiddlewareType[] {
2054
- //#region @backendFunc
2055
- return this.config.middlewares || [];
2056
- //#endregion
2057
- }
2058
- //#endregion
2059
-
2060
- //#region methods & getters / init middlewares
2061
-
2062
- private async initCustomClientMiddlewares(): Promise<void> {
2063
- const middlewares = this.getClassesInstancesArrBy(
2064
- Models__NS__ClassType.MIDDLEWARE,
2065
- )
2066
- .map(f => f as TaonBaseMiddleware)
2067
- .filter(f => ___NS__isFunction(f.interceptClient));
2068
-
2069
- middlewares.forEach(middlewareInstanceName => {
2070
- const contextName = this.contextName;
2071
- const interceptorName = `${contextName}-${ClassHelpers__NS__getName(
2072
- middlewareInstanceName,
2073
- )}`;
2074
- Resource.request.interceptors.set(interceptorName, {
2075
- intercept: ({ req, next }) => {
2076
- const url = new URL(req.url);
2077
- if (
2078
- url.pathname.startsWith(
2079
- `${this.uriPathnameOrNothingIfRoot}/${apiPrefix}/${contextName}/`,
2080
- )
2081
- ) {
2082
- // console.log('intercepting', url.pathname, req);
2083
- return middlewareInstanceName.interceptClient({
2084
- req,
2085
- next,
2086
- });
2087
- }
2088
- return next.handle(req);
2089
- },
2090
- });
2091
- });
2092
- }
2093
-
2094
- private async initCustomBackendMiddlewares(): Promise<void> {
2095
- //#region @backend
2096
- const app = this.expressApp;
2097
- const middlewares = this.getClassesInstancesArrBy(
2098
- Models__NS__ClassType.MIDDLEWARE,
2099
- );
2100
-
2101
- for (const middleware of middlewares) {
2102
- const middlewareInstance: TaonBaseMiddleware = middleware as any;
2103
- if (___NS__isFunction(middlewareInstance.interceptServer)) {
2104
- const middlewareFn = ClassHelpers__NS__asyncHandler(
2105
- async (
2106
- req: expressType.Request,
2107
- res: expressType.Response,
2108
- next: expressType.NextFunction,
2109
- ) => {
2110
- if (
2111
- req.originalUrl.startsWith(
2112
- `${this.uriPathnameOrNothingIfRoot}/${apiPrefix}/${this.contextName}/`,
2113
- )
2114
- ) {
2115
- await middlewareInstance.interceptServer({
2116
- req,
2117
- res,
2118
- next,
2119
- });
2120
- } else {
2121
- next();
2122
- }
2123
- },
2124
- );
2125
-
2126
- app.use(middlewareFn);
2127
- }
2128
- }
2129
- //#endregion
2130
- }
2131
-
2132
- private async initBackendMiddlewares(): Promise<void> {
2133
- //#region @backend
2134
- const app = this.expressApp;
2135
-
2136
- // if (this.middlewares) {
2137
- // this.middlewares.forEach(m => {
2138
- // const [fun, args] = m;
2139
- // app.use(fun.apply(null, args));
2140
- // });
2141
- // }
2142
-
2143
- this.expressApp.get('/helloworld', (req, res) => {
2144
- res.send(`Hello, world from context ${this.contextName}`);
2145
- });
2146
-
2147
- // app.use(fileUpload());
2148
- app.use(bodyParser.urlencoded({ extended: true }));
2149
- app.use(bodyParser.json());
2150
- app.use(methodOverride());
2151
- app.use(cookieParser());
2152
-
2153
- if (this.session) {
2154
- Helpers__NS__info(
2155
- '[taon][express-server] session enabled for this context ' +
2156
- this.contextName,
2157
- );
2158
- const { cookieMaxAge } = this.session;
2159
- const frontendHost = this.config.frontendHost;
2160
-
2161
- const sessionObj = {
2162
- frontendHost,
2163
- secret: 'mysecretsessioncookithing',
2164
- saveUninitialized: true,
2165
- cookieMaxAge,
2166
- secure: frontendHost.startsWith('https://'),
2167
- resave: false,
2168
- } as Models__NS__ISession;
2169
-
2170
- app.use(
2171
- cors({
2172
- credentials: true,
2173
- origin: frontendHost,
2174
- }),
2175
- );
2176
- app.use(expressSession(sessionObj));
2177
- console.log(`
2178
-
2179
- CORS ENABLED FOR SESSION
2180
-
2181
- `);
2182
- } else {
2183
- // if(this.config?.serverLogs) {
2184
- this.logHttp &&
2185
- Helpers__NS__info(
2186
- `[taon][express-server] session not enabled for this context '${this.contextName}'`,
2187
- );
2188
- // }
2189
- app.use(
2190
- cors({
2191
- // origin: "http://localhost:5555",
2192
- // methods: ["GET", "POST"],
2193
- // allowedHeaders: ["my-custom-header"],
2194
- // credentials: true
2195
- }),
2196
- );
2197
- this.logHttp &&
2198
- console.log(`
2199
-
2200
- CORS ENABLED WITHOUT SESSION
2201
-
2202
- `);
2203
- }
2204
-
2205
- (() => {
2206
- app.use((req, res, next) => {
2207
- //#region good for cors session obj
2208
- // if (this.context.session) {
2209
- // res.header('Access-Control-Allow-Origin', this.context.session.frontendHost);
2210
- // res.header('Access-Control-Allow-Credentials', 'true');
2211
- // res.header(
2212
- // 'Access-Control-Allow-Headers',
2213
- // 'Origin, X-Requested-With, Content-Type, Accept'
2214
- // );
2215
- // res.header("Access-Control-Allow-Methods", "PUT,POST,GET,HEAD,DELETE,OPTIONS,PATCH");
2216
- // // maybe this
2217
- // res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
2218
- // }
2219
- //#endregion
2220
-
2221
- res.set(
2222
- 'Access-Control-Expose-Headers',
2223
- [
2224
- 'Content-Type',
2225
- 'Authorization',
2226
- 'X-Requested-With',
2227
- Symbols__NS__old.X_TOTAL_COUNT,
2228
- Symbols__NS__old.MAPPING_CONFIG_HEADER,
2229
- Symbols__NS__old.CIRCURAL_OBJECTS_MAP_BODY,
2230
- Symbols__NS__old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM,
2231
- ].join(', '),
2232
- );
2233
- next();
2234
- });
2235
- })();
2236
-
2237
- //#endregion
2238
- }
2239
- //#endregion
2240
-
2241
- //#region methods & getters / init methods node
2242
- private initServer(
2243
- //#region parameters
2244
- httpMethodType: CoreModels__NS__HttpMethod,
2245
- methodConfig: Partial<MethodConfig>,
2246
- classConfig: ControllerConfig,
2247
- expressPath: string,
2248
- target: Function,
2249
- //#endregion
2250
- ): { expressPath: string; method: CoreModels__NS__HttpMethod } {
2251
- //#region resolve variables
2252
- // console.log(
2253
- // `CLIENT: expressPath: "${expressPath}" interceptor for method: ${methodConfig.calculatedMiddlewares.length}`,
2254
- // );
2255
-
2256
- const middlewareHandlers = methodConfig.calculatedMiddlewares
2257
- .map(middlewareClassFun => {
2258
- const middlewareInstance: TaonBaseMiddleware = this.getInstanceBy(
2259
- middlewareClassFun as any,
2260
- );
2261
- if (
2262
- middlewareInstance &&
2263
- ___NS__isFunction(middlewareInstance.interceptServerMethod)
2264
- ) {
2265
- const middlewareFn = ClassHelpers__NS__asyncHandler(
2266
- async (
2267
- req: expressType.Request,
2268
- res: expressType.Response,
2269
- next: expressType.NextFunction,
2270
- ) => {
2271
- await middlewareInstance.interceptServerMethod(
2272
- {
2273
- req,
2274
- res,
2275
- next,
2276
- },
2277
- {
2278
- methodName: methodConfig.methodName,
2279
- expressPath,
2280
- httpRequestType: methodConfig.type,
2281
- },
2282
- );
2283
- },
2284
- );
2285
- return middlewareFn;
2286
- }
2287
- })
2288
- .filter(f => !!f) as expressType.RequestHandler[];
2289
-
2290
- // const url = this.uri;
2291
-
2292
- //#region get result
2293
- const getResult = async (resolvedParams, req, res) => {
2294
- const response: Models__NS__Http__NS__Response<any> =
2295
- methodConfig.descriptor.value.apply(
2296
- /**
2297
- * Context for method @GET,@PUT etc.
2298
- */
2299
- this.getInstanceBy(target as any),
2300
- /**
2301
- * Params for method @GET, @PUT etc.
2302
- */
2303
- resolvedParams,
2304
- );
2305
- let result = await getResponseValue(response, { req, res });
2306
- return result;
2307
- };
2308
- //#endregion
2309
-
2310
- // console.log(`BACKEND: expressPath: "${expressPath}" `);
2311
- //#endregion
2312
-
2313
- if (UtilsOs__NS__isElectron) {
2314
- //#region @backend
2315
- const ipcKeyName = TaonHelpers__NS__ipcKeyNameRequest(
2316
- target,
2317
- methodConfig,
2318
- expressPath,
2319
- );
2320
- ipcMain.on(ipcKeyName, async (event, paramsFromBrowser) => {
2321
- const responseJsonData = await getResult(
2322
- paramsFromBrowser,
2323
- void 0,
2324
- void 0,
2325
- );
2326
- const sendToIpsMainOn = TaonHelpers__NS__ipcKeyNameResponse(
2327
- target,
2328
- methodConfig,
2329
- expressPath,
2330
- );
2331
- // console.log({ sendToIpsMainOn });
2332
- event.sender.send(sendToIpsMainOn, responseJsonData);
2333
- });
2334
- return {
2335
- expressPath,
2336
- method: methodConfig.type,
2337
- };
2338
- //#endregion
2339
- }
2340
-
2341
- if (!this.isRemoteHost) {
2342
- //#region apply dummy websql express routers
2343
- //#region @websql
2344
- if (UtilsOs__NS__isWebSQL) {
2345
- if (!this.expressApp[httpMethodType.toLowerCase()]) {
2346
- this.expressApp[httpMethodType.toLowerCase()] = () => {};
2347
- // TODO add middlewares for WEBSQL and ELECTRON mode
2348
- }
2349
- }
2350
- //#endregion
2351
- //#endregion
2352
-
2353
- //#region @backend
2354
- // this.logHttp &&
2355
- // console.log(`[${httpMethodType.toUpperCase()}] ${expressPath} `);
2356
- this.expressApp[httpMethodType.toLowerCase()](
2357
- expressPath,
2358
- ...middlewareHandlers,
2359
- async (req: expressType.Request, res: expressType.Response) => {
2360
- // console.log(`[${type.toUpperCase()}] ${expressPath} `);
2361
- //#region process params
2362
- const args: any[] = [];
2363
-
2364
- let tBody = req.body;
2365
- let tParams = req.params;
2366
- let tQuery: Object = req.query;
2367
-
2368
- if (req.headers[Symbols__NS__old.CIRCURAL_OBJECTS_MAP_BODY]) {
2369
- try {
2370
- tBody = JSON.parse(
2371
- JSON.stringify(tBody),
2372
- JSON.parse(
2373
- TaonHelpers__NS__firstStringOrElemFromArray(
2374
- req.headers[Symbols__NS__old.CIRCURAL_OBJECTS_MAP_BODY],
2375
- ),
2376
- ),
2377
- );
2378
- } catch (e) {}
2379
- }
2380
-
2381
- if (req.headers[Symbols__NS__old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM]) {
2382
- try {
2383
- tQuery = JSON.parse(
2384
- JSON.stringify(tQuery),
2385
- JSON.parse(
2386
- TaonHelpers__NS__firstStringOrElemFromArray(
2387
- req.headers[Symbols__NS__old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM],
2388
- ),
2389
- ),
2390
- );
2391
- } catch (e) {}
2392
- }
2393
-
2394
- // make class instance from body
2395
- // console.log('req.headers', req.headers)
2396
- if (req.headers[Symbols__NS__old.MAPPING_CONFIG_HEADER_BODY_PARAMS]) {
2397
- try {
2398
- const entity = JSON.parse(
2399
- TaonHelpers__NS__firstStringOrElemFromArray(
2400
- req.headers[Symbols__NS__old.MAPPING_CONFIG_HEADER_BODY_PARAMS],
2401
- ),
2402
- );
2403
- tBody = Mapping__NS__encode(tBody, entity);
2404
- } catch (e) {}
2405
- } else {
2406
- Object.keys(tBody).forEach(paramName => {
2407
- try {
2408
- const entityForParam = JSON.parse(
2409
- TaonHelpers__NS__firstStringOrElemFromArray(
2410
- req.headers[
2411
- `${Symbols__NS__old.MAPPING_CONFIG_HEADER_BODY_PARAMS}${paramName} `
2412
- ],
2413
- ),
2414
- );
2415
- tBody[paramName] = Mapping__NS__encode(
2416
- tBody[paramName],
2417
- entityForParam,
2418
- );
2419
- } catch (e) {}
2420
- });
2421
- }
2422
-
2423
- // make class instance from query params
2424
- // console.log('req.headers', tQuery)
2425
- if (req.headers[Symbols__NS__old.MAPPING_CONFIG_HEADER_QUERY_PARAMS]) {
2426
- try {
2427
- const entity = JSON.parse(
2428
- TaonHelpers__NS__firstStringOrElemFromArray(
2429
- req.headers[Symbols__NS__old.MAPPING_CONFIG_HEADER_QUERY_PARAMS],
2430
- ),
2431
- );
2432
- tQuery = TaonHelpers__NS__parseJSONwithStringJSONs(
2433
- Mapping__NS__encode(tQuery, entity),
2434
- );
2435
- } catch (e) {}
2436
- } else {
2437
- Object.keys(tQuery).forEach(queryParamName => {
2438
- try {
2439
- const entityForParam = JSON.parse(
2440
- TaonHelpers__NS__firstStringOrElemFromArray(
2441
- req.headers[
2442
- `${Symbols__NS__old.MAPPING_CONFIG_HEADER_QUERY_PARAMS}${queryParamName} `
2443
- ],
2444
- ),
2445
- );
2446
- let beforeTransofrm = tQuery[queryParamName];
2447
- if (___NS__isString(beforeTransofrm)) {
2448
- try {
2449
- const paresed =
2450
- TaonHelpers__NS__tryTransformParam(beforeTransofrm);
2451
- beforeTransofrm = paresed;
2452
- } catch (e) {}
2453
- }
2454
- const afterEncoding = Mapping__NS__encode(
2455
- beforeTransofrm,
2456
- entityForParam,
2457
- );
2458
- tQuery[queryParamName] =
2459
- TaonHelpers__NS__parseJSONwithStringJSONs(afterEncoding);
2460
- } catch (e) {}
2461
- });
2462
- }
2463
-
2464
- Object.keys(methodConfig.parameters).forEach(paramName => {
2465
- let p: Partial<ParamConfig> = methodConfig.parameters[paramName];
2466
- if (p.paramType === 'Path' && tParams) {
2467
- args.push(tParams[p.paramName]);
2468
- }
2469
- if (p.paramType === 'Query' && tQuery) {
2470
- if (p.paramName) {
2471
- args.push(tQuery[p.paramName]);
2472
- } else {
2473
- args.push(tQuery);
2474
- }
2475
- }
2476
-
2477
- if (p.paramType === 'Header' && req.headers) {
2478
- args.push(req.headers[p.paramName.toLowerCase()]);
2479
- }
2480
- if (p.paramType === 'Cookie' && req.cookies) {
2481
- args.push(req.cookies[p.paramName]);
2482
- }
2483
- if (p.paramType === 'Body' && tBody) {
2484
- if (p.paramName && typeof tBody === 'object') {
2485
- args.push(tBody[p.paramName]);
2486
- } else {
2487
- args.push(tBody);
2488
- }
2489
- }
2490
- });
2491
- //#endregion
2492
-
2493
- const resolvedParams = args
2494
- .reverse()
2495
- .map(v => TaonHelpers__NS__tryTransformParam(v));
2496
-
2497
- try {
2498
- let result = await getResult(resolvedParams, req, res);
2499
- if (methodConfig.responseType)
2500
- if (res.headersSent) {
2501
- // SKIP FURTHER PROCESSING IF RESPONSE ALREADY SENT
2502
- return;
2503
- }
2504
- if (methodConfig.overrideExpressSendAsHtml) {
2505
- res.setHeader('Content-Type', 'text/html');
2506
- res.send(result);
2507
- return;
2508
- }
2509
- if (
2510
- result instanceof Blob &&
2511
- (methodConfig.responseType as ModelsNg2Rest__NS__ResponseTypeAxios) ===
2512
- 'blob'
2513
- ) {
2514
- // console.log('INSTANCE OF BLOB')
2515
- //#region processs blob result type
2516
- const blob = result as Blob;
2517
- const file = Buffer.from(await blob.arrayBuffer());
2518
- res.writeHead(200, {
2519
- 'Content-Type': blob.type,
2520
- 'Content-Length': file.length,
2521
- });
2522
- res.end(file);
2523
- //#endregion
2524
- } else if (
2525
- ___NS__isString(result) &&
2526
- (methodConfig.responseType as ModelsNg2Rest__NS__ResponseTypeAxios) ===
2527
- 'blob'
2528
- ) {
2529
- // console.log('BASE64')
2530
- //#region process string buffer TODO refacetor
2531
- const img_base64 = result;
2532
- const m = /^data:(.+?);base64,(.+)$/.exec(img_base64);
2533
- if (!m) {
2534
- throw new Error(
2535
- `[taon - framework] Not a base64 image[${img_base64}]`,
2536
- );
2537
- }
2538
- const [_, content_type, file_base64] = m;
2539
- const file = Buffer.from(file_base64, 'base64');
2540
-
2541
- res.writeHead(200, {
2542
- 'Content-Type': content_type,
2543
- 'Content-Length': file.length,
2544
- });
2545
- res.end(file);
2546
- //#endregion
2547
- } else {
2548
- //#region process json request
2549
- await EntityProcess.init(result, res);
2550
- //#endregion
2551
- }
2552
- } catch (error) {
2553
- if (res.headersSent) {
2554
- // SKIP FURTHER PROCESSING IF RESPONSE ALREADY SENT
2555
- return;
2556
- }
2557
- if (methodConfig.overrideExpressSendAsHtml) {
2558
- res.setHeader('Content-Type', 'text/html');
2559
- res.send(error);
2560
- return;
2561
- }
2562
-
2563
- this.sendError(res, error, req, expressPath);
2564
- }
2565
- },
2566
- );
2567
- //#endregion
2568
- }
2569
-
2570
- return {
2571
- expressPath: expressPath,
2572
- method: methodConfig.type,
2573
- };
2574
- }
2575
- //#endregion
2576
-
2577
- //#region methods & getters / send error
2578
- protected sendError(
2579
- res: expressType.Response,
2580
- error: unknown,
2581
- req: expressType.Request,
2582
- expressPath: string,
2583
- ): void {
2584
- //#region @backendFunc
2585
- let status = 500;
2586
- let message = 'Internal Server Error';
2587
- let details: any = undefined;
2588
- let success = false;
2589
- let code = undefined;
2590
- if (typeof error === 'function') {
2591
- const obj: RestErrorResponseWrapper = error(res) || {};
2592
- status = obj.status || 400;
2593
- message = obj.message;
2594
- details = obj.details;
2595
- code = obj.code;
2596
- } else if (typeof error === 'string') {
2597
- message = error;
2598
- status = 400;
2599
- } else if (error instanceof Error) {
2600
- message = error.message;
2601
- details = process.env.NODE_ENV !== 'production' ? error.stack : undefined;
2602
- } else {
2603
- message = 'Unexpected error';
2604
- details = error;
2605
- }
2606
-
2607
- res.status(status).json({
2608
- success,
2609
- message,
2610
- details,
2611
- code,
2612
- [CoreModels__NS__TaonHttpErrorCustomProp]: true,
2613
- } as RestErrorResponseWrapper);
2614
- //#endregion
2615
- }
2616
- //#endregion
2617
-
2618
- //#region methods & getters / init client
2619
- /**
2620
- * client can be browser or nodejs (when remote host)
2621
- */
2622
- private async initClient(
2623
- target: Function,
2624
- httpRequestType: CoreModels__NS__HttpMethod,
2625
- methodConfig: Partial<MethodConfig>, // Models.Http.Rest.MethodConfig,
2626
- expressPath: string,
2627
- ): Promise<void> {
2628
- const ctx = this;
2629
-
2630
- // console.log(
2631
- // `CLIENT: expressPath: "${expressPath}" interceptor for method: ${methodConfig.calculatedMiddlewares?.length} `,
2632
- // );
2633
-
2634
- //#region init middlewares
2635
- const middlewares = methodConfig.calculatedMiddlewares;
2636
- const middlewaresInstances = middlewares
2637
- .map(f => this.getInstanceBy(f as any) as TaonBaseMiddleware)
2638
- .filter(f => ___NS__isFunction(f.interceptClientMethod));
2639
-
2640
- middlewaresInstances.forEach(instance => {
2641
- const middlewareName = ClassHelpers__NS__getName(instance);
2642
- // middlewareName - only needed for inheritace and uniqness of interceptors
2643
- const interceptorKey = `${middlewareName}-${methodConfig.type?.toUpperCase()}-${expressPath}`;
2644
- Resource.request.methodsInterceptors.set(interceptorKey, {
2645
- intercept: ({ req, next }) => {
2646
- return instance.interceptClientMethod(
2647
- {
2648
- req,
2649
- next,
2650
- },
2651
- {
2652
- methodName: methodConfig.methodName,
2653
- expressPath,
2654
- httpRequestType: httpRequestType,
2655
- },
2656
- );
2657
- },
2658
- });
2659
- });
2660
- //#endregion
2661
-
2662
- // : { received: any; /* Rest<any, any> */ }
2663
- // this.logHttp &&
2664
- // console.log(`${httpRequestType?.toUpperCase()} ${expressPath} `);
2665
- // console.log('INITING', methodConfig); // TODO inject in static
2666
- //#region resolve storage
2667
- // TODO not a good idea
2668
- const storage = globalThis;
2669
- //#endregion
2670
-
2671
- const orgMethods = target.prototype[methodConfig.methodName];
2672
-
2673
- //#region handle electron ipc request
2674
-
2675
- if (UtilsOs__NS__isElectron) {
2676
- const ipcRenderer = (window as any).require('electron').ipcRenderer;
2677
- target.prototype[methodConfig.methodName] = function (...args) {
2678
- const received = new Promise(async (resolve, reject) => {
2679
- const headers = {};
2680
- const { request, response } = TaonHelpers__NS__websqlMocks(headers);
2681
-
2682
- /* */
2683
- /* */
2684
- /* */
2685
- /* */
2686
- /* */
2687
- /* */
2688
- /* */
2689
- /* */
2690
- /* */
2691
- /* */
2692
- /* */
2693
- /* */
2694
- /* */
2695
- /* */
2696
- /* */
2697
- /* */
2698
- /* */
2699
- /* */
2700
- /* */
2701
- /* */
2702
- /* */
2703
- /* */
2704
- /* */
2705
- /* */
2706
- /* */
2707
- /* */
2708
- /* */
2709
- /* */
2710
- /* */
2711
- /* */
2712
- /* */
2713
- /* */
2714
- /* */
2715
- /* */
2716
- /* */
2717
- /* */
2718
-
2719
- });
2720
- received['observable'] = from(received);
2721
- return {
2722
- received,
2723
- request(axiosConfig: ModelsNg2Rest__NS__Ng2RestAxiosRequestConfig) {
2724
- return received;
2725
- },
2726
- } as Models__NS__Http__NS__ClientAction<any>;
2727
- };
2728
- return;
2729
- }
2730
- //#endregion
2731
-
2732
- //#region handling web sql request
2733
- /* */
2734
- /* */
2735
- /* */
2736
- /* */
2737
- /* */
2738
- /* */
2739
- /* */
2740
- /* */
2741
- /* */
2742
- /* */
2743
- /* */
2744
- /* */
2745
- /* */
2746
- /* */
2747
- /* */
2748
- /* */
2749
- /* */
2750
- /* */
2751
- /* */
2752
- /* */
2753
- /* */
2754
- /* */
2755
- /* */
2756
- /* */
2757
- /* */
2758
- /* */
2759
- /* */
2760
- /* */
2761
- /* */
2762
- /* */
2763
- /* */
2764
- /* */
2765
- /* */
2766
- /* */
2767
- /* */
2768
- /* */
2769
- /* */
2770
- /* */
2771
- /* */
2772
- /* */
2773
- /* */
2774
- /* */
2775
- /* */
2776
- /* */
2777
- /* */
2778
- /* */
2779
- /* */
2780
- /* */
2781
- /* */
2782
- /* */
2783
- /* */
2784
- /* */
2785
- /* */
2786
- /* */
2787
- /* */
2788
- /* */
2789
- /* */
2790
- /* */
2791
- /* */
2792
- /* */
2793
- /* */
2794
- /* */
2795
- /* */
2796
- /* */
2797
- /* */
2798
- /* */
2799
- /* */
2800
- /* */
2801
- /* */
2802
- /* */
2803
- /* */
2804
- /* */
2805
- /* */
2806
- /* */
2807
- /* */
2808
- /* */
2809
- /* */
2810
- /* */
2811
- /* */
2812
- /* */
2813
- /* */
2814
- /* */
2815
- /* */
2816
- /* */
2817
- /* */
2818
- /* */
2819
- /* */
2820
- /* */
2821
- /* */
2822
- /* */
2823
- /* */
2824
- /* */
2825
- /* */
2826
- /* */
2827
- /* */
2828
- /* */
2829
- /* */
2830
- /* */
2831
- /* */
2832
- /* */
2833
- /* */
2834
- /* */
2835
- /* */
2836
- /* */
2837
- /* */
2838
- /* */
2839
- /* */
2840
- /* */
2841
- /* */
2842
- /* */
2843
- /* */
2844
- /* */
2845
- /* */
2846
- /* */
2847
- /* */
2848
- /* */
2849
- /* */
2850
- /* */
2851
- /* */
2852
- /* */
2853
- /* */
2854
- /* */
2855
- /* */
2856
- /* */
2857
- /* */
2858
- /* */
2859
- /* */
2860
- /* */
2861
- /* */
2862
- /* */
2863
- /* */
2864
- /* */
2865
- /* */
2866
- /* */
2867
- /* */
2868
- /* */
2869
- /* */
2870
- /* */
2871
- /* */
2872
- /* */
2873
- /* */
2874
- /* */
2875
- /* */
2876
- /* */
2877
- /* */
2878
- /* */
2879
- /* */
2880
- /* */
2881
- /* */
2882
- /* */
2883
-
2884
- //#endregion
2885
-
2886
- //#region handle normal request
2887
-
2888
- target.prototype[methodConfig.methodName] = function (
2889
- this: {},
2890
- ...args
2891
- ): Models__NS__Http__NS__ClientAction<any> {
2892
- // console.log('[init method browser] FRONTEND expressPath', expressPath)
2893
- // const productionMode = FrameworkContext.isProductionMode;
2894
-
2895
- //#region resolve frontend parameters
2896
-
2897
- if (!storage[Symbols__NS__old.ENDPOINT_META_CONFIG])
2898
- storage[Symbols__NS__old.ENDPOINT_META_CONFIG] = {};
2899
- if (!storage[Symbols__NS__old.ENDPOINT_META_CONFIG][ctx.uriOrigin])
2900
- storage[Symbols__NS__old.ENDPOINT_META_CONFIG][ctx.uriOrigin] = {};
2901
- const endpoints = storage[Symbols__NS__old.ENDPOINT_META_CONFIG];
2902
- let rest: ModelsNg2Rest__NS__ResourceModel<any, any>;
2903
- if (!endpoints[ctx.uriOrigin][expressPath]) {
2904
- let headers = {};
2905
- if (methodConfig.contentType && !methodConfig.responseType) {
2906
- rest = Resource.create(
2907
- ctx.uriOrigin,
2908
- expressPath,
2909
- Symbols__NS__old.MAPPING_CONFIG_HEADER as any,
2910
- Symbols__NS__old.CIRCURAL_OBJECTS_MAP_BODY as any,
2911
- RestHeaders.from({
2912
- 'Content-Type': methodConfig.contentType,
2913
- Accept: methodConfig.contentType,
2914
- }),
2915
- );
2916
- } else if (methodConfig.contentType && methodConfig.responseType) {
2917
- rest = Resource.create(
2918
- ctx.uriOrigin,
2919
- expressPath,
2920
- Symbols__NS__old.MAPPING_CONFIG_HEADER as any,
2921
- Symbols__NS__old.CIRCURAL_OBJECTS_MAP_BODY as any,
2922
- RestHeaders.from({
2923
- 'Content-Type': methodConfig.contentType,
2924
- Accept: methodConfig.contentType,
2925
- responsetypeaxios: methodConfig.responseType,
2926
- }),
2927
- );
2928
- } else if (!methodConfig.contentType && methodConfig.responseType) {
2929
- rest = Resource.create(
2930
- ctx.uriOrigin,
2931
- expressPath,
2932
- Symbols__NS__old.MAPPING_CONFIG_HEADER as any,
2933
- Symbols__NS__old.CIRCURAL_OBJECTS_MAP_BODY as any,
2934
- RestHeaders.from({
2935
- responsetypeaxios: methodConfig.responseType,
2936
- }),
2937
- );
2938
- } else {
2939
- rest = Resource.create(
2940
- ctx.uriOrigin,
2941
- expressPath,
2942
- Symbols__NS__old.MAPPING_CONFIG_HEADER as any,
2943
- Symbols__NS__old.CIRCURAL_OBJECTS_MAP_BODY as any,
2944
- );
2945
- }
2946
-
2947
- endpoints[ctx.uriOrigin][expressPath] = rest;
2948
- } else {
2949
- rest = endpoints[ctx.uriOrigin][expressPath] as any;
2950
- }
2951
-
2952
- const method = httpRequestType.toLowerCase();
2953
-
2954
- const pathPrams = {};
2955
- let queryParams = {};
2956
- let bodyObject = {};
2957
- args.forEach((param, i) => {
2958
- let currentParam: Partial<ParamConfig> = void 0 as any;
2959
-
2960
- for (let pp in methodConfig.parameters) {
2961
- let v = methodConfig.parameters[pp];
2962
- if (v.index === i) {
2963
- currentParam = v;
2964
- break;
2965
- }
2966
- }
2967
-
2968
- if (!currentParam) {
2969
- const errorMessage =
2970
- `[${config.frameworkName}] Unable to resolve parameter` +
2971
- ` at index ${i} for method ${methodConfig.methodName} at path ${expressPath}.`;
2972
-
2973
- //#region @backend
2974
- console.error(errorMessage);
2975
- process.exit(0);
2976
- //#endregion
2977
- throw new Error(errorMessage);
2978
- }
2979
-
2980
- if (currentParam.paramType === 'Path') {
2981
- pathPrams[currentParam.paramName] = param;
2982
- }
2983
- if (currentParam.paramType === 'Query') {
2984
- if (currentParam.paramName) {
2985
- const mapping = Mapping__NS__decode(param, !ctx.isProductionMode);
2986
- if (mapping) {
2987
- rest.headers.set(
2988
- `${Symbols__NS__old.MAPPING_CONFIG_HEADER_QUERY_PARAMS}${currentParam.paramName} `,
2989
- JSON.stringify(mapping),
2990
- );
2991
- }
2992
- queryParams[currentParam.paramName] = param;
2993
- } else {
2994
- const mapping = Mapping__NS__decode(param, !ctx.isProductionMode);
2995
- if (mapping) {
2996
- rest.headers.set(
2997
- Symbols__NS__old.MAPPING_CONFIG_HEADER_QUERY_PARAMS,
2998
- JSON.stringify(mapping),
2999
- );
3000
- }
3001
- queryParams = ___NS__cloneDeep(param);
3002
- }
3003
- }
3004
- if (currentParam.paramType === 'Header') {
3005
- if (currentParam.paramName) {
3006
- if (currentParam.paramName === Symbols__NS__old.MDC_KEY) {
3007
- // parese MDC
3008
- rest.headers.set(
3009
- currentParam.paramName,
3010
- encodeURIComponent(JSON.stringify(param)),
3011
- );
3012
- } else {
3013
- rest.headers.set(currentParam.paramName, param);
3014
- }
3015
- } else {
3016
- for (let header in param) {
3017
- rest.headers.set(header, param[header]);
3018
- }
3019
- }
3020
- }
3021
- if (currentParam.paramType === 'Cookie') {
3022
- Resource.Cookies.write(
3023
- currentParam.paramName,
3024
- param,
3025
- currentParam.expireInSeconds,
3026
- );
3027
- }
3028
- if (currentParam.paramType === 'Body') {
3029
- if (currentParam.paramName) {
3030
- if (ClassHelpers__NS__getName(bodyObject) === 'FormData') {
3031
- throw new Error(`[taon - framework] Don use param names when posting / putting FormData.
3032
- Use this:
3033
- // ...
3034
- (@Taon.Http.Param.Body() formData: FormData) ...
3035
- // ...
3036
-
3037
- instead
3038
- // ...
3039
- (@Taon.Http.Param.Body('${currentParam.paramName}') formData: FormData) ...
3040
- // ...
3041
- `);
3042
- }
3043
- const mapping = Mapping__NS__decode(param, !ctx.isProductionMode);
3044
- if (mapping) {
3045
- rest.headers.set(
3046
- `${Symbols__NS__old.MAPPING_CONFIG_HEADER_BODY_PARAMS}${currentParam.paramName} `,
3047
- JSON.stringify(mapping),
3048
- );
3049
- }
3050
- bodyObject[currentParam.paramName] = param;
3051
- } else {
3052
- const mapping = Mapping__NS__decode(param, !ctx.isProductionMode);
3053
- if (mapping) {
3054
- rest.headers.set(
3055
- Symbols__NS__old.MAPPING_CONFIG_HEADER_BODY_PARAMS,
3056
- JSON.stringify(mapping),
3057
- );
3058
- }
3059
- bodyObject = param;
3060
- }
3061
- }
3062
- });
3063
-
3064
- if (
3065
- typeof bodyObject === 'object' &&
3066
- ClassHelpers__NS__getName(bodyObject) !== 'FormData'
3067
- ) {
3068
- let circuralFromItem = [];
3069
- bodyObject = JSON10.parse(
3070
- JSON10.stringify(bodyObject, void 0, void 0, circs => {
3071
- circuralFromItem = circs;
3072
- }),
3073
- );
3074
- rest.headers.set(
3075
- Symbols__NS__old.CIRCURAL_OBJECTS_MAP_BODY,
3076
- JSON10.stringify(circuralFromItem),
3077
- );
3078
- }
3079
-
3080
- if (typeof queryParams === 'object') {
3081
- let circuralFromQueryParams = [];
3082
- queryParams = JSON10.parse(
3083
- JSON10.stringify(queryParams, void 0, void 0, circs => {
3084
- circuralFromQueryParams = circs;
3085
- }),
3086
- );
3087
-
3088
- rest.headers.set(
3089
- Symbols__NS__old.CIRCURAL_OBJECTS_MAP_QUERY_PARAM,
3090
- JSON10.stringify(circuralFromQueryParams),
3091
- );
3092
- }
3093
- //#endregion
3094
-
3095
- const httpResultObj: Models__NS__Http__NS__ClientAction<any> = {
3096
- get received() {
3097
- return rest.model(pathPrams)[method](bodyObject, [queryParams]);
3098
- },
3099
- request(axiosConfig?: ModelsNg2Rest__NS__Ng2RestAxiosRequestConfig) {
3100
- return rest
3101
- .model(pathPrams)
3102
- [method](bodyObject, [queryParams], axiosConfig);
3103
- },
3104
- };
3105
- return httpResultObj as Models__NS__Http__NS__ClientAction<any>;
3106
- };
3107
- //#endregion
3108
- }
3109
- //#endregion
3110
- }