@autofleet/sadot 1.1.6-beta → 1.1.6

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 (331) hide show
  1. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs +1 -0
  2. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js +1 -0
  3. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs +1 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js +1 -0
  5. package/dist/_virtual/rolldown_runtime.cjs +1 -0
  6. package/dist/api/index.cjs +2 -0
  7. package/dist/api/index.cjs.map +1 -0
  8. package/dist/api/index.js +2 -12
  9. package/dist/api/index.js.map +1 -0
  10. package/dist/api/v1/definition/index.cjs +2 -0
  11. package/dist/api/v1/definition/index.cjs.map +1 -0
  12. package/dist/api/v1/definition/index.js +2 -116
  13. package/dist/api/v1/definition/index.js.map +1 -0
  14. package/dist/api/v1/definition/validations.cjs +2 -0
  15. package/dist/api/v1/definition/validations.cjs.map +1 -0
  16. package/dist/api/v1/definition/validations.js +2 -77
  17. package/dist/api/v1/definition/validations.js.map +1 -0
  18. package/dist/api/v1/errors.cjs +2 -0
  19. package/dist/api/v1/errors.cjs.map +1 -0
  20. package/dist/api/v1/errors.js +2 -12
  21. package/dist/api/v1/errors.js.map +1 -0
  22. package/dist/api/v1/index.cjs +2 -0
  23. package/dist/api/v1/index.cjs.map +1 -0
  24. package/dist/api/v1/index.js +2 -13
  25. package/dist/api/v1/index.js.map +1 -0
  26. package/dist/api/v1/validator/index.cjs +2 -0
  27. package/dist/api/v1/validator/index.cjs.map +1 -0
  28. package/dist/api/v1/validator/index.js +2 -143
  29. package/dist/api/v1/validator/index.js.map +1 -0
  30. package/dist/api/v1/validator/validations.cjs +2 -0
  31. package/dist/api/v1/validator/validations.cjs.map +1 -0
  32. package/dist/api/v1/validator/validations.d.cts +23 -0
  33. package/dist/api/v1/validator/validations.d.ts +23 -6
  34. package/dist/api/v1/validator/validations.js +2 -38
  35. package/dist/api/v1/validator/validations.js.map +1 -0
  36. package/dist/errors/index.cjs +3 -0
  37. package/dist/errors/index.cjs.map +1 -0
  38. package/dist/errors/index.js +3 -66
  39. package/dist/errors/index.js.map +1 -0
  40. package/dist/events/index.cjs +2 -0
  41. package/dist/events/index.cjs.map +1 -0
  42. package/dist/events/index.js +2 -54
  43. package/dist/events/index.js.map +1 -0
  44. package/dist/hooks/enrich.cjs +2 -0
  45. package/dist/hooks/enrich.cjs.map +1 -0
  46. package/dist/hooks/enrich.js +2 -198
  47. package/dist/hooks/enrich.js.map +1 -0
  48. package/dist/hooks/find.cjs +2 -0
  49. package/dist/hooks/find.cjs.map +1 -0
  50. package/dist/hooks/find.js +2 -29
  51. package/dist/hooks/find.js.map +1 -0
  52. package/dist/hooks/hooks.cjs +2 -0
  53. package/dist/hooks/hooks.cjs.map +1 -0
  54. package/dist/hooks/hooks.js +2 -388
  55. package/dist/hooks/hooks.js.map +1 -0
  56. package/dist/hooks/index.cjs +1 -0
  57. package/dist/hooks/index.js +1 -17
  58. package/dist/hooks/utils/updateInstanceValues.cjs +2 -0
  59. package/dist/hooks/utils/updateInstanceValues.cjs.map +1 -0
  60. package/dist/hooks/utils/updateInstanceValues.js +2 -50
  61. package/dist/hooks/utils/updateInstanceValues.js.map +1 -0
  62. package/dist/index.cjs +2 -0
  63. package/dist/index.cjs.map +1 -0
  64. package/dist/index.d.cts +23 -0
  65. package/dist/index.d.ts +22 -12
  66. package/dist/index.js +2 -67
  67. package/dist/index.js.map +1 -0
  68. package/dist/models/CustomFieldDefinition.cjs +2 -0
  69. package/dist/models/CustomFieldDefinition.cjs.map +1 -0
  70. package/dist/models/CustomFieldDefinition.d.cts +31 -0
  71. package/dist/models/CustomFieldDefinition.d.ts +29 -23
  72. package/dist/models/CustomFieldDefinition.js +2 -192
  73. package/dist/models/CustomFieldDefinition.js.map +1 -0
  74. package/dist/models/CustomFieldEntries.cjs +2 -0
  75. package/dist/models/CustomFieldEntries.cjs.map +1 -0
  76. package/dist/models/CustomFieldEntries.d.cts +16 -0
  77. package/dist/models/CustomFieldEntries.d.ts +14 -13
  78. package/dist/models/CustomFieldEntries.js +2 -123
  79. package/dist/models/CustomFieldEntries.js.map +1 -0
  80. package/dist/models/CustomFieldValue.cjs +2 -0
  81. package/dist/models/CustomFieldValue.cjs.map +1 -0
  82. package/dist/models/CustomFieldValue.d.cts +22 -0
  83. package/dist/models/CustomFieldValue.d.ts +20 -14
  84. package/dist/models/CustomFieldValue.js +2 -151
  85. package/dist/models/CustomFieldValue.js.map +1 -0
  86. package/dist/models/CustomValidator.cjs +2 -0
  87. package/dist/models/CustomValidator.cjs.map +1 -0
  88. package/dist/models/CustomValidator.d.cts +19 -0
  89. package/dist/models/CustomValidator.d.ts +17 -15
  90. package/dist/models/CustomValidator.js +2 -98
  91. package/dist/models/CustomValidator.js.map +1 -0
  92. package/dist/models/index.cjs +2 -0
  93. package/dist/models/index.cjs.map +1 -0
  94. package/dist/models/index.d.cts +6 -0
  95. package/dist/models/index.d.ts +6 -18
  96. package/dist/models/index.js +2 -131
  97. package/dist/models/index.js.map +1 -0
  98. package/dist/models/tests/AssociatedTestModel.cjs +2 -0
  99. package/dist/models/tests/AssociatedTestModel.cjs.map +1 -0
  100. package/dist/models/tests/AssociatedTestModel.js +2 -71
  101. package/dist/models/tests/AssociatedTestModel.js.map +1 -0
  102. package/dist/models/tests/TestModel.cjs +2 -0
  103. package/dist/models/tests/TestModel.cjs.map +1 -0
  104. package/dist/models/tests/TestModel.js +2 -69
  105. package/dist/models/tests/TestModel.js.map +1 -0
  106. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +2 -0
  107. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +1 -0
  108. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +2 -53
  109. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +1 -0
  110. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +2 -0
  111. package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +1 -0
  112. package/dist/models/tests/contextAwareModels/ContextTestModel.js +2 -47
  113. package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +1 -0
  114. package/dist/repository/definition.cjs +2 -0
  115. package/dist/repository/definition.cjs.map +1 -0
  116. package/dist/repository/definition.js +2 -121
  117. package/dist/repository/definition.js.map +1 -0
  118. package/dist/repository/entries.cjs +2 -0
  119. package/dist/repository/entries.cjs.map +1 -0
  120. package/dist/repository/entries.js +2 -92
  121. package/dist/repository/entries.js.map +1 -0
  122. package/dist/repository/utils/formatValues.cjs +2 -0
  123. package/dist/repository/utils/formatValues.cjs.map +1 -0
  124. package/dist/repository/utils/formatValues.js +2 -16
  125. package/dist/repository/utils/formatValues.js.map +1 -0
  126. package/dist/repository/validator.cjs +2 -0
  127. package/dist/repository/validator.cjs.map +1 -0
  128. package/dist/repository/validator.js +2 -69
  129. package/dist/repository/validator.js.map +1 -0
  130. package/dist/repository/value.cjs +2 -0
  131. package/dist/repository/value.cjs.map +1 -0
  132. package/dist/repository/value.js +2 -124
  133. package/dist/repository/value.js.map +1 -0
  134. package/dist/scopes/filter.cjs +2 -0
  135. package/dist/scopes/filter.cjs.map +1 -0
  136. package/dist/scopes/filter.d.cts +23 -0
  137. package/dist/scopes/filter.d.ts +22 -29
  138. package/dist/scopes/filter.js +2 -75
  139. package/dist/scopes/filter.js.map +1 -0
  140. package/dist/scopes/helpers/filter.helpers.cjs +46 -0
  141. package/dist/scopes/helpers/filter.helpers.cjs.map +1 -0
  142. package/dist/scopes/helpers/filter.helpers.d.cts +17 -0
  143. package/dist/scopes/helpers/filter.helpers.d.ts +15 -40
  144. package/dist/scopes/helpers/filter.helpers.js +25 -183
  145. package/dist/scopes/helpers/filter.helpers.js.map +1 -0
  146. package/dist/scopes/index.cjs +1 -0
  147. package/dist/scopes/index.js +1 -6
  148. package/dist/types/index.d.cts +45 -0
  149. package/dist/types/index.d.ts +45 -46
  150. package/dist/utils/constants/index.cjs +2 -0
  151. package/dist/utils/constants/index.cjs.map +1 -0
  152. package/dist/utils/constants/index.d.cts +22 -0
  153. package/dist/utils/constants/index.d.ts +20 -17
  154. package/dist/utils/constants/index.js +2 -22
  155. package/dist/utils/constants/index.js.map +1 -0
  156. package/dist/utils/db/index.cjs +2 -0
  157. package/dist/utils/db/index.cjs.map +1 -0
  158. package/dist/utils/db/index.js +2 -24
  159. package/dist/utils/db/index.js.map +1 -0
  160. package/dist/utils/helpers/index.cjs +2 -0
  161. package/dist/utils/helpers/index.cjs.map +1 -0
  162. package/dist/utils/helpers/index.d.cts +31 -0
  163. package/dist/utils/helpers/index.d.ts +28 -23
  164. package/dist/utils/helpers/index.js +2 -40
  165. package/dist/utils/helpers/index.js.map +1 -0
  166. package/dist/utils/init.cjs +2 -0
  167. package/dist/utils/init.cjs.map +1 -0
  168. package/dist/utils/init.js +2 -112
  169. package/dist/utils/init.js.map +1 -0
  170. package/dist/utils/logger/index.cjs +2 -0
  171. package/dist/utils/logger/index.cjs.map +1 -0
  172. package/dist/utils/logger/index.js +2 -42
  173. package/dist/utils/logger/index.js.map +1 -0
  174. package/dist/utils/scopeAttributes.cjs +2 -0
  175. package/dist/utils/scopeAttributes.cjs.map +1 -0
  176. package/dist/utils/scopeAttributes.js +2 -11
  177. package/dist/utils/scopeAttributes.js.map +1 -0
  178. package/dist/utils/validations/index.cjs +2 -0
  179. package/dist/utils/validations/index.cjs.map +1 -0
  180. package/dist/utils/validations/index.js +2 -41
  181. package/dist/utils/validations/index.js.map +1 -0
  182. package/dist/utils/validations/schema/custom-fields.cjs +2 -0
  183. package/dist/utils/validations/schema/custom-fields.cjs.map +1 -0
  184. package/dist/utils/validations/schema/custom-fields.d.cts +7 -0
  185. package/dist/utils/validations/schema/custom-fields.d.ts +6 -2
  186. package/dist/utils/validations/schema/custom-fields.js +2 -9
  187. package/dist/utils/validations/schema/custom-fields.js.map +1 -0
  188. package/dist/utils/validations/schema/validator-schema.cjs +2 -0
  189. package/dist/utils/validations/schema/validator-schema.cjs.map +1 -0
  190. package/dist/utils/validations/schema/validator-schema.js +2 -95
  191. package/dist/utils/validations/schema/validator-schema.js.map +1 -0
  192. package/dist/utils/validations/validators/index.cjs +2 -0
  193. package/dist/utils/validations/validators/index.cjs.map +1 -0
  194. package/dist/utils/validations/validators/index.js +2 -40
  195. package/dist/utils/validations/validators/index.js.map +1 -0
  196. package/dist/utils/validations/validators/select.validator.cjs +2 -0
  197. package/dist/utils/validations/validators/select.validator.cjs.map +1 -0
  198. package/dist/utils/validations/validators/select.validator.js +2 -12
  199. package/dist/utils/validations/validators/select.validator.js.map +1 -0
  200. package/dist/utils/validations/validators/status.validator.cjs +2 -0
  201. package/dist/utils/validations/validators/status.validator.cjs.map +1 -0
  202. package/dist/utils/validations/validators/status.validator.js +2 -15
  203. package/dist/utils/validations/validators/status.validator.js.map +1 -0
  204. package/package.json +40 -39
  205. package/.nvmrc +0 -1
  206. package/dist/api/index.d.ts +0 -3
  207. package/dist/api/v1/definition/index.d.ts +0 -3
  208. package/dist/api/v1/definition/validations.d.ts +0 -2
  209. package/dist/api/v1/errors.d.ts +0 -4
  210. package/dist/api/v1/index.d.ts +0 -3
  211. package/dist/api/v1/validator/index.d.ts +0 -3
  212. package/dist/errors/index.d.ts +0 -24
  213. package/dist/events/index.d.ts +0 -5
  214. package/dist/hooks/create.d.ts +0 -10
  215. package/dist/hooks/create.js +0 -95
  216. package/dist/hooks/enrich.d.ts +0 -25
  217. package/dist/hooks/find.d.ts +0 -1
  218. package/dist/hooks/hooks.d.ts +0 -17
  219. package/dist/hooks/index.d.ts +0 -5
  220. package/dist/hooks/update.d.ts +0 -10
  221. package/dist/hooks/update.js +0 -49
  222. package/dist/hooks/utils/updateInstanceValues.d.ts +0 -15
  223. package/dist/hooks/workaround.d.ts +0 -10
  224. package/dist/hooks/workaround.js +0 -37
  225. package/dist/models/tests/AssociatedTestModel.d.ts +0 -12
  226. package/dist/models/tests/TestModel.d.ts +0 -12
  227. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +0 -10
  228. package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +0 -13
  229. package/dist/repository/definition.d.ts +0 -36
  230. package/dist/repository/entries.d.ts +0 -13
  231. package/dist/repository/utils/formatValues.d.ts +0 -3
  232. package/dist/repository/validator.d.ts +0 -28
  233. package/dist/repository/value.d.ts +0 -28
  234. package/dist/scopes/index.d.ts +0 -2
  235. package/dist/tests/api/test-api.d.ts +0 -2
  236. package/dist/tests/api/test-api.js +0 -38
  237. package/dist/tests/functional/searching/index.d.ts +0 -8
  238. package/dist/tests/functional/searching/index.js +0 -44
  239. package/dist/tests/helpers/commonHooks.d.ts +0 -6
  240. package/dist/tests/helpers/commonHooks.js +0 -62
  241. package/dist/tests/helpers/database-config.d.ts +0 -16
  242. package/dist/tests/helpers/database-config.js +0 -17
  243. package/dist/tests/helpers/index.d.ts +0 -7
  244. package/dist/tests/helpers/index.js +0 -33
  245. package/dist/tests/mocks/definition.mock.d.ts +0 -48
  246. package/dist/tests/mocks/definition.mock.js +0 -78
  247. package/dist/tests/mocks/events.mock.d.ts +0 -4
  248. package/dist/tests/mocks/events.mock.js +0 -21
  249. package/dist/tests/mocks/testModel.d.ts +0 -12
  250. package/dist/tests/mocks/testModel.js +0 -35
  251. package/dist/types/definition/index.d.ts +0 -25
  252. package/dist/types/definition/index.js +0 -2
  253. package/dist/types/entries/index.d.ts +0 -25
  254. package/dist/types/entries/index.js +0 -2
  255. package/dist/types/index.js +0 -2
  256. package/dist/types/value/index.d.ts +0 -15
  257. package/dist/types/value/index.js +0 -2
  258. package/dist/utils/db/index.d.ts +0 -4
  259. package/dist/utils/init.d.ts +0 -7
  260. package/dist/utils/logger/index.d.ts +0 -3
  261. package/dist/utils/scopeAttributes.d.ts +0 -2
  262. package/dist/utils/validations/index.d.ts +0 -8
  263. package/dist/utils/validations/schema/validator-schema.d.ts +0 -9
  264. package/dist/utils/validations/type.d.ts +0 -15
  265. package/dist/utils/validations/type.js +0 -2
  266. package/dist/utils/validations/validators/index.d.ts +0 -14
  267. package/dist/utils/validations/validators/select.validator.d.ts +0 -5
  268. package/dist/utils/validations/validators/status.validator.d.ts +0 -12
  269. package/src/api/index.ts +0 -10
  270. package/src/api/v1/definition/index.ts +0 -104
  271. package/src/api/v1/definition/validations.ts +0 -75
  272. package/src/api/v1/errors.ts +0 -13
  273. package/src/api/v1/index.ts +0 -11
  274. package/src/api/v1/validator/index.ts +0 -141
  275. package/src/api/v1/validator/validations.ts +0 -38
  276. package/src/errors/index.ts +0 -70
  277. package/src/events/index.ts +0 -63
  278. package/src/hooks/create.ts +0 -81
  279. package/src/hooks/enrich.ts +0 -255
  280. package/src/hooks/find.ts +0 -27
  281. package/src/hooks/hooks.ts +0 -479
  282. package/src/hooks/index.ts +0 -20
  283. package/src/hooks/update.ts +0 -55
  284. package/src/hooks/utils/updateInstanceValues.ts +0 -63
  285. package/src/hooks/workaround.ts +0 -47
  286. package/src/index.ts +0 -52
  287. package/src/models/CustomFieldDefinition.ts +0 -162
  288. package/src/models/CustomFieldEntries.ts +0 -81
  289. package/src/models/CustomFieldValue.ts +0 -118
  290. package/src/models/CustomValidator.ts +0 -78
  291. package/src/models/index.ts +0 -165
  292. package/src/models/tests/AssociatedTestModel.ts +0 -57
  293. package/src/models/tests/TestModel.ts +0 -54
  294. package/src/models/tests/contextAwareModels/ContextAwareTestModel.ts +0 -43
  295. package/src/models/tests/contextAwareModels/ContextTestModel.ts +0 -38
  296. package/src/repository/definition.ts +0 -175
  297. package/src/repository/entries.ts +0 -88
  298. package/src/repository/utils/formatValues.ts +0 -14
  299. package/src/repository/validator.ts +0 -119
  300. package/src/repository/value.ts +0 -116
  301. package/src/scopes/filter.ts +0 -100
  302. package/src/scopes/helpers/filter.helpers.ts +0 -227
  303. package/src/scopes/index.ts +0 -6
  304. package/src/tests/api/test-api.ts +0 -40
  305. package/src/tests/functional/searching/index.ts +0 -39
  306. package/src/tests/helpers/commonHooks.ts +0 -43
  307. package/src/tests/helpers/database-config.ts +0 -15
  308. package/src/tests/helpers/index.ts +0 -35
  309. package/src/tests/mocks/definition.mock.ts +0 -84
  310. package/src/tests/mocks/events.mock.ts +0 -21
  311. package/src/tests/mocks/testModel.ts +0 -37
  312. package/src/types/definition/index.ts +0 -24
  313. package/src/types/entries/index.ts +0 -27
  314. package/src/types/index.ts +0 -52
  315. package/src/types/value/index.ts +0 -14
  316. package/src/utils/constants/index.ts +0 -25
  317. package/src/utils/db/index.ts +0 -21
  318. package/src/utils/helpers/index.ts +0 -66
  319. package/src/utils/init.ts +0 -122
  320. package/src/utils/logger/index.ts +0 -14
  321. package/src/utils/scopeAttributes.ts +0 -12
  322. package/src/utils/validations/index.ts +0 -46
  323. package/src/utils/validations/schema/README.md +0 -93
  324. package/src/utils/validations/schema/custom-fields.ts +0 -8
  325. package/src/utils/validations/schema/validator-schema.ts +0 -106
  326. package/src/utils/validations/type.ts +0 -20
  327. package/src/utils/validations/validators/index.ts +0 -38
  328. package/src/utils/validations/validators/select.validator.ts +0 -12
  329. package/src/utils/validations/validators/status.validator.ts +0 -22
  330. package/tsconfig.build.json +0 -7
  331. package/tsconfig.json +0 -16
@@ -0,0 +1,23 @@
1
+ import Joi from "joi";
2
+
3
+ //#region src/api/v1/validator/validations.d.ts
4
+ interface SchemaObject {
5
+ type: "object";
6
+ properties?: {
7
+ before?: object;
8
+ after?: object;
9
+ };
10
+ required?: string[];
11
+ allOf?: object[];
12
+ anyOf?: object[];
13
+ oneOf?: object[];
14
+ additionalProperties?: boolean | object;
15
+ $id?: string;
16
+ $schema?: string;
17
+ if?: object;
18
+ then?: object;
19
+ else?: object;
20
+ }
21
+ //#endregion
22
+ export { SchemaObject };
23
+ //# sourceMappingURL=validations.d.cts.map
@@ -1,6 +1,23 @@
1
- import Joi from 'joi';
2
- declare const validationSchemas: {
3
- create: Joi.ObjectSchema<any>;
4
- update: Joi.ObjectSchema<any>;
5
- };
6
- export default validationSchemas;
1
+ import Joi from "joi";
2
+
3
+ //#region src/api/v1/validator/validations.d.ts
4
+ interface SchemaObject {
5
+ type: "object";
6
+ properties?: {
7
+ before?: object;
8
+ after?: object;
9
+ };
10
+ required?: string[];
11
+ allOf?: object[];
12
+ anyOf?: object[];
13
+ oneOf?: object[];
14
+ additionalProperties?: boolean | object;
15
+ $id?: string;
16
+ $schema?: string;
17
+ if?: object;
18
+ then?: object;
19
+ else?: object;
20
+ }
21
+ //#endregion
22
+ export { SchemaObject };
23
+ //# sourceMappingURL=validations.d.ts.map
@@ -1,38 +1,2 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const joi_1 = __importDefault(require("joi"));
7
- const jsonSchemaValidation = joi_1.default.object().unknown(true);
8
- const schemaObject = joi_1.default.object({
9
- type: joi_1.default.string().valid('object'),
10
- properties: joi_1.default.object({
11
- before: jsonSchemaValidation,
12
- after: jsonSchemaValidation,
13
- }).required(),
14
- required: joi_1.default.array().items(joi_1.default.string()),
15
- allOf: joi_1.default.array().items(joi_1.default.object()),
16
- anyOf: joi_1.default.array().items(joi_1.default.object()),
17
- oneOf: joi_1.default.array().items(joi_1.default.object()),
18
- additionalProperties: joi_1.default.alternatives().try(joi_1.default.boolean(), joi_1.default.object()),
19
- $id: joi_1.default.string(),
20
- $schema: joi_1.default.string(),
21
- if: joi_1.default.object(),
22
- then: joi_1.default.object(),
23
- else: joi_1.default.object(),
24
- });
25
- const validationSchemas = {
26
- create: joi_1.default.object({
27
- entityId: joi_1.default.string().uuid().required(),
28
- entityType: joi_1.default.string().required(),
29
- schema: schemaObject.required(),
30
- }),
31
- update: joi_1.default.object({
32
- entityId: joi_1.default.string().uuid(),
33
- entityType: joi_1.default.string(),
34
- schema: schemaObject,
35
- disabled: joi_1.default.boolean(),
36
- }).min(1),
37
- };
38
- exports.default = validationSchemas;
1
+ import e from"joi";const t=e.object().unknown(!0),n=e.object({type:e.string().valid(`object`),properties:e.object({before:t,after:t}).required(),required:e.array().items(e.string()),allOf:e.array().items(e.object()),anyOf:e.array().items(e.object()),oneOf:e.array().items(e.object()),additionalProperties:e.alternatives().try(e.boolean(),e.object()),$id:e.string(),$schema:e.string(),if:e.object(),then:e.object(),else:e.object()});var r={create:e.object({entityId:e.string().uuid().required(),entityType:e.string().required(),schema:n.required()}),update:e.object({entityId:e.string().uuid(),entityType:e.string(),schema:n,disabled:e.boolean()}).min(1)};export{r as default};
2
+ //# sourceMappingURL=validations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validations.js","names":["validationSchemas: ValidationSchemas"],"sources":["../../../../src/api/v1/validator/validations.ts"],"sourcesContent":["import Joi from 'joi';\n\nconst jsonSchemaValidation = Joi.object().unknown(true);\n\nexport interface SchemaObject {\n type: 'object';\n properties?: {\n before?: object;\n after?: object;\n };\n required?: string[];\n allOf?: object[];\n anyOf?: object[];\n oneOf?: object[];\n additionalProperties?: boolean | object;\n $id?: string;\n $schema?: string;\n if?: object;\n then?: object;\n else?: object;\n}\n\nconst schemaObject = Joi.object<SchemaObject>({\n type: Joi.string().valid('object'),\n properties: Joi.object({\n before: jsonSchemaValidation,\n after: jsonSchemaValidation,\n }).required(),\n required: Joi.array().items(Joi.string()),\n allOf: Joi.array().items(Joi.object()),\n anyOf: Joi.array().items(Joi.object()),\n oneOf: Joi.array().items(Joi.object()),\n additionalProperties: Joi.alternatives().try(Joi.boolean(), Joi.object()),\n $id: Joi.string(),\n $schema: Joi.string(),\n if: Joi.object(),\n then: Joi.object(),\n else: Joi.object(),\n});\n\nexport interface CreateValidatorPayload {\n entityId: string;\n entityType: string;\n schema: SchemaObject;\n}\n\nexport interface UpdateValidatorPayload extends Partial<CreateValidatorPayload> {\n disabled?: boolean;\n}\n\ninterface ValidationSchemas {\n create: Joi.ObjectSchema<CreateValidatorPayload>;\n update: Joi.ObjectSchema<UpdateValidatorPayload>;\n}\n\nconst validationSchemas: ValidationSchemas = {\n create: Joi.object<CreateValidatorPayload>({\n entityId: Joi.string().uuid().required(),\n entityType: Joi.string().required(),\n schema: schemaObject.required(),\n }),\n\n update: Joi.object<UpdateValidatorPayload>({\n entityId: Joi.string().uuid(),\n entityType: Joi.string(),\n schema: schemaObject,\n disabled: Joi.boolean(),\n }).min(1),\n};\n\nexport default validationSchemas;\n"],"mappings":"mBAEA,MAAM,EAAuB,EAAI,QAAQ,CAAC,QAAQ,GAAK,CAoBjD,EAAe,EAAI,OAAqB,CAC5C,KAAM,EAAI,QAAQ,CAAC,MAAM,SAAS,CAClC,WAAY,EAAI,OAAO,CACrB,OAAQ,EACR,MAAO,EACR,CAAC,CAAC,UAAU,CACb,SAAU,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACzC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,MAAO,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,CACtC,qBAAsB,EAAI,cAAc,CAAC,IAAI,EAAI,SAAS,CAAE,EAAI,QAAQ,CAAC,CACzE,IAAK,EAAI,QAAQ,CACjB,QAAS,EAAI,QAAQ,CACrB,GAAI,EAAI,QAAQ,CAChB,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CACnB,CAAC,CAgCF,IAAA,EAf6C,CAC3C,OAAQ,EAAI,OAA+B,CACzC,SAAU,EAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,CACxC,WAAY,EAAI,QAAQ,CAAC,UAAU,CACnC,OAAQ,EAAa,UAAU,CAChC,CAAC,CAEF,OAAQ,EAAI,OAA+B,CACzC,SAAU,EAAI,QAAQ,CAAC,MAAM,CAC7B,WAAY,EAAI,QAAQ,CACxB,OAAQ,EACR,SAAU,EAAI,SAAS,CACxB,CAAC,CAAC,IAAI,EAAE,CACV"}
@@ -0,0 +1,3 @@
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`);let t=require(`@autofleet/errors`);var n=class extends t.BadRequest{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],void 0,e),this.message=`MISSING_REQUIRED_CUSTOM_FIELDS`}},r=class extends t.BadRequest{constructor(e){let t=Error(`Type "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_FIELD_TYPE`}},i=class extends t.BadRequest{constructor(e){let t=Error(`Validation for "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_VALIDATION_TYPE`}},a=class extends t.BadRequest{constructor(e){let t=Error(`Invalid field type ${e}`);super([t],void 0,null),this.message=`INVALID_FIELD_TYPE`}},o=class extends t.BadRequest{constructor(e,t,n){let r=`Invalid Value on field '${t}'. ${n.message.replace(/"/g,``).replace(`value`,`'${t}'`)}. received: '${typeof e==`object`?JSON.stringify(e):e}'`;super([Error(r)],void 0,null),this.message=r}},s=class extends t.BadRequest{constructor(e,t){let n=t.map(e=>new o(e.value,e.fieldDefinitionName,e.joiValidationError));super(n,void 0,null),this.message=`Invalid entries on ${e}\n${t.map(e=>`${e.fieldDefinitionName} - ${e.joiValidationError.message}`).join(`
2
+ `)}`}},c=class extends t.BadRequest{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],void 0,null),this.message=`MISSING_DEFINITION`}};exports.InvalidEntriesError=s,exports.InvalidFieldTypeError=a,exports.InvalidValueError=o,exports.MissingDefinitionError=c,exports.MissingRequiredCustomFieldError=n,exports.UnsupportedCustomFieldTypeError=r,exports.UnsupportedCustomValidationError=i;
3
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["BadRequest"],"sources":["../../src/errors/index.ts"],"sourcesContent":["import { BadRequest } from '@autofleet/errors';\nimport type { ValidationError } from 'joi';\nimport type { EntriesValidationError } from '../types/entries';\n\nexport class MissingRequiredCustomFieldError extends BadRequest {\n constructor(missingFields: string[]) {\n const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);\n super([err], undefined, missingFields);\n this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';\n }\n}\n\nexport class UnsupportedCustomFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Type \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';\n }\n}\n\nexport class UnsupportedCustomValidationError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Validation for \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';\n }\n}\n\nexport class InvalidFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Invalid field type ${fieldType}`);\n super([err], undefined, null);\n this.message = 'INVALID_FIELD_TYPE';\n }\n}\n\nexport class InvalidValueError extends BadRequest {\n constructor(value: any, fieldDefinitionName: string, joiValidationError: ValidationError) {\n const formattedErrorMessage = joiValidationError.message\n .replace(/\"/g, '')\n .replace('value', `'${fieldDefinitionName}'`);\n\n const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;\n\n const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;\n\n const err = new Error(invalidValueMessage);\n super([err], undefined, null);\n this.message = invalidValueMessage;\n }\n}\n\nexport class InvalidEntriesError extends BadRequest {\n constructor(modelId: string, validationErrors: EntriesValidationError[]) {\n const errors = validationErrors.map(validationError => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));\n super(errors, undefined, null);\n this.message = `Invalid entries on ${modelId}\\n${validationErrors.map(validationError => (\n `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`\n )).join('\\n')}`;\n }\n}\n\nexport class MissingDefinitionError extends BadRequest {\n constructor(fieldNames: string[]) {\n const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);\n super([err], undefined, null);\n this.message = 'MISSING_DEFINITION';\n }\n}\n"],"mappings":"uFAIA,IAAa,EAAb,cAAqDA,EAAAA,UAAW,CAC9D,YAAY,EAAyB,CACnC,IAAM,EAAU,MAAM,6CAA6C,EAAc,KAAK,IAAI,GAAG,CAC7F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,EAAc,CACtC,KAAK,QAAU,mCAIN,EAAb,cAAqDA,EAAAA,UAAW,CAC9D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,SAAS,EAAU,oBAAoB,CAC7D,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,kCAIN,EAAb,cAAsDA,EAAAA,UAAW,CAC/D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,mBAAmB,EAAU,oBAAoB,CACvE,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uCAIN,EAAb,cAA2CA,EAAAA,UAAW,CACpD,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,sBAAsB,IAAY,CACxD,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uBAIN,EAAb,cAAuCA,EAAAA,UAAW,CAChD,YAAY,EAAY,EAA6B,EAAqC,CAOxF,IAAM,EAAsB,2BAA2B,EAAoB,KAN7C,EAAmB,QAC9C,QAAQ,KAAM,GAAG,CACjB,QAAQ,QAAS,IAAI,EAAoB,GAAG,CAIuD,eAF/E,OAAO,GAAU,SAAW,KAAK,UAAU,EAAM,CAAG,EAEyD,GAGpI,MAAM,CADU,MAAM,EAAoB,CAC/B,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,IAIN,EAAb,cAAyCA,EAAAA,UAAW,CAClD,YAAY,EAAiB,EAA4C,CACvE,IAAM,EAAS,EAAiB,IAAI,GAAmB,IAAI,EAAkB,EAAgB,MAAO,EAAgB,oBAAqB,EAAgB,mBAAmB,CAAC,CAC7K,MAAM,EAAQ,IAAA,GAAW,KAAK,CAC9B,KAAK,QAAU,sBAAsB,EAAQ,IAAI,EAAiB,IAAI,GACpE,GAAG,EAAgB,oBAAoB,KAAK,EAAgB,mBAAmB,UAC/E,CAAC,KAAK;EAAK,KAIJ,EAAb,cAA4CA,EAAAA,UAAW,CACrD,YAAY,EAAsB,CAChC,IAAM,EAAU,MAAM,6CAA6C,EAAW,KAAK,IAAI,GAAG,CAC1F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU"}
@@ -1,66 +1,3 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MissingDefinitionError = exports.InvalidEntriesError = exports.InvalidValueError = exports.InvalidFieldTypeError = exports.UnsupportedCustomValidationError = exports.UnsupportedCustomFieldTypeError = exports.MissingRequiredCustomFieldError = void 0;
4
- /* eslint-disable max-classes-per-file */
5
- const errors_1 = require("@autofleet/errors");
6
- class MissingRequiredCustomFieldError extends errors_1.BadRequest {
7
- constructor(missingFields) {
8
- const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);
9
- super([err], null, missingFields);
10
- this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';
11
- }
12
- }
13
- exports.MissingRequiredCustomFieldError = MissingRequiredCustomFieldError;
14
- class UnsupportedCustomFieldTypeError extends errors_1.BadRequest {
15
- constructor(fieldType) {
16
- const err = new Error(`Type "${fieldType}" is not supported`);
17
- super([err], null, null);
18
- this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';
19
- }
20
- }
21
- exports.UnsupportedCustomFieldTypeError = UnsupportedCustomFieldTypeError;
22
- class UnsupportedCustomValidationError extends errors_1.BadRequest {
23
- constructor(fieldType) {
24
- const err = new Error(`Validation for "${fieldType}" is not supported`);
25
- super([err], null, null);
26
- this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';
27
- }
28
- }
29
- exports.UnsupportedCustomValidationError = UnsupportedCustomValidationError;
30
- class InvalidFieldTypeError extends errors_1.BadRequest {
31
- constructor(fieldType) {
32
- const err = new Error(`Invalid field type ${fieldType}`);
33
- super([err], null, null);
34
- this.message = 'INVALID_FIELD_TYPE';
35
- }
36
- }
37
- exports.InvalidFieldTypeError = InvalidFieldTypeError;
38
- class InvalidValueError extends errors_1.BadRequest {
39
- constructor(value, fieldDefinitionName, joiValidationError) {
40
- const formattedErrorMessage = joiValidationError.message
41
- .replace(/"/g, '')
42
- .replace('value', `'${fieldDefinitionName}'`);
43
- const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;
44
- const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;
45
- const err = new Error(invalidValueMessage);
46
- super([err], null, null);
47
- this.message = invalidValueMessage;
48
- }
49
- }
50
- exports.InvalidValueError = InvalidValueError;
51
- class InvalidEntriesError extends errors_1.BadRequest {
52
- constructor(modelId, validationErrors) {
53
- const errors = validationErrors.map((validationError) => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));
54
- super(errors, null, null);
55
- this.message = `Invalid entries on ${modelId}\n${validationErrors.map((validationError) => (`${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`)).join('\n')}`;
56
- }
57
- }
58
- exports.InvalidEntriesError = InvalidEntriesError;
59
- class MissingDefinitionError extends errors_1.BadRequest {
60
- constructor(fieldNames) {
61
- const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);
62
- super([err], null, null);
63
- this.message = 'MISSING_DEFINITION';
64
- }
65
- }
66
- exports.MissingDefinitionError = MissingDefinitionError;
1
+ import{BadRequest as e}from"@autofleet/errors";var t=class extends e{constructor(e){let t=Error(`The following custom fields are required: ${e.join(`,`)}`);super([t],void 0,e),this.message=`MISSING_REQUIRED_CUSTOM_FIELDS`}},n=class extends e{constructor(e){let t=Error(`Type "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_FIELD_TYPE`}},r=class extends e{constructor(e){let t=Error(`Validation for "${e}" is not supported`);super([t],void 0,null),this.message=`UNSUPPORTED_CUSTOM_VALIDATION_TYPE`}},i=class extends e{constructor(e){let t=Error(`Invalid field type ${e}`);super([t],void 0,null),this.message=`INVALID_FIELD_TYPE`}},a=class extends e{constructor(e,t,n){let r=`Invalid Value on field '${t}'. ${n.message.replace(/"/g,``).replace(`value`,`'${t}'`)}. received: '${typeof e==`object`?JSON.stringify(e):e}'`;super([Error(r)],void 0,null),this.message=r}},o=class extends e{constructor(e,t){let n=t.map(e=>new a(e.value,e.fieldDefinitionName,e.joiValidationError));super(n,void 0,null),this.message=`Invalid entries on ${e}\n${t.map(e=>`${e.fieldDefinitionName} - ${e.joiValidationError.message}`).join(`
2
+ `)}`}},s=class extends e{constructor(e){let t=Error(`Missing custom field definition for field ${e.join(`,`)}`);super([t],void 0,null),this.message=`MISSING_DEFINITION`}};export{o as InvalidEntriesError,i as InvalidFieldTypeError,a as InvalidValueError,s as MissingDefinitionError,t as MissingRequiredCustomFieldError,n as UnsupportedCustomFieldTypeError,r as UnsupportedCustomValidationError};
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/errors/index.ts"],"sourcesContent":["import { BadRequest } from '@autofleet/errors';\nimport type { ValidationError } from 'joi';\nimport type { EntriesValidationError } from '../types/entries';\n\nexport class MissingRequiredCustomFieldError extends BadRequest {\n constructor(missingFields: string[]) {\n const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);\n super([err], undefined, missingFields);\n this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';\n }\n}\n\nexport class UnsupportedCustomFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Type \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';\n }\n}\n\nexport class UnsupportedCustomValidationError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Validation for \"${fieldType}\" is not supported`);\n super([err], undefined, null);\n this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';\n }\n}\n\nexport class InvalidFieldTypeError extends BadRequest {\n constructor(fieldType: string) {\n const err = new Error(`Invalid field type ${fieldType}`);\n super([err], undefined, null);\n this.message = 'INVALID_FIELD_TYPE';\n }\n}\n\nexport class InvalidValueError extends BadRequest {\n constructor(value: any, fieldDefinitionName: string, joiValidationError: ValidationError) {\n const formattedErrorMessage = joiValidationError.message\n .replace(/\"/g, '')\n .replace('value', `'${fieldDefinitionName}'`);\n\n const formattedValue = typeof value === 'object' ? JSON.stringify(value) : value;\n\n const invalidValueMessage = `Invalid Value on field '${fieldDefinitionName}'. ${formattedErrorMessage}. received: '${formattedValue}'`;\n\n const err = new Error(invalidValueMessage);\n super([err], undefined, null);\n this.message = invalidValueMessage;\n }\n}\n\nexport class InvalidEntriesError extends BadRequest {\n constructor(modelId: string, validationErrors: EntriesValidationError[]) {\n const errors = validationErrors.map(validationError => new InvalidValueError(validationError.value, validationError.fieldDefinitionName, validationError.joiValidationError));\n super(errors, undefined, null);\n this.message = `Invalid entries on ${modelId}\\n${validationErrors.map(validationError => (\n `${validationError.fieldDefinitionName} - ${validationError.joiValidationError.message}`\n )).join('\\n')}`;\n }\n}\n\nexport class MissingDefinitionError extends BadRequest {\n constructor(fieldNames: string[]) {\n const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);\n super([err], undefined, null);\n this.message = 'MISSING_DEFINITION';\n }\n}\n"],"mappings":"+CAIA,IAAa,EAAb,cAAqD,CAAW,CAC9D,YAAY,EAAyB,CACnC,IAAM,EAAU,MAAM,6CAA6C,EAAc,KAAK,IAAI,GAAG,CAC7F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,EAAc,CACtC,KAAK,QAAU,mCAIN,EAAb,cAAqD,CAAW,CAC9D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,SAAS,EAAU,oBAAoB,CAC7D,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,kCAIN,EAAb,cAAsD,CAAW,CAC/D,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,mBAAmB,EAAU,oBAAoB,CACvE,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uCAIN,EAAb,cAA2C,CAAW,CACpD,YAAY,EAAmB,CAC7B,IAAM,EAAU,MAAM,sBAAsB,IAAY,CACxD,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,uBAIN,EAAb,cAAuC,CAAW,CAChD,YAAY,EAAY,EAA6B,EAAqC,CAOxF,IAAM,EAAsB,2BAA2B,EAAoB,KAN7C,EAAmB,QAC9C,QAAQ,KAAM,GAAG,CACjB,QAAQ,QAAS,IAAI,EAAoB,GAAG,CAIuD,eAF/E,OAAO,GAAU,SAAW,KAAK,UAAU,EAAM,CAAG,EAEyD,GAGpI,MAAM,CADU,MAAM,EAAoB,CAC/B,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU,IAIN,EAAb,cAAyC,CAAW,CAClD,YAAY,EAAiB,EAA4C,CACvE,IAAM,EAAS,EAAiB,IAAI,GAAmB,IAAI,EAAkB,EAAgB,MAAO,EAAgB,oBAAqB,EAAgB,mBAAmB,CAAC,CAC7K,MAAM,EAAQ,IAAA,GAAW,KAAK,CAC9B,KAAK,QAAU,sBAAsB,EAAQ,IAAI,EAAiB,IAAI,GACpE,GAAG,EAAgB,oBAAoB,KAAK,EAAgB,mBAAmB,UAC/E,CAAC,KAAK;EAAK,KAIJ,EAAb,cAA4C,CAAW,CACrD,YAAY,EAAsB,CAChC,IAAM,EAAU,MAAM,6CAA6C,EAAW,KAAK,IAAI,GAAG,CAC1F,MAAM,CAAC,EAAI,CAAE,IAAA,GAAW,KAAK,CAC7B,KAAK,QAAU"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`);let n=require(`@autofleet/zehut`),r=require(`@autofleet/events`);r=e.__toESM(r);const i=new r.default({logger:t.default,getUserId:e=>e?.user_id??(0,n.getUser)()?.id??null}),a=[`value`,`defaultValue`,`blockEditingFromUI`],o=(e,t)=>{let n=new Set(Object.keys(e));return t.every(e=>!n.has(e))?e:{...e,...Object.fromEntries(t.map(t=>[t,typeof e[t]==`boolean`?e[t].toString():e[t]]))}},s={CustomFieldDefinition:{tableName:`dim_custom_field_definition`,eventVersion:`1`},CustomFieldValue:{tableName:`dim_custom_field_value`,eventVersion:`1`},CustomFieldEntries:{tableName:`dim_custom_field_entries`,eventVersion:`1`}},c=e=>{let n=s[e.constructor.name];if(!n)return;let r=e.get();try{r=o(e.get(),a)}catch(e){t.default.error(`Failed to convert booleans in dim event payload`,e)}i.sendObject(n.tableName,n.eventVersion,r).catch(()=>null)};exports.sendDimEvent=c;
2
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":["events: Events","Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId: payload => payload?.user_id ?? getUser()?.id ?? null,\n});\n\nconst KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];\n\nconst stringifyBooleans = (savedObject: any, keysToConvert: string[]) => {\n const savedObjectKeySet = new Set(Object.keys(savedObject));\n if (keysToConvert.every(key => !savedObjectKeySet.has(key))) {\n return savedObject;\n }\n return {\n ...savedObject,\n ...Object.fromEntries(keysToConvert.map(key => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),\n };\n};\n\nconst modelTableMapping = {\n CustomFieldDefinition: {\n tableName: 'dim_custom_field_definition',\n eventVersion: '1',\n },\n CustomFieldValue: {\n tableName: 'dim_custom_field_value',\n eventVersion: '1',\n },\n CustomFieldEntries: {\n tableName: 'dim_custom_field_entries',\n eventVersion: '1',\n },\n};\n\nexport const sendDimEvent = (instance: CustomFieldDefinition | CustomFieldValue | CustomFieldEntries | CustomValidator): void => {\n const mapping = modelTableMapping[instance.constructor.name as keyof typeof modelTableMapping];\n if (!mapping) {\n return;\n }\n let objectToSend = instance.get();\n try {\n objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);\n } catch (err) {\n logger.error('Failed to convert booleans in dim event payload', err);\n }\n\n events.sendObject(\n mapping.tableName,\n mapping.eventVersion,\n objectToSend,\n ).catch(() => null);\n};\n\nexport default events;\n"],"mappings":"2KAUA,MAAMA,EAAiB,IAAIC,EAAAA,QAAO,CAChC,OAAA,EAAA,QACA,UAAW,GAAW,GAAS,UAAA,EAAA,EAAA,UAAoB,EAAE,IAAM,KAC5D,CAAC,CAEI,EAAkB,CAAC,QAAS,eAAgB,qBAAqB,CAEjE,GAAqB,EAAkB,IAA4B,CACvE,IAAM,EAAoB,IAAI,IAAI,OAAO,KAAK,EAAY,CAAC,CAI3D,OAHI,EAAc,MAAM,GAAO,CAAC,EAAkB,IAAI,EAAI,CAAC,CAClD,EAEF,CACL,GAAG,EACH,GAAG,OAAO,YAAY,EAAc,IAAI,GAAO,CAAC,EAAK,OAAO,EAAY,IAAS,UAAY,EAAY,GAAK,UAAU,CAAG,EAAY,GAAK,CAAC,CAAC,CAC/I,EAGG,EAAoB,CACxB,sBAAuB,CACrB,UAAW,8BACX,aAAc,IACf,CACD,iBAAkB,CAChB,UAAW,yBACX,aAAc,IACf,CACD,mBAAoB,CAClB,UAAW,2BACX,aAAc,IACf,CACF,CAEY,EAAgB,GAAoG,CAC/H,IAAM,EAAU,EAAkB,EAAS,YAAY,MACvD,GAAI,CAAC,EACH,OAEF,IAAI,EAAe,EAAS,KAAK,CACjC,GAAI,CACF,EAAe,EAAkB,EAAS,KAAK,CAAE,EAAgB,OAC1D,EAAK,CACZ,EAAA,QAAO,MAAM,kDAAmD,EAAI,CAGtE,EAAO,WACL,EAAQ,UACR,EAAQ,aACR,EACD,CAAC,UAAY,KAAK"}
@@ -1,54 +1,2 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.sendDimEvent = void 0;
7
- const events_1 = __importDefault(require("@autofleet/events"));
8
- const zehut_1 = require("@autofleet/zehut");
9
- const logger_1 = __importDefault(require("../utils/logger"));
10
- const events = new events_1.default({
11
- logger: logger_1.default,
12
- getUserId: (payload) => payload?.user_id ?? (0, zehut_1.getUser)()?.id ?? null,
13
- });
14
- const KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];
15
- const stringifyBooleans = (savedObject, keysToConvert) => {
16
- const savedObjectKeySet = new Set(Object.keys(savedObject));
17
- if (keysToConvert.every((key) => !savedObjectKeySet.has(key))) {
18
- return savedObject;
19
- }
20
- return {
21
- ...savedObject,
22
- ...Object.fromEntries(keysToConvert.map((key) => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),
23
- };
24
- };
25
- const modelTableMapping = {
26
- CustomFieldDefinition: {
27
- tableName: 'dim_custom_field_definition',
28
- eventVersion: '1',
29
- },
30
- CustomFieldValue: {
31
- tableName: 'dim_custom_field_value',
32
- eventVersion: '1',
33
- },
34
- CustomFieldEntries: {
35
- tableName: 'dim_custom_field_entries',
36
- eventVersion: '1',
37
- },
38
- };
39
- const sendDimEvent = (instance) => {
40
- const mapping = modelTableMapping[instance.constructor.name];
41
- if (!mapping) {
42
- return;
43
- }
44
- let objectToSend = instance.get();
45
- try {
46
- objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);
47
- }
48
- catch (err) {
49
- logger_1.default.error('Failed to convert booleans in dim event payload', err);
50
- }
51
- events.sendObject(mapping.tableName, mapping.eventVersion, objectToSend).catch(() => { });
52
- };
53
- exports.sendDimEvent = sendDimEvent;
54
- exports.default = events;
1
+ import e from"../utils/logger/index.js";import{getUser as t}from"@autofleet/zehut";import n from"@autofleet/events";const r=new n({logger:e,getUserId:e=>e?.user_id??t()?.id??null}),i=[`value`,`defaultValue`,`blockEditingFromUI`],a=(e,t)=>{let n=new Set(Object.keys(e));return t.every(e=>!n.has(e))?e:{...e,...Object.fromEntries(t.map(t=>[t,typeof e[t]==`boolean`?e[t].toString():e[t]]))}},o={CustomFieldDefinition:{tableName:`dim_custom_field_definition`,eventVersion:`1`},CustomFieldValue:{tableName:`dim_custom_field_value`,eventVersion:`1`},CustomFieldEntries:{tableName:`dim_custom_field_entries`,eventVersion:`1`}},s=t=>{let n=o[t.constructor.name];if(!n)return;let s=t.get();try{s=a(t.get(),i)}catch(t){e.error(`Failed to convert booleans in dim event payload`,t)}r.sendObject(n.tableName,n.eventVersion,s).catch(()=>null)};export{s as sendDimEvent};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["events: Events"],"sources":["../../src/events/index.ts"],"sourcesContent":["import Events from '@autofleet/events';\nimport { getUser } from '@autofleet/zehut';\nimport logger from '../utils/logger';\nimport type {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from '../models';\n\nconst events: Events = new Events({\n logger,\n getUserId: payload => payload?.user_id ?? getUser()?.id ?? null,\n});\n\nconst KEYS_TO_CONVERT = ['value', 'defaultValue', 'blockEditingFromUI'];\n\nconst stringifyBooleans = (savedObject: any, keysToConvert: string[]) => {\n const savedObjectKeySet = new Set(Object.keys(savedObject));\n if (keysToConvert.every(key => !savedObjectKeySet.has(key))) {\n return savedObject;\n }\n return {\n ...savedObject,\n ...Object.fromEntries(keysToConvert.map(key => [key, typeof savedObject[key] === 'boolean' ? savedObject[key].toString() : savedObject[key]])),\n };\n};\n\nconst modelTableMapping = {\n CustomFieldDefinition: {\n tableName: 'dim_custom_field_definition',\n eventVersion: '1',\n },\n CustomFieldValue: {\n tableName: 'dim_custom_field_value',\n eventVersion: '1',\n },\n CustomFieldEntries: {\n tableName: 'dim_custom_field_entries',\n eventVersion: '1',\n },\n};\n\nexport const sendDimEvent = (instance: CustomFieldDefinition | CustomFieldValue | CustomFieldEntries | CustomValidator): void => {\n const mapping = modelTableMapping[instance.constructor.name as keyof typeof modelTableMapping];\n if (!mapping) {\n return;\n }\n let objectToSend = instance.get();\n try {\n objectToSend = stringifyBooleans(instance.get(), KEYS_TO_CONVERT);\n } catch (err) {\n logger.error('Failed to convert booleans in dim event payload', err);\n }\n\n events.sendObject(\n mapping.tableName,\n mapping.eventVersion,\n objectToSend,\n ).catch(() => null);\n};\n\nexport default events;\n"],"mappings":"oHAUA,MAAMA,EAAiB,IAAI,EAAO,CAChC,OAAA,EACA,UAAW,GAAW,GAAS,SAAW,GAAS,EAAE,IAAM,KAC5D,CAAC,CAEI,EAAkB,CAAC,QAAS,eAAgB,qBAAqB,CAEjE,GAAqB,EAAkB,IAA4B,CACvE,IAAM,EAAoB,IAAI,IAAI,OAAO,KAAK,EAAY,CAAC,CAI3D,OAHI,EAAc,MAAM,GAAO,CAAC,EAAkB,IAAI,EAAI,CAAC,CAClD,EAEF,CACL,GAAG,EACH,GAAG,OAAO,YAAY,EAAc,IAAI,GAAO,CAAC,EAAK,OAAO,EAAY,IAAS,UAAY,EAAY,GAAK,UAAU,CAAG,EAAY,GAAK,CAAC,CAAC,CAC/I,EAGG,EAAoB,CACxB,sBAAuB,CACrB,UAAW,8BACX,aAAc,IACf,CACD,iBAAkB,CAChB,UAAW,yBACX,aAAc,IACf,CACD,mBAAoB,CAClB,UAAW,2BACX,aAAc,IACf,CACF,CAEY,EAAgB,GAAoG,CAC/H,IAAM,EAAU,EAAkB,EAAS,YAAY,MACvD,GAAI,CAAC,EACH,OAEF,IAAI,EAAe,EAAS,KAAK,CACjC,GAAI,CACF,EAAe,EAAkB,EAAS,KAAK,CAAE,EAAgB,OAC1D,EAAK,CACZ,EAAO,MAAM,kDAAmD,EAAI,CAGtE,EAAO,WACL,EAAQ,UACR,EAAQ,aACR,EACD,CAAC,UAAY,KAAK"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../repository/definition.cjs`),t=require(`../repository/value.cjs`),n=require(`../repository/entries.cjs`),r=require(`../utils/scopeAttributes.cjs`),i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n.findEntriesByModelIds(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t.findValuesByModelIds(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{}),c=(t,n,c,l={},u={useCustomFieldsEntries:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r.default(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache??=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v)),_||(_=e.findByEntityIds(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(e=>{a[e.name]===void 0&&(a[e.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};var l=c;exports.default=l;
2
+ //# sourceMappingURL=enrich.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: string | undefined"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"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"}
@@ -1,198 +1,2 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
24
- };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
- Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.getValuesGroupByInstance = exports.getCustomFieldEntriesByInstanceId = void 0;
30
- /* eslint-disable no-param-reassign */
31
- const ValueRepo = __importStar(require("../repository/value"));
32
- const DefinitionRepo = __importStar(require("../repository/definition"));
33
- const EntriesRepo = __importStar(require("../repository/entries"));
34
- const scopeAttributes_1 = __importDefault(require("../utils/scopeAttributes"));
35
- // Include all required fields for proper functioning
36
- const CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [
37
- 'id',
38
- 'name',
39
- 'entityId',
40
- 'fieldType',
41
- 'displayName',
42
- 'validation',
43
- 'entityType',
44
- 'modelType',
45
- 'required',
46
- 'disabled',
47
- 'defaultValue',
48
- ];
49
- const getCustomFieldEntriesByInstanceId = async ({ instancesIds, options, sadotOptions, }) => {
50
- if (!sadotOptions.useCustomFieldsEntries) {
51
- return {};
52
- }
53
- const customFieldEntries = await EntriesRepo.findEntriesByModelIds(instancesIds, options ?? {});
54
- const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {
55
- const { modelId, customFields } = instanceEntries?.dataValues ?? {};
56
- if (!modelId) {
57
- return undefined;
58
- }
59
- return [modelId, customFields];
60
- }).filter(Boolean));
61
- instancesIds.forEach((instanceId) => {
62
- customFieldEntriesByInstanceId[instanceId] ?? (customFieldEntriesByInstanceId[instanceId] = {});
63
- });
64
- return customFieldEntriesByInstanceId;
65
- };
66
- exports.getCustomFieldEntriesByInstanceId = getCustomFieldEntriesByInstanceId;
67
- const getValuesGroupByInstance = async ({ instancesIds, options, sadotOptions, }) => {
68
- if (sadotOptions.useCustomFieldsEntries) {
69
- return {};
70
- }
71
- const customFieldValues = await ValueRepo.findValuesByModelIds(instancesIds, options ?? {});
72
- // Group fields by modelId
73
- return customFieldValues.reduce((acc, v) => {
74
- const { modelId } = v;
75
- acc[modelId] ?? (acc[modelId] = []);
76
- acc[modelId].push(v);
77
- return acc;
78
- }, {});
79
- };
80
- exports.getValuesGroupByInstance = getValuesGroupByInstance;
81
- /**
82
- * Serialize custom fields value into the format of {[name] -> [fieldData]}
83
- */
84
- const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) => {
85
- const customFields = customFieldValues.reduce((acc, cfv) => ({
86
- ...acc,
87
- ...(customFieldDefinitionsHash[cfv.customFieldDefinitionId]
88
- && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }),
89
- }), {});
90
- return customFields;
91
- };
92
- /**
93
- * A hook to attach the custom fields when fetching a model instances.
94
- */
95
- const enrichResults = (modelType, scopeAttributes, hookType, modelOptions = {}, sadotOptions = { useCustomFieldsEntries: false }) => async (instancesOrInstance, options) => {
96
- var _a;
97
- if (options.originalAttributes?.length > 0
98
- && !options.originalAttributes?.includes?.('customFields')) {
99
- return;
100
- }
101
- const primaryKey = 'id';
102
- let instances = Array.isArray(instancesOrInstance)
103
- ? instancesOrInstance
104
- : [instancesOrInstance];
105
- instances = instances.filter(Boolean);
106
- const identifiers = (0, scopeAttributes_1.default)(instances, scopeAttributes);
107
- const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
108
- const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
109
- ...map,
110
- [identifier]: [],
111
- }), {});
112
- // Cache for definitions by model type and transaction to avoid redundant DB queries
113
- let customFieldDefinitionsPromise;
114
- let cacheKey;
115
- if (options.transaction) {
116
- // Initialize definition cache Map if not already present directly on the transaction object
117
- (_a = options.transaction).definitionCache || (_a.definitionCache = new Map());
118
- cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;
119
- customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);
120
- }
121
- if (!customFieldDefinitionsPromise) {
122
- // Fetch from database (either first time in this transaction or no transaction)
123
- customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL });
124
- options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);
125
- }
126
- const customFieldDefinitions = await customFieldDefinitionsPromise;
127
- if (customFieldDefinitions.length === 0) {
128
- // if no custom fields, we can return
129
- instances.forEach((instance) => {
130
- instance.customFields = {};
131
- });
132
- return;
133
- }
134
- if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {
135
- // if we pass useEntityIdFromInclude,
136
- // map the entity from the options to the identifierCustomFieldDefinitionsMapping
137
- modelOptions.include(identifiers).forEach(({ model }) => {
138
- customFieldDefinitions.forEach((cfd) => {
139
- const entityId = cfd[`${model.name}.entityId`];
140
- identifierCustomFieldDefinitionsMapping[entityId] = [];
141
- });
142
- });
143
- }
144
- const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
145
- ...map,
146
- [definition.id]: definition,
147
- }), {});
148
- customFieldDefinitions.forEach((cfd) => {
149
- identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
150
- });
151
- // Get the values per instates ids:
152
- const instancesIds = instances.map((i) => i[primaryKey]);
153
- // Group fields by modelId
154
- const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([
155
- (0, exports.getValuesGroupByInstance)({
156
- instancesIds,
157
- options,
158
- sadotOptions,
159
- }),
160
- (0, exports.getCustomFieldEntriesByInstanceId)({
161
- instancesIds,
162
- options,
163
- sadotOptions,
164
- }),
165
- ]);
166
- // Attach custom fields to the instances
167
- instances.forEach((instance) => {
168
- const { id } = instance;
169
- const instanceValues = valuesGroupByInstance[id];
170
- const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};
171
- const customFields = sadotOptions.useCustomFieldsEntries
172
- ? customFieldEntriesByInstanceId[id]
173
- : serializedCustomFieldsValues;
174
- scopeAttributes.forEach((attribute) => {
175
- const identifier = instance[attribute];
176
- const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];
177
- if (entityCustomFieldDefinitions?.length > 0) {
178
- entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
179
- if (customFields[customFieldDefinition.name] === undefined) {
180
- customFields[customFieldDefinition.name] = null;
181
- }
182
- });
183
- }
184
- });
185
- instance.customFields = customFields;
186
- options.attributesToRemove?.forEach?.((attribute) => {
187
- delete instance.dataValues?.[attribute];
188
- // if raw:
189
- delete instance?.[attribute];
190
- });
191
- // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged
192
- if (hookType === 'afterFind') {
193
- // changed() could be undefined, i.e in raw: true
194
- instance?.changed?.('customFields', false);
195
- }
196
- });
197
- };
198
- exports.default = enrichResults;
1
+ import{findByEntityIds as e}from"../repository/definition.js";import{findValuesByModelIds as t}from"../repository/value.js";import{findEntriesByModelIds as n}from"../repository/entries.js";import r from"../utils/scopeAttributes.js";const i=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],a=async({instancesIds:e,options:t,sadotOptions:r})=>{if(!r.useCustomFieldsEntries)return{};let i=await n(e,t??{}),a=Object.fromEntries(i.map(e=>{let{modelId:t,customFields:n}=e?.dataValues??{};if(t)return[t,n]}).filter(e=>e!==void 0));return e.forEach(e=>{a[e]??={}}),a},o=async({instancesIds:e,options:n,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await t(e,n??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),s=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var c=(t,n,c,l={},u={useCustomFieldsEntries:!1})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache??=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v)),_||(_=e(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(e=>{a[e.name]===void 0&&(a[e.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{c as default};
2
+ //# sourceMappingURL=enrich.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","DefinitionRepo.findByEntityIds"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"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"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../utils/logger/index.cjs`),t=(e,t)=>{let n=e.filter(e=>!t.includes(e));return t.includes?.(`id`)||n.push(`id`),n},n=n=>r=>{let{attributes:i}=r;if(i?.includes?.(`customFields`)){let a=t(n,i);e.default.debug(`sadot - before find hook`),a?.length>0&&(i.push(...a),r.attributesToRemove=a)}};exports.beforeFind=n;
2
+ //# sourceMappingURL=find.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"find.cjs","names":[],"sources":["../../src/hooks/find.ts"],"sourcesContent":["import type { FindOptions } from 'sequelize';\nimport logger from '../utils/logger';\n\nconst doScopeAttributesMissing = (\n scopeAttributes: string[],\n queryAttributes: (string | string[])[],\n): string[] => {\n const attributes = scopeAttributes\n .filter(attribute => !queryAttributes.includes(attribute));\n if (!queryAttributes.includes?.('id')) {\n attributes.push('id');\n }\n return attributes;\n};\n\nexport const beforeFind = (scopeAttributes: string[]) => (options: FindOptions): void => {\n const { attributes: queryAttributes } = options;\n if ((queryAttributes as string[])?.includes?.('customFields')) {\n const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes as string[]);\n logger.debug('sadot - before find hook');\n if (missingScopeAttributes?.length > 0) {\n (queryAttributes as string[]).push(...missingScopeAttributes);\n (options as any).attributesToRemove = missingScopeAttributes;\n }\n }\n};\n"],"mappings":"6CAGM,GACJ,EACA,IACa,CACb,IAAM,EAAa,EAChB,OAAO,GAAa,CAAC,EAAgB,SAAS,EAAU,CAAC,CAI5D,OAHK,EAAgB,WAAW,KAAK,EACnC,EAAW,KAAK,KAAK,CAEhB,GAGI,EAAc,GAA+B,GAA+B,CACvF,GAAM,CAAE,WAAY,GAAoB,EACxC,GAAK,GAA8B,WAAW,eAAe,CAAE,CAC7D,IAAM,EAAyB,EAAyB,EAAiB,EAA4B,CACrG,EAAA,QAAO,MAAM,2BAA2B,CACpC,GAAwB,OAAS,IAClC,EAA6B,KAAK,GAAG,EAAuB,CAC5D,EAAgB,mBAAqB"}
@@ -1,29 +1,2 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.beforeFind = void 0;
7
- /* eslint-disable no-param-reassign */
8
- const logger_1 = __importDefault(require("../utils/logger"));
9
- const doScopeAttributesMissing = (scopeAttributes, queryAttributes) => {
10
- const attributes = scopeAttributes
11
- .filter((attribute) => !queryAttributes.includes(attribute));
12
- if (!queryAttributes.includes?.('id')) {
13
- attributes.push('id');
14
- }
15
- return attributes;
16
- };
17
- // eslint-disable-next-line import/prefer-default-export
18
- const beforeFind = (scopeAttributes) => (options) => {
19
- const { attributes: queryAttributes } = options;
20
- if (queryAttributes?.includes?.('customFields')) {
21
- const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes);
22
- logger_1.default.debug('sadot - before find hook');
23
- if (missingScopeAttributes?.length > 0) {
24
- queryAttributes.push(...missingScopeAttributes);
25
- options.attributesToRemove = missingScopeAttributes;
26
- }
27
- }
28
- };
29
- exports.beforeFind = beforeFind;
1
+ import e from"../utils/logger/index.js";const t=(e,t)=>{let n=e.filter(e=>!t.includes(e));return t.includes?.(`id`)||n.push(`id`),n},n=n=>r=>{let{attributes:i}=r;if(i?.includes?.(`customFields`)){let a=t(n,i);e.debug(`sadot - before find hook`),a?.length>0&&(i.push(...a),r.attributesToRemove=a)}};export{n as beforeFind};
2
+ //# sourceMappingURL=find.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"find.js","names":[],"sources":["../../src/hooks/find.ts"],"sourcesContent":["import type { FindOptions } from 'sequelize';\nimport logger from '../utils/logger';\n\nconst doScopeAttributesMissing = (\n scopeAttributes: string[],\n queryAttributes: (string | string[])[],\n): string[] => {\n const attributes = scopeAttributes\n .filter(attribute => !queryAttributes.includes(attribute));\n if (!queryAttributes.includes?.('id')) {\n attributes.push('id');\n }\n return attributes;\n};\n\nexport const beforeFind = (scopeAttributes: string[]) => (options: FindOptions): void => {\n const { attributes: queryAttributes } = options;\n if ((queryAttributes as string[])?.includes?.('customFields')) {\n const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes as string[]);\n logger.debug('sadot - before find hook');\n if (missingScopeAttributes?.length > 0) {\n (queryAttributes as string[]).push(...missingScopeAttributes);\n (options as any).attributesToRemove = missingScopeAttributes;\n }\n }\n};\n"],"mappings":"wCAGA,MAAM,GACJ,EACA,IACa,CACb,IAAM,EAAa,EAChB,OAAO,GAAa,CAAC,EAAgB,SAAS,EAAU,CAAC,CAI5D,OAHK,EAAgB,WAAW,KAAK,EACnC,EAAW,KAAK,KAAK,CAEhB,GAGI,EAAc,GAA+B,GAA+B,CACvF,GAAM,CAAE,WAAY,GAAoB,EACxC,GAAK,GAA8B,WAAW,eAAe,CAAE,CAC7D,IAAM,EAAyB,EAAyB,EAAiB,EAA4B,CACrG,EAAO,MAAM,2BAA2B,CACpC,GAAwB,OAAS,IAClC,EAA6B,KAAK,GAAG,EAAuB,CAC5D,EAAgB,mBAAqB"}