@koalarx/nest 3.0.3 → 3.0.4

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 (293) hide show
  1. package/core/backgroud-services/cron-service/cron-job.handler.base.d.ts +16 -0
  2. package/core/backgroud-services/cron-service/cron-job.handler.base.js +49 -0
  3. package/core/backgroud-services/event-service/event-class.d.ts +5 -0
  4. package/core/backgroud-services/event-service/event-class.js +11 -0
  5. package/core/backgroud-services/event-service/event-handler.base.d.ts +8 -0
  6. package/core/backgroud-services/event-service/event-handler.base.js +14 -0
  7. package/core/backgroud-services/event-service/event-is-trigger.d.ts +3 -0
  8. package/core/backgroud-services/event-service/event-is-trigger.js +7 -0
  9. package/core/backgroud-services/event-service/event-job.d.ts +13 -0
  10. package/core/backgroud-services/event-service/event-job.js +21 -0
  11. package/core/backgroud-services/event-service/event-queue.d.ts +17 -0
  12. package/core/backgroud-services/event-service/event-queue.js +62 -0
  13. package/core/constants/query-params.d.ts +6 -0
  14. package/core/constants/query-params.js +8 -0
  15. package/core/controllers/base.controller.d.ts +4 -0
  16. package/core/controllers/base.controller.js +6 -0
  17. package/core/controllers/controller.decorator.d.ts +2 -0
  18. package/core/controllers/controller.decorator.js +11 -0
  19. package/core/controllers/created-registre-response.base.d.ts +10 -0
  20. package/core/controllers/created-registre-response.base.js +35 -0
  21. package/core/controllers/list-response.base.d.ts +4 -0
  22. package/core/controllers/list-response.base.js +21 -0
  23. package/core/controllers/pagination.request.d.ts +10 -0
  24. package/core/controllers/pagination.request.js +56 -0
  25. package/core/controllers/router-config.base.d.ts +7 -0
  26. package/core/controllers/router-config.base.js +18 -0
  27. package/core/controllers/schemas/boolean.schema.d.ts +2 -0
  28. package/core/controllers/schemas/boolean.schema.js +12 -0
  29. package/core/controllers/schemas/document-number.schema.d.ts +1 -0
  30. package/core/controllers/schemas/document-number.schema.js +26 -0
  31. package/core/controllers/schemas/email.schema.d.ts +1 -0
  32. package/core/controllers/schemas/email.schema.js +13 -0
  33. package/core/controllers/schemas/list-query.schema.d.ts +17 -0
  34. package/core/controllers/schemas/list-query.schema.js +19 -0
  35. package/core/controllers/schemas/native-enum.schema.d.ts +7 -0
  36. package/core/controllers/schemas/native-enum.schema.js +28 -0
  37. package/core/controllers/schemas/set-mask-document-number.schema.d.ts +1 -0
  38. package/core/controllers/schemas/set-mask-document-number.schema.js +13 -0
  39. package/core/database/entity.base.d.ts +20 -0
  40. package/core/database/entity.base.js +71 -0
  41. package/core/database/entity.decorator.d.ts +13 -0
  42. package/core/database/entity.decorator.js +23 -0
  43. package/core/database/prisma-client-with-custom-transaction.interface.d.ts +8 -0
  44. package/core/database/prisma-client-with-custom-transaction.interface.js +2 -0
  45. package/core/database/prisma-resolver.d.ts +2 -0
  46. package/core/database/prisma-resolver.js +74 -0
  47. package/core/database/prisma-transactional-client.d.ts +11 -0
  48. package/core/database/prisma-transactional-client.js +25 -0
  49. package/core/database/prisma.service.d.ts +24 -0
  50. package/core/database/prisma.service.js +104 -0
  51. package/core/database/repository.base.d.ts +44 -0
  52. package/core/database/repository.base.js +360 -0
  53. package/core/dtos/pagination.dto.d.ts +9 -0
  54. package/core/dtos/pagination.dto.js +49 -0
  55. package/core/errors/bad-request.error.d.ts +5 -0
  56. package/core/errors/bad-request.error.js +10 -0
  57. package/core/errors/conflict.error.d.ts +4 -0
  58. package/core/errors/conflict.error.js +10 -0
  59. package/core/errors/error.base.d.ts +4 -0
  60. package/core/errors/error.base.js +11 -0
  61. package/core/errors/no-content.error.d.ts +5 -0
  62. package/core/errors/no-content.error.js +10 -0
  63. package/core/errors/not-allowed.error.d.ts +5 -0
  64. package/core/errors/not-allowed.error.js +10 -0
  65. package/core/errors/resource-not-found.error.d.ts +5 -0
  66. package/core/errors/resource-not-found.error.js +10 -0
  67. package/{src/core/errors/use-case-error.ts → core/errors/use-case-error.d.ts} +1 -1
  68. package/core/errors/use-case-error.js +2 -0
  69. package/core/errors/user-already-exist.error.d.ts +4 -0
  70. package/core/errors/user-already-exist.error.js +10 -0
  71. package/core/errors/wrong-credentials.error.d.ts +4 -0
  72. package/core/errors/wrong-credentials.error.js +10 -0
  73. package/core/health-check/health-check.controller.d.ts +5 -0
  74. package/core/health-check/health-check.controller.js +32 -0
  75. package/core/health-check/health-check.module.d.ts +2 -0
  76. package/core/health-check/health-check.module.js +19 -0
  77. package/core/index.d.ts +18 -0
  78. package/core/index.js +7 -0
  79. package/core/koala-app.d.ts +64 -0
  80. package/core/koala-app.js +252 -0
  81. package/core/koala-global-vars.d.ts +7 -0
  82. package/core/koala-global-vars.js +9 -0
  83. package/core/koala-nest-database.module.d.ts +16 -0
  84. package/core/koala-nest-database.module.js +52 -0
  85. package/core/koala-nest-http.module.d.ts +13 -0
  86. package/core/koala-nest-http.module.js +37 -0
  87. package/core/koala-nest.module.d.ts +17 -0
  88. package/core/koala-nest.module.js +66 -0
  89. package/core/mapping/auto-mapping-class-context.d.ts +16 -0
  90. package/core/mapping/auto-mapping-class-context.js +18 -0
  91. package/core/mapping/auto-mapping-context.d.ts +11 -0
  92. package/core/mapping/auto-mapping-context.js +24 -0
  93. package/core/mapping/auto-mapping-list.d.ts +27 -0
  94. package/core/mapping/auto-mapping-list.js +94 -0
  95. package/core/mapping/auto-mapping-profile.d.ts +3 -0
  96. package/core/mapping/auto-mapping-profile.js +6 -0
  97. package/core/mapping/auto-mapping.decorator.d.ts +9 -0
  98. package/core/mapping/auto-mapping.decorator.js +27 -0
  99. package/core/mapping/auto-mapping.module.d.ts +5 -0
  100. package/core/mapping/auto-mapping.module.js +29 -0
  101. package/core/mapping/auto-mapping.service.d.ts +14 -0
  102. package/core/mapping/auto-mapping.service.js +140 -0
  103. package/core/mapping/create-map.d.ts +3 -0
  104. package/core/mapping/create-map.js +7 -0
  105. package/core/mapping/for-member.d.ts +5 -0
  106. package/core/mapping/for-member.js +8 -0
  107. package/core/request-overflow/request-handler.base.d.ts +4 -0
  108. package/core/request-overflow/request-handler.base.js +6 -0
  109. package/core/request-overflow/request-result.d.ts +15 -0
  110. package/core/request-overflow/request-result.js +37 -0
  111. package/core/request-overflow/request-validator.base.d.ts +7 -0
  112. package/core/request-overflow/request-validator.base.js +26 -0
  113. package/core/security/strategies/api-key.strategy.d.ts +16 -0
  114. package/core/security/strategies/api-key.strategy.js +31 -0
  115. package/core/utils/assing-object.d.ts +5 -0
  116. package/core/utils/assing-object.js +6 -0
  117. package/core/utils/env.config.d.ts +6 -0
  118. package/core/utils/env.config.js +18 -0
  119. package/core/utils/filter-request-params.d.ts +13 -0
  120. package/core/utils/filter-request-params.js +22 -0
  121. package/core/utils/find-on-list.d.ts +2 -0
  122. package/core/utils/find-on-list.js +13 -0
  123. package/core/utils/get-type-by-prop.d.ts +2 -0
  124. package/core/utils/get-type-by-prop.js +11 -0
  125. package/core/utils/instanciate-class-with-dependencies-injection.d.ts +2 -0
  126. package/core/utils/instanciate-class-with-dependencies-injection.js +10 -0
  127. package/core/utils/interfaces/icomparable.d.ts +5 -0
  128. package/core/utils/interfaces/icomparable.js +6 -0
  129. package/core/utils/list.d.ts +39 -0
  130. package/core/utils/list.js +168 -0
  131. package/core/utils/promise-all.d.ts +7 -0
  132. package/core/utils/promise-all.js +19 -0
  133. package/core/utils/set-mask-document-number.d.ts +1 -0
  134. package/core/utils/set-mask-document-number.js +13 -0
  135. package/core/validators/file-validator.d.ts +27 -0
  136. package/core/validators/file-validator.js +94 -0
  137. package/decorators/api-exclude-endpoint-diff-develop.decorator.d.ts +1 -0
  138. package/decorators/api-exclude-endpoint-diff-develop.decorator.js +9 -0
  139. package/decorators/api-property-enum.decorator.d.ts +8 -0
  140. package/decorators/api-property-enum.decorator.js +21 -0
  141. package/decorators/api-property-only-develop.decorator.d.ts +2 -0
  142. package/decorators/api-property-only-develop.decorator.js +9 -0
  143. package/decorators/cookies.decorator.d.ts +1 -0
  144. package/decorators/cookies.decorator.js +8 -0
  145. package/decorators/is-public.decorator.d.ts +2 -0
  146. package/decorators/is-public.decorator.js +7 -0
  147. package/decorators/upload.decorator.d.ts +1 -0
  148. package/decorators/upload.decorator.js +18 -0
  149. package/env/env.d.ts +25 -0
  150. package/env/env.js +14 -0
  151. package/env/env.module.d.ts +2 -0
  152. package/env/env.module.js +20 -0
  153. package/env/env.service.d.ts +7 -0
  154. package/env/env.service.js +28 -0
  155. package/filters/domain-errors.filter.d.ts +18 -0
  156. package/filters/domain-errors.filter.js +92 -0
  157. package/filters/global-exception.filter.d.ts +8 -0
  158. package/filters/global-exception.filter.js +68 -0
  159. package/filters/prisma-validation-exception.filter.d.ts +10 -0
  160. package/filters/prisma-validation-exception.filter.js +82 -0
  161. package/filters/zod-errors.filter.d.ts +9 -0
  162. package/filters/zod-errors.filter.js +60 -0
  163. package/package.json +4 -1
  164. package/services/logging/ilogging.service.d.ts +16 -0
  165. package/services/logging/ilogging.service.js +6 -0
  166. package/services/logging/logging.service.d.ts +4 -0
  167. package/services/logging/logging.service.js +20 -0
  168. package/services/redis/iredis.service.d.ts +6 -0
  169. package/services/redis/iredis.service.js +6 -0
  170. package/services/redis/redis.service.d.ts +14 -0
  171. package/services/redis/redis.service.js +65 -0
  172. package/services/redlock/ired-lock.service.d.ts +4 -0
  173. package/services/redlock/ired-lock.service.js +6 -0
  174. package/services/redlock/red-lock.service.d.ts +9 -0
  175. package/services/redlock/red-lock.service.js +46 -0
  176. package/test/koala-app-test-dependencies.d.ts +10 -0
  177. package/test/koala-app-test-dependencies.js +13 -0
  178. package/test/koala-app-test.d.ts +22 -0
  179. package/test/koala-app-test.js +77 -0
  180. package/test/repositories/in-memory-base.repository.d.ts +17 -0
  181. package/test/repositories/in-memory-base.repository.js +65 -0
  182. package/test/services/fake-logging.service.d.ts +4 -0
  183. package/test/services/fake-logging.service.js +9 -0
  184. package/test/services/fake-red-lock.service.d.ts +5 -0
  185. package/test/services/fake-red-lock.service.js +11 -0
  186. package/test/utils/create-e2e-database.d.ts +2 -0
  187. package/test/utils/create-e2e-database.js +47 -0
  188. package/test/utils/drop-e2e-database.d.ts +2 -0
  189. package/test/utils/drop-e2e-database.js +33 -0
  190. package/test/utils/wait-for.d.ts +1 -0
  191. package/test/utils/wait-for.js +21 -0
  192. package/tsconfig.lib.tsbuildinfo +1 -0
  193. package/CHANGELOG.md +0 -27
  194. package/src/core/backgroud-services/cron-service/cron-job.handler.base.ts +0 -66
  195. package/src/core/backgroud-services/cron-service/cron-job.handler.spec.ts +0 -38
  196. package/src/core/backgroud-services/event-service/event-class.ts +0 -5
  197. package/src/core/backgroud-services/event-service/event-handler.base.ts +0 -17
  198. package/src/core/backgroud-services/event-service/event-is-trigger.ts +0 -3
  199. package/src/core/backgroud-services/event-service/event-job.ts +0 -28
  200. package/src/core/backgroud-services/event-service/event-queue.spec.ts +0 -47
  201. package/src/core/backgroud-services/event-service/event-queue.ts +0 -107
  202. package/src/core/constants/query-params.ts +0 -7
  203. package/src/core/controllers/base.controller.ts +0 -9
  204. package/src/core/controllers/controller.decorator.ts +0 -10
  205. package/src/core/controllers/created-registre-response.base.ts +0 -17
  206. package/src/core/controllers/list-response.base.ts +0 -8
  207. package/src/core/controllers/pagination.request.ts +0 -41
  208. package/src/core/controllers/router-config.base.ts +0 -14
  209. package/src/core/controllers/schemas/boolean.schema.ts +0 -10
  210. package/src/core/controllers/schemas/document-number.schema.ts +0 -23
  211. package/src/core/controllers/schemas/email.schema.ts +0 -13
  212. package/src/core/controllers/schemas/list-query.schema.ts +0 -17
  213. package/src/core/controllers/schemas/native-enum.schema.ts +0 -34
  214. package/src/core/controllers/schemas/set-mask-document-number.schema.ts +0 -13
  215. package/src/core/database/entity.base.ts +0 -95
  216. package/src/core/database/entity.decorator.spec.ts +0 -71
  217. package/src/core/database/entity.decorator.ts +0 -39
  218. package/src/core/database/prisma-client-with-custom-transaction.interface.ts +0 -13
  219. package/src/core/database/prisma-resolver.ts +0 -99
  220. package/src/core/database/prisma-transactional-client.ts +0 -43
  221. package/src/core/database/prisma.service.ts +0 -136
  222. package/src/core/database/repository.base.ts +0 -548
  223. package/src/core/dtos/pagination.dto.ts +0 -35
  224. package/src/core/errors/bad-request.error.ts +0 -8
  225. package/src/core/errors/conflict.error.ts +0 -7
  226. package/src/core/errors/error.base.ts +0 -5
  227. package/src/core/errors/no-content.error.ts +0 -8
  228. package/src/core/errors/not-allowed.error.ts +0 -8
  229. package/src/core/errors/resource-not-found.error.ts +0 -8
  230. package/src/core/errors/user-already-exist.error.ts +0 -7
  231. package/src/core/errors/wrong-credentials.error.ts +0 -7
  232. package/src/core/health-check/health-check.controller.ts +0 -13
  233. package/src/core/health-check/health-check.module.ts +0 -7
  234. package/src/core/index.ts +0 -56
  235. package/src/core/koala-app.ts +0 -379
  236. package/src/core/koala-global-vars.ts +0 -8
  237. package/src/core/koala-nest-database.module.ts +0 -65
  238. package/src/core/koala-nest-http.module.ts +0 -44
  239. package/src/core/koala-nest.module.ts +0 -67
  240. package/src/core/mapping/auto-mapping-class-context.ts +0 -28
  241. package/src/core/mapping/auto-mapping-context.ts +0 -26
  242. package/src/core/mapping/auto-mapping-list.ts +0 -154
  243. package/src/core/mapping/auto-mapping-profile.ts +0 -3
  244. package/src/core/mapping/auto-mapping.decorator.ts +0 -54
  245. package/src/core/mapping/auto-mapping.module.ts +0 -17
  246. package/src/core/mapping/auto-mapping.service.ts +0 -187
  247. package/src/core/mapping/create-map.ts +0 -11
  248. package/src/core/mapping/for-member.ts +0 -16
  249. package/src/core/request-overflow/request-handler.base.ts +0 -8
  250. package/src/core/request-overflow/request-result.spec.ts +0 -23
  251. package/src/core/request-overflow/request-result.ts +0 -41
  252. package/src/core/request-overflow/request-validator.base.ts +0 -33
  253. package/src/core/security/strategies/api-key.strategy.ts +0 -45
  254. package/src/core/utils/assing-object.ts +0 -9
  255. package/src/core/utils/env.config.ts +0 -17
  256. package/src/core/utils/filter-request-params.ts +0 -23
  257. package/src/core/utils/find-on-list.ts +0 -18
  258. package/src/core/utils/get-type-by-prop.ts +0 -9
  259. package/src/core/utils/instanciate-class-with-dependencies-injection.ts +0 -12
  260. package/src/core/utils/interfaces/icomparable.ts +0 -6
  261. package/src/core/utils/list.spec.ts +0 -81
  262. package/src/core/utils/list.ts +0 -223
  263. package/src/core/utils/promise-all.ts +0 -24
  264. package/src/core/utils/set-mask-document-number.ts +0 -13
  265. package/src/core/validators/file-validator.ts +0 -113
  266. package/src/decorators/api-exclude-endpoint-diff-develop.decorator.ts +0 -15
  267. package/src/decorators/api-property-enum.decorator.ts +0 -58
  268. package/src/decorators/api-property-only-develop.decorator.ts +0 -6
  269. package/src/decorators/cookies.decorator.ts +0 -8
  270. package/src/decorators/is-public.decorator.ts +0 -5
  271. package/src/decorators/upload.decorator.ts +0 -31
  272. package/src/env/env.module.ts +0 -8
  273. package/src/env/env.service.ts +0 -12
  274. package/src/env/env.ts +0 -14
  275. package/src/filters/domain-errors.filter.ts +0 -97
  276. package/src/filters/global-exception.filter.ts +0 -60
  277. package/src/filters/prisma-validation-exception.filter.ts +0 -73
  278. package/src/filters/zod-errors.filter.ts +0 -48
  279. package/src/services/logging/ilogging.service.ts +0 -17
  280. package/src/services/logging/logging.service.ts +0 -10
  281. package/src/services/redis/iredis.service.ts +0 -11
  282. package/src/services/redis/redis.service.ts +0 -70
  283. package/src/services/redlock/ired-lock.service.ts +0 -4
  284. package/src/services/redlock/red-lock.service.ts +0 -36
  285. package/src/test/koala-app-test-dependencies.ts +0 -15
  286. package/src/test/koala-app-test.ts +0 -103
  287. package/src/test/repositories/in-memory-base.repository.ts +0 -90
  288. package/src/test/services/fake-logging.service.ts +0 -7
  289. package/src/test/services/fake-red-lock.service.ts +0 -11
  290. package/src/test/utils/create-e2e-database.ts +0 -55
  291. package/src/test/utils/drop-e2e-database.ts +0 -36
  292. package/src/test/utils/wait-for.ts +0 -31
  293. package/tsconfig.lib.json +0 -11
@@ -1,548 +0,0 @@
1
- import { toCamelCase } from '@koalarx/utils/KlString'
2
- import { Type } from '@nestjs/common'
3
- import { ListResponse } from '..'
4
- import { PaginationDto } from '../dtos/pagination.dto'
5
- import { KoalaGlobalVars } from '../koala-global-vars'
6
- import { IComparableId } from '../utils/interfaces/icomparable'
7
- import { List } from '../utils/list'
8
- import { EntityActionType, EntityBase } from './entity.base'
9
- import { PrismaTransactionalClient } from './prisma-transactional-client'
10
- import { AutoMappingList } from '../mapping/auto-mapping-list'
11
-
12
- type RepositoryInclude<TEntity> = Omit<
13
- {
14
- [K in keyof TEntity as TEntity[K] extends Function ? never : K]?:
15
- | boolean
16
- | (TEntity[K] extends List<infer U>
17
- ? RepositoryInclude<U>
18
- : RepositoryInclude<TEntity[K]>)
19
- },
20
- '_id' | '_action'
21
- >
22
-
23
- interface RepositoryInitProps<
24
- TEntity extends EntityBase<TEntity>,
25
- TContext extends PrismaTransactionalClient,
26
- > {
27
- context: TContext
28
- modelName: Type<TEntity>
29
- transactionContext?: Type<TContext>
30
- include?: RepositoryInclude<TEntity>
31
- }
32
-
33
- export abstract class RepositoryBase<
34
- TEntity extends EntityBase<TEntity>,
35
- TContext extends PrismaTransactionalClient = PrismaTransactionalClient,
36
- TModelKey extends keyof TContext = keyof TContext,
37
- > {
38
- protected _context: TContext
39
- private readonly _modelName: Type<TEntity>
40
- private readonly _include?: RepositoryInclude<TEntity>
41
-
42
- constructor({
43
- context,
44
- modelName,
45
- include,
46
- }: RepositoryInitProps<TEntity, TContext>) {
47
- this._context = context
48
- this._modelName = modelName
49
- this._include = include
50
- }
51
-
52
- private listRelationEntities(entity: TEntity) {
53
- const relationEntities: TEntity[] = []
54
-
55
- Object.keys(entity).forEach((key) => {
56
- if (entity[key] instanceof List) {
57
- const list = entity[key]
58
-
59
- list.toArray('added').forEach((item) => {
60
- relationEntities.push(item)
61
- relationEntities.push(...this.listRelationEntities(item))
62
- })
63
-
64
- list.toArray('updated').forEach((item) => {
65
- relationEntities.push(item)
66
- relationEntities.push(...this.listRelationEntities(item))
67
- })
68
- } else if (entity[key] instanceof EntityBase) {
69
- relationEntities.push(entity[key] as any)
70
- relationEntities.push(...this.listRelationEntities(entity[key] as any))
71
- }
72
- })
73
-
74
- return relationEntities
75
- }
76
-
77
- private listToRelationActionList(entity: TEntity) {
78
- type RelationActionList = Array<{
79
- modelName: string
80
- entityInstance: Type<TEntity>
81
- schema: any
82
- relations: TEntity[]
83
- }>
84
-
85
- const relationCreates: RelationActionList = []
86
- const relationUpdates: RelationActionList = []
87
- const relationDeletes: RelationActionList = []
88
-
89
- Object.keys(entity).forEach((key) => {
90
- if (entity[key] instanceof List) {
91
- const list = entity[key]
92
- const entityInstance = list.entityType! as any
93
- const modelName = entityInstance.name
94
- const parentModelName = entity.constructor.name
95
-
96
- if (modelName) {
97
- list.toArray('removed').forEach((item) => {
98
- relationDeletes.push({
99
- modelName: toCamelCase(modelName),
100
- entityInstance,
101
- schema: { where: { id: item._id } },
102
- relations: [],
103
- })
104
- })
105
-
106
- list.toArray('added').forEach((item) => {
107
- relationCreates.push({
108
- modelName: toCamelCase(modelName),
109
- entityInstance,
110
- schema: {
111
- data: {
112
- ...this.entityToPrisma(item),
113
- [toCamelCase(parentModelName)]: {
114
- connect: {
115
- [this.getIdPropName(entity)]:
116
- entity[this.getIdPropName(entity)],
117
- },
118
- },
119
- },
120
- },
121
- relations: this.listRelationEntities(item),
122
- })
123
- })
124
-
125
- list.toArray('updated').forEach((item) => {
126
- relationUpdates.push({
127
- modelName: toCamelCase(modelName),
128
- entityInstance,
129
- schema: {
130
- where: { id: item._id },
131
- data: this.entityToPrisma(item),
132
- },
133
- relations: this.listRelationEntities(item),
134
- })
135
- })
136
- }
137
- }
138
- })
139
-
140
- return { relationCreates, relationUpdates, relationDeletes }
141
- }
142
-
143
- private entityToPrisma(entity: TEntity) {
144
- const prismaSchema = {}
145
-
146
- Object.keys(entity)
147
- .filter((key) => !['id', '_id', '_action'].includes(key))
148
- .filter(
149
- (key) =>
150
- !(entity[key] instanceof Function || entity[key] instanceof List),
151
- )
152
- .forEach((key) => {
153
- if (entity[key] instanceof EntityBase) {
154
- if (entity[key]._action === EntityActionType.create) {
155
- if (entity[key][this.getIdPropName(entity)]) {
156
- prismaSchema[key] = {
157
- connectOrCreate: {
158
- where: {
159
- [this.getIdPropName(entity)]:
160
- entity[key][this.getIdPropName(entity)],
161
- },
162
- create: this.entityToPrisma(entity[key] as any),
163
- },
164
- }
165
- } else {
166
- prismaSchema[key] = {
167
- create: this.entityToPrisma(entity[key] as any),
168
- }
169
- }
170
- } else {
171
- prismaSchema[key] = {
172
- update: this.entityToPrisma(entity[key] as any),
173
- }
174
- }
175
- } else {
176
- prismaSchema[key] = entity[key]
177
- }
178
- })
179
-
180
- return prismaSchema
181
- }
182
-
183
- private findManySchema<T>(where: T, pagination?: PaginationDto) {
184
- return {
185
- include: this.getInclude(),
186
- where,
187
- orderBy: pagination?.generateOrderBy(),
188
- skip: pagination?.skip(),
189
- take: (pagination?.limit ?? 0) > 0 ? pagination?.limit : undefined,
190
- }
191
- }
192
-
193
- private createEntity(data: any, entityClass?: Type<TEntity>) {
194
- const entity = new (entityClass || this._modelName)()
195
- entity._action = EntityActionType.update
196
- entity.automap(data)
197
-
198
- return entity
199
- }
200
-
201
- private orphanRemoval(
202
- client: PrismaTransactionalClient,
203
- entity: EntityBase<TEntity>,
204
- ) {
205
- const where = {}
206
-
207
- Object.keys(entity)
208
- .filter((key: string) => key === 'id' || key.includes('Id'))
209
- .forEach((key) => (where[key] = entity[key]))
210
-
211
- return client[toCamelCase(entity.constructor.name)].delete({ where })
212
- }
213
-
214
- private getIdPropName(entity?: TEntity) {
215
- return (
216
- Reflect.getMetadata(
217
- 'entity:id',
218
- entity ? entity.constructor.prototype : this._modelName.prototype,
219
- ) ?? 'id'
220
- )
221
- }
222
-
223
- private getInclude(include?: RepositoryInclude<TEntity>) {
224
- include = include ?? this._include ?? {}
225
-
226
- const result = {}
227
-
228
- Object.keys(include).forEach((key) => {
229
- if (typeof include[key] === 'boolean') {
230
- result[key] = include[key]
231
- } else {
232
- result[key] = {
233
- include: this.getInclude(include[key]),
234
- }
235
- }
236
- })
237
-
238
- return result
239
- }
240
-
241
- private getPropNameFromEntitySource(source: TEntity, entity: Type<TEntity>) {
242
- return Object.keys(source).find((key) => {
243
- const propDefinitions = AutoMappingList.getPropDefinitions(
244
- source.constructor as any,
245
- key,
246
- )
247
-
248
- if (propDefinitions) {
249
- if (propDefinitions.type === entity.name) {
250
- return true
251
- } else if (source[key] instanceof List) {
252
- const list = source[key] as List<any>
253
- return list.entityType?.name === entity.name
254
- }
255
- }
256
-
257
- return false
258
- })
259
- }
260
-
261
- private persistRelations(
262
- transaction: PrismaTransactionalClient,
263
- entity: TEntity,
264
- ) {
265
- const { relationCreates, relationUpdates, relationDeletes } =
266
- this.listToRelationActionList(entity)
267
-
268
- return Promise.all([
269
- ...relationCreates.map((relationCreate) =>
270
- transaction[relationCreate.modelName]
271
- .create(relationCreate.schema)
272
- .then((response) => {
273
- return Promise.all(
274
- relationCreate.relations.map((relation) => {
275
- const relationPropName = this.getPropNameFromEntitySource(
276
- relation,
277
- relationCreate.entityInstance,
278
- )
279
-
280
- if (!relationPropName) {
281
- throw new Error(
282
- `Propname not found for relation entity ${relation.constructor.name} on entity ${relationCreate.entityInstance.constructor.name}`,
283
- )
284
- }
285
-
286
- const relationEntity = this.createEntity(
287
- response,
288
- relationCreate.entityInstance as any,
289
- )
290
- relationEntity._action = EntityActionType.create
291
-
292
- relation[relationPropName] = relationEntity
293
-
294
- return transaction[toCamelCase(relation.constructor.name)]
295
- .create({
296
- data: this.entityToPrisma(relation),
297
- })
298
- .then((response: TEntity) => {
299
- entity[this.getIdPropName(relation)] =
300
- response[this.getIdPropName(relation)]
301
- return this.persistRelations(transaction, relation)
302
- })
303
- }),
304
- )
305
- }),
306
- ),
307
- ...relationUpdates.map((relation) =>
308
- transaction[relation.modelName].update(relation.schema),
309
- ),
310
- ...relationDeletes.map((relation) => this.removeMany(relation.schema)),
311
- ])
312
- }
313
-
314
- protected context(transactionalClient?: TContext): TContext[TModelKey] {
315
- const modelName = this._modelName.name
316
-
317
- if (!modelName)
318
- throw new Error('modelName não informado no contrutor do repositorio')
319
-
320
- const contextKey = toCamelCase(modelName) as TModelKey
321
-
322
- if (transactionalClient) {
323
- return transactionalClient[contextKey] as any
324
- }
325
-
326
- return this._context[contextKey] as any
327
- }
328
-
329
- protected async findById(id: IComparableId): Promise<TEntity | null> {
330
- return (this.context() as any)
331
- .findFirst({
332
- include: this.getInclude(),
333
- where: { [this.getIdPropName()]: id },
334
- })
335
- .then((response: TEntity) => {
336
- if (response) {
337
- return this.createEntity(response)
338
- }
339
-
340
- return null
341
- })
342
- }
343
-
344
- protected async findFirst<T>(where: T): Promise<TEntity | null> {
345
- return (this.context() as any)
346
- .findFirst({
347
- include: this.getInclude(),
348
- where,
349
- })
350
- .then((response: TEntity) => {
351
- if (response) {
352
- return this.createEntity(response)
353
- }
354
-
355
- return null
356
- })
357
- }
358
-
359
- protected async findUnique<T>(where: T): Promise<TEntity | null> {
360
- return (this.context() as any)
361
- .findUnique({
362
- include: this.getInclude(),
363
- where,
364
- })
365
- .then((response: TEntity) => {
366
- if (response) {
367
- return this.createEntity(response)
368
- }
369
-
370
- return null
371
- })
372
- }
373
-
374
- protected async findMany<T>(
375
- where: T,
376
- pagination?: PaginationDto,
377
- ): Promise<TEntity[]> {
378
- return (this.context() as any)
379
- .findMany(this.findManySchema(where, pagination))
380
- .then((result: TEntity[]) =>
381
- result.map((response) => this.createEntity(response)),
382
- )
383
- }
384
-
385
- protected async findManyAndCount<T>(
386
- where: T,
387
- pagination?: PaginationDto,
388
- ): Promise<ListResponse<TEntity>> {
389
- const count = await (this.context() as any).count({ where })
390
-
391
- if (count > 0) {
392
- const items = await this.findMany(
393
- where,
394
- Object.assign(new PaginationDto(), pagination),
395
- )
396
-
397
- return { items, count }
398
- }
399
-
400
- return { items: [], count }
401
- }
402
-
403
- protected async saveChanges<TWhere = any>(
404
- entity: TEntity,
405
- updateWhere?: TWhere,
406
- ): Promise<TEntity> {
407
- const prismaEntity = this.entityToPrisma(entity)
408
-
409
- if (entity._action === EntityActionType.create) {
410
- return this.withTransaction((client) =>
411
- (this.context(client) as any)
412
- .create({
413
- data: prismaEntity,
414
- include: this.getInclude(),
415
- })
416
- .then((response: TEntity) => {
417
- entity[this.getIdPropName()] = response[this.getIdPropName()]
418
- return this.persistRelations(client, entity).then(() => entity)
419
- }),
420
- )
421
- } else {
422
- const where = updateWhere ?? { id: entity._id }
423
-
424
- return this.withTransaction((client) =>
425
- (this.context(client) as any)
426
- .update({
427
- where,
428
- data: prismaEntity,
429
- })
430
- .then(() => this.persistRelations(client, entity)),
431
- ).then(() => this.findUnique(where) as Promise<TEntity>)
432
- }
433
- }
434
-
435
- protected async saveMany<TWhere = any>(
436
- entities: TEntity[],
437
- updateWhere?: TWhere,
438
- ): Promise<void> {
439
- await this.withTransaction(async (client) => {
440
- const prismaEntities = entities.map((entity) =>
441
- this.entityToPrisma(entity),
442
- )
443
-
444
- return Promise.all([
445
- (this.context(client) as any).createMany({
446
- data: prismaEntities,
447
- skipDuplicates: true,
448
- }),
449
- ...entities
450
- .filter((entity) => !!entity._id)
451
- .map((entity) =>
452
- (this.context(client) as any).update({
453
- data: entity,
454
- where: updateWhere ?? { id: entity._id },
455
- }),
456
- ),
457
- ])
458
- })
459
- }
460
-
461
- protected async remove<TWhere = any>(
462
- where: TWhere,
463
- notCascadeEntityProps?: Array<keyof TEntity>,
464
- externalServices?: Promise<any>,
465
- ) {
466
- const entity = await this.findUnique(where)
467
-
468
- if (!entity) {
469
- throw new Error(`Entity not found for where: ${JSON.stringify(where)}`)
470
- }
471
-
472
- const relationEntity: EntityBase<TEntity>[] = []
473
-
474
- Object.keys(entity).forEach((key) => {
475
- if (
476
- entity[key] instanceof EntityBase &&
477
- !notCascadeEntityProps?.includes(key as keyof TEntity)
478
- ) {
479
- relationEntity.push(entity[key])
480
- }
481
- })
482
-
483
- return this.withTransaction((client) =>
484
- (externalServices
485
- ? externalServices.then(() => client)
486
- : Promise.resolve(client)
487
- ).then((client) =>
488
- (this.context(client) as any)
489
- .delete({ where })
490
- .then((response) =>
491
- Promise.all(
492
- relationEntity.map((entity) =>
493
- this.orphanRemoval(client, entity),
494
- ),
495
- ).then(() => response),
496
- ),
497
- ),
498
- )
499
- }
500
-
501
- protected async removeMany<TWhere = any>(
502
- where: TWhere,
503
- notCascadeEntityProps?: Array<keyof TEntity>,
504
- externalServices?: Promise<any>,
505
- ): Promise<void> {
506
- const entities = await this.findMany(where)
507
-
508
- if (entities.length === 0) {
509
- throw new Error(`Entities not found for where: ${JSON.stringify(where)}`)
510
- }
511
-
512
- return this.withTransaction((client) =>
513
- (externalServices
514
- ? externalServices.then(() => client)
515
- : Promise.resolve(client)
516
- ).then(async (client) => {
517
- const relationEntity: EntityBase<TEntity>[] = []
518
-
519
- for (const entity of entities) {
520
- Object.keys(entity).forEach((key) => {
521
- if (
522
- entity[key] instanceof EntityBase &&
523
- !notCascadeEntityProps?.includes(key as keyof TEntity)
524
- ) {
525
- relationEntity.push(entity[key])
526
- }
527
- })
528
- }
529
-
530
- return (this.context(client) as any)
531
- .deleteMany({ where })
532
- .then((response) =>
533
- Promise.all(
534
- relationEntity.map((entity) =>
535
- this.orphanRemoval(client, entity),
536
- ),
537
- ).then(() => response),
538
- )
539
- }),
540
- )
541
- }
542
-
543
- withTransaction(fn: (prisma: TContext) => Promise<any>) {
544
- return this._context.withTransaction(async (client) => {
545
- return fn(new (KoalaGlobalVars.dbTransactionContext as any)(client))
546
- })
547
- }
548
- }
@@ -1,35 +0,0 @@
1
- import type { QueryDirectionType } from '..'
2
- import { QUERY_FILTER_PARAMS } from '../constants/query-params'
3
- import { AutoMap } from '../mapping/auto-mapping.decorator'
4
-
5
- export class PaginationDto {
6
- @AutoMap()
7
- page?: number = 0
8
-
9
- @AutoMap()
10
- limit?: number = QUERY_FILTER_PARAMS.limit
11
-
12
- @AutoMap()
13
- orderBy?: string = ''
14
-
15
- @AutoMap()
16
- direction?: QueryDirectionType = 'asc'
17
-
18
- skip() {
19
- return (this.limit ?? 0) * (this.page ?? QUERY_FILTER_PARAMS.page)
20
- }
21
-
22
- generateOrderBy() {
23
- if (this.orderBy) {
24
- const orderByField = this.orderBy.split('.')
25
- return orderByField.reduceRight(
26
- (acc, item, index) => ({
27
- [item]: index === orderByField.length - 1 ? this.direction : acc,
28
- }),
29
- {},
30
- )
31
- }
32
-
33
- return undefined
34
- }
35
- }
@@ -1,8 +0,0 @@
1
- import { ErrorBase } from './error.base'
2
- import { UseCaseError } from './use-case-error'
3
-
4
- export class BadRequestError extends ErrorBase implements UseCaseError {
5
- constructor(message?: string, data?: any) {
6
- super(message ?? 'Bad Request', data)
7
- }
8
- }
@@ -1,7 +0,0 @@
1
- import { ErrorBase } from './error.base'
2
-
3
- export class ConflictError extends ErrorBase {
4
- constructor(identifier: string, data?: any) {
5
- super(`O registro ${identifier} já existe.`, data)
6
- }
7
- }
@@ -1,5 +0,0 @@
1
- export abstract class ErrorBase extends Error {
2
- constructor(message: string, public readonly data?: any) {
3
- super(message)
4
- }
5
- }
@@ -1,8 +0,0 @@
1
- import { ErrorBase } from './error.base'
2
- import { UseCaseError } from './use-case-error'
3
-
4
- export class NoContentError extends ErrorBase implements UseCaseError {
5
- constructor(message?: string, data?: any) {
6
- super(message ?? 'No Content', data)
7
- }
8
- }
@@ -1,8 +0,0 @@
1
- import { ErrorBase } from './error.base'
2
- import { UseCaseError } from './use-case-error'
3
-
4
- export class NotAllowedError extends ErrorBase implements UseCaseError {
5
- constructor(message?: string, data?: any) {
6
- super(message ?? 'Você não tem permissão para utilizar esse recurso.', data)
7
- }
8
- }
@@ -1,8 +0,0 @@
1
- import { ErrorBase } from './error.base'
2
- import { UseCaseError } from './use-case-error'
3
-
4
- export class ResourceNotFoundError extends ErrorBase implements UseCaseError {
5
- constructor(name = 'Recurso', data?: any) {
6
- super(`${name} não encontrado(a).`, data)
7
- }
8
- }
@@ -1,7 +0,0 @@
1
- import { ErrorBase } from './error.base'
2
-
3
- export class UserAlreadyExist extends ErrorBase {
4
- constructor(identifier: string, data?: any) {
5
- super(`User ${identifier} already exists`, data)
6
- }
7
- }
@@ -1,7 +0,0 @@
1
- import { ErrorBase } from './error.base'
2
-
3
- export class WrongCredentialsError extends ErrorBase {
4
- constructor(data?: any) {
5
- super('Credentials are not valid', data)
6
- }
7
- }
@@ -1,13 +0,0 @@
1
- import { IsPublic } from '@koalarx/nest/decorators/is-public.decorator'
2
- import { Controller, Get } from '@nestjs/common'
3
- import { ApiExcludeEndpoint } from '@nestjs/swagger'
4
-
5
- @Controller('health')
6
- export class HealthCheckController {
7
- @Get()
8
- @IsPublic()
9
- @ApiExcludeEndpoint()
10
- healthCheck() {
11
- return { status: 'ok' }
12
- }
13
- }
@@ -1,7 +0,0 @@
1
- import { Module } from '@nestjs/common'
2
- import { HealthCheckController } from './health-check.controller'
3
-
4
- @Module({
5
- controllers: [HealthCheckController],
6
- })
7
- export class HealthCheckModule {}