taon 21.0.51 → 21.0.53

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