@autofleet/sadot 1.2.0 → 1.2.1-beta
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.
- package/.nvmrc +1 -0
- package/dist/api/index.d.ts +3 -0
- package/dist/api/index.js +12 -2
- package/dist/api/v1/definition/index.d.ts +3 -0
- package/dist/api/v1/definition/index.js +116 -2
- package/dist/api/v1/definition/validations.d.ts +2 -0
- package/dist/api/v1/definition/validations.js +77 -2
- package/dist/api/v1/errors.d.ts +4 -0
- package/dist/api/v1/errors.js +12 -2
- package/dist/api/v1/index.d.ts +3 -0
- package/dist/api/v1/index.js +13 -2
- package/dist/api/v1/validator/index.d.ts +3 -0
- package/dist/api/v1/validator/index.js +143 -2
- package/dist/api/v1/validator/validations.d.ts +6 -23
- package/dist/api/v1/validator/validations.js +38 -2
- package/dist/errors/index.d.ts +24 -0
- package/dist/errors/index.js +66 -3
- package/dist/events/index.d.ts +5 -0
- package/dist/events/index.js +54 -2
- package/dist/hooks/create.d.ts +10 -0
- package/dist/hooks/create.js +95 -0
- package/dist/hooks/enrich.d.ts +25 -0
- package/dist/hooks/enrich.js +198 -2
- package/dist/hooks/find.d.ts +1 -0
- package/dist/hooks/find.js +29 -2
- package/dist/hooks/hooks.d.ts +17 -0
- package/dist/hooks/hooks.js +388 -2
- package/dist/hooks/index.d.ts +5 -0
- package/dist/hooks/index.js +17 -1
- package/dist/hooks/update.d.ts +10 -0
- package/dist/hooks/update.js +49 -0
- package/dist/hooks/utils/updateInstanceValues.d.ts +15 -0
- package/dist/hooks/utils/updateInstanceValues.js +50 -2
- package/dist/hooks/workaround.d.ts +10 -0
- package/dist/hooks/workaround.js +37 -0
- package/dist/index.d.ts +12 -22
- package/dist/index.js +67 -2
- package/dist/models/CustomFieldDefinition.d.ts +23 -31
- package/dist/models/CustomFieldDefinition.js +192 -2
- package/dist/models/CustomFieldEntries.d.ts +13 -14
- package/dist/models/CustomFieldEntries.js +123 -2
- package/dist/models/CustomFieldValue.d.ts +14 -19
- package/dist/models/CustomFieldValue.js +151 -2
- package/dist/models/CustomValidator.d.ts +15 -17
- package/dist/models/CustomValidator.js +98 -2
- package/dist/models/index.d.ts +18 -7
- package/dist/models/index.js +131 -2
- package/dist/models/tests/AssociatedTestModel.d.ts +12 -0
- package/dist/models/tests/AssociatedTestModel.js +71 -2
- package/dist/models/tests/TestModel.d.ts +12 -0
- package/dist/models/tests/TestModel.js +69 -2
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +10 -0
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +53 -2
- package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +13 -0
- package/dist/models/tests/contextAwareModels/ContextTestModel.js +47 -2
- package/dist/repository/definition.d.ts +36 -0
- package/dist/repository/definition.js +121 -2
- package/dist/repository/entries.d.ts +13 -0
- package/dist/repository/entries.js +92 -2
- package/dist/repository/utils/formatValues.d.ts +3 -0
- package/dist/repository/utils/formatValues.js +16 -2
- package/dist/repository/validator.d.ts +27 -0
- package/dist/repository/validator.js +69 -2
- package/dist/repository/value.d.ts +28 -0
- package/dist/repository/value.js +124 -2
- package/dist/scopes/filter.d.ts +29 -22
- package/dist/scopes/filter.js +75 -2
- package/dist/scopes/helpers/filter.helpers.d.ts +40 -15
- package/dist/scopes/helpers/filter.helpers.js +183 -25
- package/dist/scopes/index.d.ts +2 -0
- package/dist/scopes/index.js +6 -1
- package/dist/tests/api/test-api.d.ts +2 -0
- package/dist/tests/api/test-api.js +38 -0
- package/dist/tests/functional/searching/index.d.ts +8 -0
- package/dist/tests/functional/searching/index.js +44 -0
- package/dist/tests/helpers/commonHooks.d.ts +6 -0
- package/dist/tests/helpers/commonHooks.js +62 -0
- package/dist/tests/helpers/database-config.d.ts +16 -0
- package/dist/tests/helpers/database-config.js +17 -0
- package/dist/tests/helpers/index.d.ts +7 -0
- package/dist/tests/helpers/index.js +33 -0
- package/dist/tests/mocks/definition.mock.d.ts +48 -0
- package/dist/tests/mocks/definition.mock.js +78 -0
- package/dist/tests/mocks/events.mock.d.ts +4 -0
- package/dist/tests/mocks/events.mock.js +21 -0
- package/dist/tests/mocks/testModel.d.ts +12 -0
- package/dist/tests/mocks/testModel.js +35 -0
- package/dist/types/definition/index.d.ts +25 -0
- package/dist/types/definition/index.js +2 -0
- package/dist/types/entries/index.d.ts +25 -0
- package/dist/types/entries/index.js +2 -0
- package/dist/types/index.d.ts +46 -48
- package/dist/types/index.js +2 -0
- package/dist/types/value/index.d.ts +15 -0
- package/dist/types/value/index.js +2 -0
- package/dist/utils/constants/index.d.ts +17 -20
- package/dist/utils/constants/index.js +22 -2
- package/dist/utils/db/index.d.ts +4 -0
- package/dist/utils/db/index.js +24 -2
- package/dist/utils/helpers/index.d.ts +23 -28
- package/dist/utils/helpers/index.js +40 -2
- package/dist/utils/init.d.ts +7 -0
- package/dist/utils/init.js +112 -2
- package/dist/utils/logger/index.d.ts +3 -0
- package/dist/utils/logger/index.js +42 -2
- package/dist/utils/scopeAttributes.d.ts +2 -0
- package/dist/utils/scopeAttributes.js +11 -2
- package/dist/utils/validations/index.d.ts +8 -0
- package/dist/utils/validations/index.js +41 -2
- package/dist/utils/validations/schema/custom-fields.d.ts +2 -6
- package/dist/utils/validations/schema/custom-fields.js +9 -2
- package/dist/utils/validations/schema/validator-schema.d.ts +9 -0
- package/dist/utils/validations/schema/validator-schema.js +95 -2
- package/dist/utils/validations/type.d.ts +15 -0
- package/dist/utils/validations/type.js +2 -0
- package/dist/utils/validations/validators/index.d.ts +14 -0
- package/dist/utils/validations/validators/index.js +40 -2
- package/dist/utils/validations/validators/select.validator.d.ts +5 -0
- package/dist/utils/validations/validators/select.validator.js +12 -2
- package/dist/utils/validations/validators/status.validator.d.ts +12 -0
- package/dist/utils/validations/validators/status.validator.js +15 -2
- package/package.json +39 -40
- package/src/api/index.ts +10 -0
- package/src/api/v1/definition/index.ts +104 -0
- package/src/api/v1/definition/validations.ts +75 -0
- package/src/api/v1/errors.ts +13 -0
- package/src/api/v1/index.ts +11 -0
- package/src/api/v1/validator/index.ts +141 -0
- package/src/api/v1/validator/validations.ts +39 -0
- package/src/errors/index.ts +70 -0
- package/src/events/index.ts +63 -0
- package/src/hooks/create.ts +81 -0
- package/src/hooks/enrich.ts +255 -0
- package/src/hooks/find.ts +27 -0
- package/src/hooks/hooks.ts +464 -0
- package/src/hooks/index.ts +20 -0
- package/src/hooks/update.ts +55 -0
- package/src/hooks/utils/updateInstanceValues.ts +63 -0
- package/src/hooks/workaround.ts +47 -0
- package/src/index.ts +52 -0
- package/src/models/CustomFieldDefinition.ts +162 -0
- package/src/models/CustomFieldEntries.ts +81 -0
- package/src/models/CustomFieldValue.ts +118 -0
- package/src/models/CustomValidator.ts +78 -0
- package/src/models/index.ts +165 -0
- package/src/models/tests/AssociatedTestModel.ts +57 -0
- package/src/models/tests/TestModel.ts +54 -0
- package/src/models/tests/contextAwareModels/ContextAwareTestModel.ts +43 -0
- package/src/models/tests/contextAwareModels/ContextTestModel.ts +38 -0
- package/src/repository/definition.ts +175 -0
- package/src/repository/entries.ts +88 -0
- package/src/repository/utils/formatValues.ts +14 -0
- package/src/repository/validator.ts +116 -0
- package/src/repository/value.ts +116 -0
- package/src/scopes/filter.ts +100 -0
- package/src/scopes/helpers/filter.helpers.ts +227 -0
- package/src/scopes/index.ts +6 -0
- package/src/tests/api/test-api.ts +40 -0
- package/src/tests/functional/searching/index.ts +39 -0
- package/src/tests/helpers/commonHooks.ts +43 -0
- package/src/tests/helpers/database-config.ts +15 -0
- package/src/tests/helpers/index.ts +35 -0
- package/src/tests/mocks/definition.mock.ts +84 -0
- package/src/tests/mocks/events.mock.ts +21 -0
- package/src/tests/mocks/testModel.ts +37 -0
- package/src/types/definition/index.ts +24 -0
- package/src/types/entries/index.ts +27 -0
- package/src/types/index.ts +52 -0
- package/src/types/value/index.ts +14 -0
- package/src/utils/constants/index.ts +25 -0
- package/src/utils/db/index.ts +21 -0
- package/src/utils/helpers/index.ts +66 -0
- package/src/utils/init.ts +122 -0
- package/src/utils/logger/index.ts +14 -0
- package/src/utils/scopeAttributes.ts +12 -0
- package/src/utils/validations/index.ts +46 -0
- package/src/utils/validations/schema/README.md +93 -0
- package/src/utils/validations/schema/custom-fields.ts +8 -0
- package/src/utils/validations/schema/validator-schema.ts +106 -0
- package/src/utils/validations/type.ts +20 -0
- package/src/utils/validations/validators/index.ts +38 -0
- package/src/utils/validations/validators/select.validator.ts +12 -0
- package/src/utils/validations/validators/status.validator.ts +22 -0
- package/tsconfig.build.json +7 -0
- package/tsconfig.json +16 -0
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs +0 -1
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js +0 -1
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs +0 -1
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js +0 -1
- package/dist/_virtual/rolldown_runtime.cjs +0 -1
- package/dist/api/index.cjs +0 -2
- package/dist/api/index.cjs.map +0 -1
- package/dist/api/index.js.map +0 -1
- package/dist/api/v1/definition/index.cjs +0 -2
- package/dist/api/v1/definition/index.cjs.map +0 -1
- package/dist/api/v1/definition/index.js.map +0 -1
- package/dist/api/v1/definition/validations.cjs +0 -2
- package/dist/api/v1/definition/validations.cjs.map +0 -1
- package/dist/api/v1/definition/validations.js.map +0 -1
- package/dist/api/v1/errors.cjs +0 -2
- package/dist/api/v1/errors.cjs.map +0 -1
- package/dist/api/v1/errors.js.map +0 -1
- package/dist/api/v1/index.cjs +0 -2
- package/dist/api/v1/index.cjs.map +0 -1
- package/dist/api/v1/index.js.map +0 -1
- package/dist/api/v1/validator/index.cjs +0 -2
- package/dist/api/v1/validator/index.cjs.map +0 -1
- package/dist/api/v1/validator/index.js.map +0 -1
- package/dist/api/v1/validator/validations.cjs +0 -2
- package/dist/api/v1/validator/validations.cjs.map +0 -1
- package/dist/api/v1/validator/validations.d.cts +0 -23
- package/dist/api/v1/validator/validations.js.map +0 -1
- package/dist/errors/index.cjs +0 -3
- package/dist/errors/index.cjs.map +0 -1
- package/dist/errors/index.js.map +0 -1
- package/dist/events/index.cjs +0 -2
- package/dist/events/index.cjs.map +0 -1
- package/dist/events/index.js.map +0 -1
- package/dist/hooks/enrich.cjs +0 -2
- package/dist/hooks/enrich.cjs.map +0 -1
- package/dist/hooks/enrich.js.map +0 -1
- package/dist/hooks/find.cjs +0 -2
- package/dist/hooks/find.cjs.map +0 -1
- package/dist/hooks/find.js.map +0 -1
- package/dist/hooks/hooks.cjs +0 -2
- package/dist/hooks/hooks.cjs.map +0 -1
- package/dist/hooks/hooks.js.map +0 -1
- package/dist/hooks/index.cjs +0 -1
- package/dist/hooks/utils/updateInstanceValues.cjs +0 -2
- package/dist/hooks/utils/updateInstanceValues.cjs.map +0 -1
- package/dist/hooks/utils/updateInstanceValues.js.map +0 -1
- package/dist/index.cjs +0 -2
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -23
- package/dist/index.js.map +0 -1
- package/dist/models/CustomFieldDefinition.cjs +0 -2
- package/dist/models/CustomFieldDefinition.cjs.map +0 -1
- package/dist/models/CustomFieldDefinition.d.cts +0 -33
- package/dist/models/CustomFieldDefinition.js.map +0 -1
- package/dist/models/CustomFieldEntries.cjs +0 -2
- package/dist/models/CustomFieldEntries.cjs.map +0 -1
- package/dist/models/CustomFieldEntries.d.cts +0 -16
- package/dist/models/CustomFieldEntries.js.map +0 -1
- package/dist/models/CustomFieldModelTypeMap.cjs +0 -2
- package/dist/models/CustomFieldModelTypeMap.cjs.map +0 -1
- package/dist/models/CustomFieldModelTypeMap.d.cts +0 -15
- package/dist/models/CustomFieldModelTypeMap.d.ts +0 -15
- package/dist/models/CustomFieldModelTypeMap.js +0 -2
- package/dist/models/CustomFieldModelTypeMap.js.map +0 -1
- package/dist/models/CustomFieldValue.cjs +0 -2
- package/dist/models/CustomFieldValue.cjs.map +0 -1
- package/dist/models/CustomFieldValue.d.cts +0 -21
- package/dist/models/CustomFieldValue.js.map +0 -1
- package/dist/models/CustomValidator.cjs +0 -2
- package/dist/models/CustomValidator.cjs.map +0 -1
- package/dist/models/CustomValidator.d.cts +0 -19
- package/dist/models/CustomValidator.js.map +0 -1
- package/dist/models/index.cjs +0 -2
- package/dist/models/index.cjs.map +0 -1
- package/dist/models/index.d.cts +0 -7
- package/dist/models/index.js.map +0 -1
- package/dist/models/tests/AssociatedTestModel.cjs +0 -2
- package/dist/models/tests/AssociatedTestModel.cjs.map +0 -1
- package/dist/models/tests/AssociatedTestModel.js.map +0 -1
- package/dist/models/tests/TestModel.cjs +0 -2
- package/dist/models/tests/TestModel.cjs.map +0 -1
- package/dist/models/tests/TestModel.js.map +0 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +0 -2
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +0 -1
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +0 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +0 -2
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +0 -1
- package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +0 -1
- package/dist/repository/definition.cjs +0 -2
- package/dist/repository/definition.cjs.map +0 -1
- package/dist/repository/definition.js.map +0 -1
- package/dist/repository/entries.cjs +0 -2
- package/dist/repository/entries.cjs.map +0 -1
- package/dist/repository/entries.js.map +0 -1
- package/dist/repository/utils/formatValues.cjs +0 -2
- package/dist/repository/utils/formatValues.cjs.map +0 -1
- package/dist/repository/utils/formatValues.js.map +0 -1
- package/dist/repository/validator.cjs +0 -2
- package/dist/repository/validator.cjs.map +0 -1
- package/dist/repository/validator.js.map +0 -1
- package/dist/repository/value.cjs +0 -2
- package/dist/repository/value.cjs.map +0 -1
- package/dist/repository/value.js.map +0 -1
- package/dist/scopes/filter.cjs +0 -2
- package/dist/scopes/filter.cjs.map +0 -1
- package/dist/scopes/filter.d.cts +0 -23
- package/dist/scopes/filter.js.map +0 -1
- package/dist/scopes/helpers/filter.helpers.cjs +0 -46
- package/dist/scopes/helpers/filter.helpers.cjs.map +0 -1
- package/dist/scopes/helpers/filter.helpers.d.cts +0 -17
- package/dist/scopes/helpers/filter.helpers.js.map +0 -1
- package/dist/scopes/index.cjs +0 -1
- package/dist/types/index.d.cts +0 -48
- package/dist/utils/constants/index.cjs +0 -2
- package/dist/utils/constants/index.cjs.map +0 -1
- package/dist/utils/constants/index.d.cts +0 -22
- package/dist/utils/constants/index.js.map +0 -1
- package/dist/utils/db/index.cjs +0 -2
- package/dist/utils/db/index.cjs.map +0 -1
- package/dist/utils/db/index.js.map +0 -1
- package/dist/utils/helpers/index.cjs +0 -2
- package/dist/utils/helpers/index.cjs.map +0 -1
- package/dist/utils/helpers/index.d.cts +0 -31
- package/dist/utils/helpers/index.js.map +0 -1
- package/dist/utils/init.cjs +0 -2
- package/dist/utils/init.cjs.map +0 -1
- package/dist/utils/init.js.map +0 -1
- package/dist/utils/logger/index.cjs +0 -2
- package/dist/utils/logger/index.cjs.map +0 -1
- package/dist/utils/logger/index.js.map +0 -1
- package/dist/utils/scopeAttributes.cjs +0 -2
- package/dist/utils/scopeAttributes.cjs.map +0 -1
- package/dist/utils/scopeAttributes.js.map +0 -1
- package/dist/utils/validations/index.cjs +0 -2
- package/dist/utils/validations/index.cjs.map +0 -1
- package/dist/utils/validations/index.js.map +0 -1
- package/dist/utils/validations/schema/custom-fields.cjs +0 -2
- package/dist/utils/validations/schema/custom-fields.cjs.map +0 -1
- package/dist/utils/validations/schema/custom-fields.d.cts +0 -7
- package/dist/utils/validations/schema/custom-fields.js.map +0 -1
- package/dist/utils/validations/schema/validator-schema.cjs +0 -2
- package/dist/utils/validations/schema/validator-schema.cjs.map +0 -1
- package/dist/utils/validations/schema/validator-schema.js.map +0 -1
- package/dist/utils/validations/validators/index.cjs +0 -2
- package/dist/utils/validations/validators/index.cjs.map +0 -1
- package/dist/utils/validations/validators/index.js.map +0 -1
- package/dist/utils/validations/validators/select.validator.cjs +0 -2
- package/dist/utils/validations/validators/select.validator.cjs.map +0 -1
- package/dist/utils/validations/validators/select.validator.js.map +0 -1
- package/dist/utils/validations/validators/status.validator.cjs +0 -2
- package/dist/utils/validations/validators/status.validator.cjs.map +0 -1
- package/dist/utils/validations/validators/status.validator.js.map +0 -1
package/dist/api/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","v1"],"sources":["../../src/api/index.ts"],"sourcesContent":["// export the api object\nimport { Router } from '@autofleet/node-common';\nimport v1 from './v1';\nimport logger from '../utils/logger';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\n\nrouter.use('/v1', v1);\n\nexport default router;\n"],"mappings":"qHAKA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CAE5D,EAAO,IAAI,MAAOC,EAAG,CAErB,IAAA,EAAe"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/logger/index.cjs`),n=require(`../../../repository/definition.cjs`),r=require(`../errors.cjs`),i=require(`./validations.cjs`);let a=require(`@autofleet/errors`),o=require(`@autofleet/node-common`);const s=(0,o.Router)({logger:t.default}),c=`CustomFieldDefinition`,l=e=>e.replace(/(^\w|-\w)/g,e=>e.replace(/-/,``).toUpperCase());s.post(`/`,async(e,a)=>{let{modelName:o}=e.params,s=l(o);try{let t=await i.validateCustomFieldDefinitionCreation(e.body),r=await n.create({...t,modelType:s});return a.status(201).json(r)}catch(e){return t.default.error(`Failed to create custom field definition`,e),r.default(e,a,{logger:t.default,message:`Error in create ${c} request`})}}),s.get(`/:customFieldDefinitionId`,async(e,i)=>{let{customFieldDefinitionId:o}=e.params;try{let e=await n.findById(o);if(!e)throw new a.ResourceNotFoundError;return i.json(e)}catch(e){return t.default.error(`Failed to fetch custom field definition`,e),r.default(e,i,{logger:t.default,message:`Error in get ${c} request`})}}),s.get(`/`,async(e,i)=>{let{params:{modelName:a},query:{entityIds:o,modelTypeId:s}}=e,u=l(a);try{if(s){let e=await n.findByModelTypeId(s,{withDisabled:!0,modelType:u});return i.json(e)}let e={modelType:u,...o&&o.length>0&&{entityId:o}},t=await n.findAll(e,{withDisabled:!0,enrichWithModelTypeIds:!0});return i.json(t)}catch(e){return t.default.error(`Failed to fetch custom field definitions`,e),r.default(e,i,{logger:t.default,message:`Error in get all ${c} request`})}}),s.patch(`/:customFieldDefinitionId`,async(e,o)=>{let{customFieldDefinitionId:s,modelName:u}=e.params,d=l(u);try{let t=await i.validateCustomFieldDefinitionUpdate(e.body);if(!await n.findByWhere({id:s,modelType:d}))throw new a.ResourceNotFoundError;let r=await n.update(s,{...t,modelType:d});return o.status(200).json(r)}catch(e){return t.default.error(`Failed to patch custom field definition`,e),r.default(e,o,{logger:t.default,message:`Error in update ${c} request`})}});var u=s;exports.default=u;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","validateCustomFieldDefinitionCreation","handleError","ResourceNotFoundError","customFieldDefinitions","validatedPayload: UpdateCustomFieldDefinition","validateCustomFieldDefinitionUpdate"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, { withDisabled: true, modelType });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"wRASA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMC,EAAgD,MAAMC,EAAAA,sCAAsC,EAAI,KAAK,CAErG,EAAwB,MAAA,EAAA,OAA4B,CACxD,GAAG,EACH,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAAoF,4BAA6B,MAAO,EAAK,IAAQ,CAC1I,GAAM,CAAE,2BAA4B,EAAI,OACxC,GAAI,CACF,IAAM,EAAwB,MAAA,EAAA,SAA8B,EAAw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CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validatedPayload: CreateCustomFieldDefinition","DefinitionRepo.create","handleError","DefinitionRepo.findById","customFieldDefinitions","DefinitionRepo.findByModelTypeId","DefinitionRepo.findAll","validatedPayload: UpdateCustomFieldDefinition","DefinitionRepo.findByWhere","DefinitionRepo.update"],"sources":["../../../../src/api/v1/definition/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport handleError from '../errors';\nimport * as DefinitionRepo from '../../../repository/definition';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\nimport { validateCustomFieldDefinitionCreation, validateCustomFieldDefinitionUpdate } from './validations';\nimport logger from '../../../utils/logger';\nimport type { CustomFieldDefinition } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomFieldDefinition';\n\nconst toPascalCase = (str: string): string => str.replace(/(^\\w|-\\w)/g, subStr => subStr.replace(/-/, '').toUpperCase());\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: CreateCustomFieldDefinition = await validateCustomFieldDefinitionCreation(req.body);\n\n const customFieldDefinition = await DefinitionRepo.create({\n ...validatedPayload,\n modelType,\n });\n return res.status(201).json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to create custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId } = req.params;\n try {\n const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n return res.json(customFieldDefinition);\n } catch (err) {\n logger.error('Failed to fetch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<{ modelName: string; }, CustomFieldDefinition[], never, { entityIds?: string[]; modelTypeId?: string; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds, modelTypeId } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n // If modelTypeId is provided, get definitions applicable to that specific type instance\n if (modelTypeId) {\n const customFieldDefinitions = await DefinitionRepo.findByModelTypeId(modelTypeId, { withDisabled: true, modelType });\n return res.json(customFieldDefinitions);\n }\n\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, enrichWithModelTypeIds: true });\n return res.json(customFieldDefinitions);\n } catch (err) {\n logger.error('Failed to fetch custom field definitions', err);\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; customFieldDefinitionId: string; }, CustomFieldDefinition>('/:customFieldDefinitionId', async (req, res) => {\n const { customFieldDefinitionId, modelName } = req.params;\n const modelType = toPascalCase(modelName);\n try {\n const validatedPayload: UpdateCustomFieldDefinition = await validateCustomFieldDefinitionUpdate(req.body);\n\n const customFieldDefinition = await DefinitionRepo.findByWhere({\n id: customFieldDefinitionId,\n modelType,\n });\n\n if (!customFieldDefinition) {\n throw new ResourceNotFoundError();\n }\n\n const updatedCustomFieldDefinition = await DefinitionRepo.update(\n customFieldDefinitionId,\n { ...validatedPayload, modelType },\n );\n\n return res.status(200).json(updatedCustomFieldDefinition);\n } catch (err) {\n logger.error('Failed to patch custom field definition', err);\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"gbASA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,wBAET,EAAgB,GAAwB,EAAI,QAAQ,aAAc,GAAU,EAAO,QAAQ,IAAK,GAAG,CAAC,aAAa,CAAC,CAKxH,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OACpB,EAAY,EAAa,EAAU,CACzC,GAAI,CAGF,IAAM,EAAwB,MAAME,EAAsB,CACxD,GAHoD,MAAM,EAAsC,EAAI,KAAK,CAIzG,YACD,CAAC,CACF,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAAsB,OAC3C,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDC,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAAoF,4BAA6B,MAAO,EAAK,IAAQ,CAC1I,GAAM,CAAE,2BAA4B,EAAI,OACxC,GAAI,CACF,IAAM,EAAwB,MAAMC,EAAwB,EAAwB,CAEpF,GAAI,CAAC,EACH,MAAM,IAAI,EAGZ,OAAO,EAAI,KAAK,EAAsB,OAC/B,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,gBAAgB,EAAO,UAAW,CAAC,GAE9F,CAKF,EAAO,IAA6G,IAAK,MAAO,EAAK,IAAQ,CAC3I,GAAM,CAAE,OAAQ,CAAE,aAAa,MAAO,CAAE,YAAW,gBAAkB,EAE/D,EAAY,EAAa,EAAU,CACzC,GAAI,CAEF,GAAI,EAAa,CACf,IAAME,EAAyB,MAAMC,EAAiC,EAAa,CAAE,aAAc,GAAM,YAAW,CAAC,CACrH,OAAO,EAAI,KAAKD,EAAuB,CAOzC,IAAM,EAAyB,MAAME,EAJvB,CACZ,YACA,GAAI,GAAa,EAAU,OAAS,GAAK,CAAE,SAAU,EAAW,CACjE,CACkE,CAAE,aAAc,GAAM,uBAAwB,GAAM,CAAC,CACxH,OAAO,EAAI,KAAK,EAAuB,OAChC,EAAK,CAEZ,OADA,EAAO,MAAM,2CAA4C,EAAI,CACtDJ,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,MAAsF,4BAA6B,MAAO,EAAK,IAAQ,CAC5I,GAAM,CAAE,0BAAyB,aAAc,EAAI,OAC7C,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAMK,EAAgD,MAAM,EAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAMC,EAA2B,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAI,EAGZ,IAAM,EAA+B,MAAMC,EACzC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,CAAC,KAAK,EAA6B,OAClD,EAAK,CAEZ,OADA,EAAO,MAAM,0CAA2C,EAAI,CACrDP,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/constants/index.cjs`);let n=require(`joi`);n=e.__toESM(n);const r=n.default.object({name:n.default.string().required(),type:n.default.string(),size:n.default.string(),addedBy:n.default.string().uuid()}),i=n.default.object({value:n.default.string().required(),color:n.default.string().required()}),a=n.default.when(`fieldType`,{is:t.CustomFieldDefinitionType.SELECT,then:n.default.array().required().items(n.default.string()).min(1).unique(),otherwise:n.default.when(`fieldType`,{is:t.CustomFieldDefinitionType.STATUS,then:n.default.array().required().items(i).min(1).unique(`value`),otherwise:n.default.forbidden()})}),o=n.default.when(`fieldType`,{switch:[{is:t.CustomFieldDefinitionType.BOOLEAN,then:n.default.boolean().allow(null)},{is:t.CustomFieldDefinitionType.DATE,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.DATETIME,then:n.default.date().allow(null)},{is:t.CustomFieldDefinitionType.FILE,then:n.default.array().items(r).allow(null)},{is:t.CustomFieldDefinitionType.IMAGE,then:n.default.array().items(n.default.string().uri()).allow(null)},{is:t.CustomFieldDefinitionType.NUMBER,then:n.default.number().allow(null)},{is:t.CustomFieldDefinitionType.SELECT,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.STATUS,then:n.default.string().allow(null)},{is:t.CustomFieldDefinitionType.TEXT,then:n.default.string().allow(null)}]}),s=n.default.object({name:n.default.string().required(),displayName:n.default.string().required(),validation:a,defaultValue:o,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)).required(),entityId:n.default.string().guid().required(),entityType:n.default.string().required(),description:n.default.string(),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean(),modelTypeIds:n.default.array().items(n.default.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),c=n.default.object({displayName:n.default.string(),validation:a,defaultValue:o,fieldType:n.default.string().valid(...Object.values(t.CustomFieldDefinitionType)),description:n.default.string().allow(null),required:n.default.boolean(),disabled:n.default.boolean(),blockEditingFromUI:n.default.boolean(),modelTypeIds:n.default.array().items(n.default.string().guid())}).oxor(`required`,`blockEditingFromUI`,{isPresent:e=>e===!0}),l=e=>s.validateAsync(e,{abortEarly:!1}),u=e=>c.validateAsync(e,{abortEarly:!1});exports.validateCustomFieldDefinitionCreation=l,exports.validateCustomFieldDefinitionUpdate=u;
|
|
2
|
-
//# sourceMappingURL=validations.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validations.cjs","names":["Joi","CustomFieldDefinitionType"],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"8IAIA,MAAM,EAAuBA,EAAAA,QAAI,OAAO,CACtC,KAAMA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC7B,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,QAASA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyBA,EAAAA,QAAI,OAAO,CACxC,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC9B,MAAOA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmBA,EAAAA,QAAI,KAAK,YAAa,CAC7C,GAAIC,EAAAA,0BAA0B,OAC9B,KAAMD,EAAAA,QAAI,OAAO,CAAC,UAAU,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAA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,EAAS,CAAE,WAAY,GAAO,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validations.js","names":[],"sources":["../../../../src/api/v1/definition/validations.ts"],"sourcesContent":["import Joi from 'joi';\nimport { CustomFieldDefinitionType } from '../../../utils/constants';\nimport type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../../../types/definition';\n\nconst FileValidationSchema = Joi.object({\n name: Joi.string().required(),\n type: Joi.string(),\n size: Joi.string(),\n addedBy: Joi.string().uuid(),\n});\nconst statusValidationObject = Joi.object({\n value: Joi.string().required(),\n color: Joi.string().required(),\n});\n/**\n * Schema for the validation of custom field definition\n * The only custom validation is for\n * {@link CustomFieldDefinitionType.SELECT SELECT}\n * and\n * {@link CustomFieldDefinitionType.STATUS STATUS}\n * field types.\n * The rest of the field types are validated by Joi\n */\nconst ValidationSchema = Joi.when('fieldType', {\n is: CustomFieldDefinitionType.SELECT,\n then: Joi.array().required().items(Joi.string()).min(1).unique(),\n otherwise: Joi.when('fieldType', {\n is: CustomFieldDefinitionType.STATUS,\n then: Joi.array().required().items(statusValidationObject).min(1).unique('value'),\n otherwise: Joi.forbidden(),\n }),\n});\n\nconst DefaultValueSchema = Joi.when('fieldType', {\n switch: [\n { is: CustomFieldDefinitionType.BOOLEAN, then: Joi.boolean().allow(null) },\n { is: CustomFieldDefinitionType.DATE, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.DATETIME, then: Joi.date().allow(null) },\n { is: CustomFieldDefinitionType.FILE, then: Joi.array().items(FileValidationSchema).allow(null) },\n { is: CustomFieldDefinitionType.IMAGE, then: Joi.array().items(Joi.string().uri()).allow(null) },\n { is: CustomFieldDefinitionType.NUMBER, then: Joi.number().allow(null) },\n { is: CustomFieldDefinitionType.SELECT, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.STATUS, then: Joi.string().allow(null) },\n { is: CustomFieldDefinitionType.TEXT, then: Joi.string().allow(null) },\n ],\n});\n\nconst CustomFieldDefinitionCreationSchema = Joi.object({\n name: Joi.string().required(),\n displayName: Joi.string().required(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)).required(),\n entityId: Joi.string().guid().required(),\n entityType: Joi.string().required(),\n description: Joi.string(),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nconst CustomFieldDefinitionUpdateSchema = Joi.object({\n displayName: Joi.string(),\n validation: ValidationSchema,\n defaultValue: DefaultValueSchema,\n fieldType: Joi.string().valid(...Object.values(CustomFieldDefinitionType)),\n description: Joi.string().allow(null),\n required: Joi.boolean(),\n disabled: Joi.boolean(),\n blockEditingFromUI: Joi.boolean(),\n modelTypeIds: Joi.array().items(Joi.string().guid()),\n}).oxor('required', 'blockEditingFromUI', { isPresent: value => value === true });\n\nexport const validateCustomFieldDefinitionCreation = (payload: unknown): Promise<CreateCustomFieldDefinition> =>\n CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });\n\nexport const validateCustomFieldDefinitionUpdate = (payload: unknown): Promise<UpdateCustomFieldDefinition> =>\n CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });\n"],"mappings":"iGAIA,MAAM,EAAuB,EAAI,OAAO,CACtC,KAAM,EAAI,QAAQ,CAAC,UAAU,CAC7B,KAAM,EAAI,QAAQ,CAClB,KAAM,EAAI,QAAQ,CAClB,QAAS,EAAI,QAAQ,CAAC,MAAM,CAC7B,CAAC,CACI,EAAyB,EAAI,OAAO,CACxC,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC9B,MAAO,EAAI,QAAQ,CAAC,UAAU,CAC/B,CAAC,CAUI,EAAmB,EAAI,KAAK,YAAa,CAC7C,GAAI,EAA0B,OAC9B,KAAM,EAAI,OAAO,CAAC,UAAU,CAAC,MAAM,EA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,UAAU,CACrF,SAAU,EAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,CACxC,WAAY,EAAI,QAAQ,CAAC,UAAU,CACnC,YAAa,EAAI,QAAQ,CACzB,SAAU,EAAI,SAAS,CACvB,SAAU,EAAI,SAAS,CACvB,mBAAoB,EAAI,SAAS,CACjC,aAAc,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,MAAM,CAAC,CACrD,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAE3E,EAAoC,EAAI,OAAO,CACnD,YAAa,EAAI,QAAQ,CACzB,WAAY,EACZ,aAAc,EACd,UAAW,EAAI,QAAQ,CAAC,MAAM,GAAG,OAAO,OAAO,EAA0B,CAAC,CAC1E,YAAa,EAAI,QAAQ,CAAC,MAAM,KAAK,CACrC,SAAU,EAAI,SAAS,CACvB,SAAU,EAAI,SAAS,CACvB,mBAAoB,EAAI,SAAS,CACjC,aAAc,EAAI,OAAO,CAAC,MAAM,EAAI,QAAQ,CAAC,MAAM,CAAC,CACrD,CAAC,CAAC,KAAK,WAAY,qBAAsB,CAAE,UAAW,GAAS,IAAU,GAAM,CAAC,CAEpE,EAAyC,GACpD,EAAoC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC,CAEtE,EAAuC,GAClD,EAAkC,cAAc,EAAS,CAAE,WAAY,GAAO,CAAC"}
|
package/dist/api/v1/errors.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../_virtual/rolldown_runtime.cjs`);let t=require(`sequelize`),n=require(`joi`),r=require(`@autofleet/errors`);var i=(e,i,a)=>{let o=e;return[n.ValidationError,t.ValidationError].some(t=>e instanceof t)&&(o=new r.BadRequest([e])),(0,r.handleError)(o,i,a)};exports.default=i;
|
|
2
|
-
//# sourceMappingURL=errors.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors.cjs","names":["InputValidationError","DatabaseValidationError","BadRequest"],"sources":["../../../src/api/v1/errors.ts"],"sourcesContent":["import type { Response } from 'express';\nimport { handleError, BadRequest, type LogPayload } from '@autofleet/errors';\nimport { ValidationError as InputValidationError } from 'joi';\nimport { ValidationError as DatabaseValidationError } from 'sequelize';\n\nexport default (err: Error, res: Response, additionalData: LogPayload): void => {\n let error = err;\n if ([InputValidationError, DatabaseValidationError].some(ErrClass => err instanceof ErrClass)) {\n error = new BadRequest([err]);\n }\n\n return handleError(error, res, additionalData);\n};\n"],"mappings":"kIAKA,IAAA,GAAgB,EAAY,EAAe,IAAqC,CAC9E,IAAI,EAAQ,EAKZ,MAJI,CAACA,EAAAA,gBAAsBC,EAAAA,gBAAwB,CAAC,KAAK,GAAY,aAAe,EAAS,GAC3F,EAAQ,IAAIC,EAAAA,WAAW,CAAC,EAAI,CAAC,GAG/B,EAAA,EAAA,aAAmB,EAAO,EAAK,EAAe"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","names":["InputValidationError","DatabaseValidationError"],"sources":["../../../src/api/v1/errors.ts"],"sourcesContent":["import type { Response } from 'express';\nimport { handleError, BadRequest, type LogPayload } from '@autofleet/errors';\nimport { ValidationError as InputValidationError } from 'joi';\nimport { ValidationError as DatabaseValidationError } from 'sequelize';\n\nexport default (err: Error, res: Response, additionalData: LogPayload): void => {\n let error = err;\n if ([InputValidationError, DatabaseValidationError].some(ErrClass => err instanceof ErrClass)) {\n error = new BadRequest([err]);\n }\n\n return handleError(error, res, additionalData);\n};\n"],"mappings":"kJAKA,IAAA,GAAgB,EAAY,EAAe,IAAqC,CAC9E,IAAI,EAAQ,EAKZ,MAJI,CAACA,EAAsBC,EAAwB,CAAC,KAAK,GAAY,aAAe,EAAS,GAC3F,EAAQ,IAAI,EAAW,CAAC,EAAI,CAAC,EAGxB,EAAY,EAAO,EAAK,EAAe"}
|
package/dist/api/v1/index.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../_virtual/rolldown_runtime.cjs`),t=require(`../../utils/logger/index.cjs`),n=require(`./definition/index.cjs`),r=require(`./validator/index.cjs`);let i=require(`@autofleet/node-common`);const a=(0,i.Router)({logger:t.default});a.use(`/custom-field-definitions/:modelName`,n.default),a.use(`/custom-validators/:modelName`,r.default);var o=a;exports.default=o;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","definitionRouter","validatorRouter"],"sources":["../../../src/api/v1/index.ts"],"sourcesContent":["import { Router } from '@autofleet/node-common';\nimport logger from '../../utils/logger';\nimport definitionRouter from './definition';\nimport validatorRouter from './validator';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\n\nrouter.use('/custom-field-definitions/:modelName', definitionRouter);\nrouter.use('/custom-validators/:modelName', validatorRouter);\n\nexport default router;\n"],"mappings":"gNAKA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CAE5D,EAAO,IAAI,uCAAwCC,EAAAA,QAAiB,CACpE,EAAO,IAAI,gCAAiCC,EAAAA,QAAgB,CAE5D,IAAA,EAAe"}
|
package/dist/api/v1/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","definitionRouter","validatorRouter"],"sources":["../../../src/api/v1/index.ts"],"sourcesContent":["import { Router } from '@autofleet/node-common';\nimport logger from '../../utils/logger';\nimport definitionRouter from './definition';\nimport validatorRouter from './validator';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\n\nrouter.use('/custom-field-definitions/:modelName', definitionRouter);\nrouter.use('/custom-validators/:modelName', validatorRouter);\n\nexport default router;\n"],"mappings":"oKAKA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CAE5D,EAAO,IAAI,uCAAwCC,EAAiB,CACpE,EAAO,IAAI,gCAAiCC,EAAgB,CAE5D,IAAA,EAAe"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../../_virtual/rolldown_runtime.cjs`),t=require(`../../../utils/logger/index.cjs`),n=require(`../errors.cjs`),r=require(`../../../repository/validator.cjs`),i=require(`./validations.cjs`),a=require(`../../../utils/validations/schema/validator-schema.cjs`);let o=require(`@autofleet/errors`),s=require(`@autofleet/node-common`),c=require(`http-status-codes`);const l=(0,s.Router)({logger:t.default}),u=`CustomValidator`;l.post(`/`,async(e,o)=>{let{modelName:s}=e.params;try{let t=await i.default.create.validateAsync(e.body);a.validateValidatorSchema(t.schema);let n=await r.create({...t,modelType:s});return o.status(c.StatusCodes.CREATED).json(n)}catch(e){return n.default(e,o,{logger:t.default,message:`Error in create ${u} request`})}}),l.get(`/`,async(e,i)=>{try{let{modelName:t}=e.params,{entityId:n,entityType:a}=e.query,o={modelType:t,...n&&{entityId:n},...a&&{entityType:a}},s=await r.findAll(o);return i.status(c.StatusCodes.OK).json({validators:s})}catch(e){return n.default(e,i,{logger:t.default,message:`Error in get all ${u} request`})}}),l.get(`/:validatorId`,async(e,i)=>{try{let{validatorId:t,modelName:n}=e.params,a=await r.findAll({id:t,modelType:n},{withDisabled:!0});if(!a.length)throw new o.ResourceNotFoundError(`Validator not found`);return i.status(c.StatusCodes.OK).json(a[0])}catch(e){return n.default(e,i,{logger:t.default,message:`Error in get ${u} request`})}}),l.patch(`/:validatorId`,async(e,s)=>{try{let{validatorId:t}=e.params,n=await i.default.update.validateAsync(e.body);if(n.schema&&a.validateValidatorSchema(n.schema),!(await r.findAll({id:t},{withDisabled:!0})).length)throw new o.ResourceNotFoundError(`Validator not found`);let[l,u]=await r.update(t,n);if(!l)throw new o.ResourceNotFoundError(`Validator not found`);return s.status(c.StatusCodes.OK).json(u[0])}catch(e){return n.default(e,s,{logger:t.default,message:`Error in update ${u} request`})}}),l.delete(`/:validatorId`,async(e,i)=>{try{let{validatorId:t}=e.params;if(!(await r.findAll({id:t},{withDisabled:!0})).length)throw new o.ResourceNotFoundError(`Validator not found`);let[n]=await r.disable(t);if(!n)throw new o.ResourceNotFoundError(`Validator failed to be disabled`);return i.status(c.StatusCodes.NO_CONTENT).send()}catch(e){return n.default(e,i,{logger:t.default,message:`Error in delete ${u} request`})}});var d=l;exports.default=d;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["router: ReturnType<typeof Router>","validations","StatusCodes","handleError","ResourceNotFoundError"],"sources":["../../../../src/api/v1/validator/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport { StatusCodes } from 'http-status-codes';\nimport handleError from '../errors';\nimport * as ValidatorRepo from '../../../repository/validator';\nimport validations from './validations';\nimport logger from '../../../utils/logger';\nimport { validateValidatorSchema } from '../../../utils/validations/schema/validator-schema';\nimport type { CustomValidator } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomValidator';\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n try {\n // Validate the request body\n const validatedPayload = await validations.create.validateAsync(req.body);\n\n // Validate that the schema is a valid AJV schema\n validateValidatorSchema(validatedPayload.schema);\n\n const validator = await ValidatorRepo.create({\n ...validatedPayload,\n modelType: modelName,\n });\n\n return res.status(StatusCodes.CREATED).json(validator);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<\n { modelName: string; },\n { validators: CustomValidator[]; },\n never,\n { entityId?: string; entityType?: string; }\n>('/', async (req, res) => {\n try {\n const { modelName } = req.params;\n const { entityId, entityType } = req.query;\n\n const where = {\n modelType: modelName,\n ...(entityId && { entityId }),\n ...(entityType && { entityType }),\n };\n\n const validators = await ValidatorRepo.findAll(where);\n\n return res.status(StatusCodes.OK).json({ validators });\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; validatorId: string; }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId, modelName } = req.params;\n // Include disabled validators when fetching by ID\n const validators = await ValidatorRepo.findAll({ id: validatorId, modelType: modelName }, { withDisabled: true });\n\n if (!validators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; validatorId: string; }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // Validate the request body\n const validatedPayload = await validations.update.validateAsync(req.body);\n\n // If schema is included in the update, validate that it's a valid AJV schema\n if (validatedPayload.schema) {\n validateValidatorSchema(validatedPayload.schema);\n }\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count, validators] = await ValidatorRepo.update(validatorId, validatedPayload as any);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\n/**\n * Delete (disable)\n */\nrouter.delete<{ modelName: string; validatorId: string; }>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count] = await ValidatorRepo.disable(validatorId);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator failed to be disabled');\n }\n\n return res.status(StatusCodes.NO_CONTENT).send();\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kCAAkC,CAGpE,OAAO,EAAI,OAAOF,EAAAA,YAAY,WAAW,CAAC,MAAM,OACzC,EAAK,CACZ,OAAOC,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAEF,IAAA,EAAe"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["router: ReturnType<typeof Router>","validations","ValidatorRepo.create","handleError","ValidatorRepo.findAll","ValidatorRepo.update","ValidatorRepo.disable"],"sources":["../../../../src/api/v1/validator/index.ts"],"sourcesContent":["import { ResourceNotFoundError } from '@autofleet/errors';\nimport { Router } from '@autofleet/node-common';\nimport { StatusCodes } from 'http-status-codes';\nimport handleError from '../errors';\nimport * as ValidatorRepo from '../../../repository/validator';\nimport validations from './validations';\nimport logger from '../../../utils/logger';\nimport { validateValidatorSchema } from '../../../utils/validations/schema/validator-schema';\nimport type { CustomValidator } from '../../../models';\n\nconst router: ReturnType<typeof Router> = Router({ logger });\nconst ENTITY = 'CustomValidator';\n\n/**\n * Create\n */\nrouter.post<{ modelName: string; }>('/', async (req, res) => {\n const { modelName } = req.params;\n try {\n // Validate the request body\n const validatedPayload = await validations.create.validateAsync(req.body);\n\n // Validate that the schema is a valid AJV schema\n validateValidatorSchema(validatedPayload.schema);\n\n const validator = await ValidatorRepo.create({\n ...validatedPayload,\n modelType: modelName,\n });\n\n return res.status(StatusCodes.CREATED).json(validator);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in create ${ENTITY} request` });\n }\n});\n\n/**\n * Get all\n */\nrouter.get<\n { modelName: string; },\n { validators: CustomValidator[]; },\n never,\n { entityId?: string; entityType?: string; }\n>('/', async (req, res) => {\n try {\n const { modelName } = req.params;\n const { entityId, entityType } = req.query;\n\n const where = {\n modelType: modelName,\n ...(entityId && { entityId }),\n ...(entityType && { entityType }),\n };\n\n const validators = await ValidatorRepo.findAll(where);\n\n return res.status(StatusCodes.OK).json({ validators });\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in get all ${ENTITY} request` });\n }\n});\n\n/**\n * Get by id\n */\nrouter.get<{ modelName: string; validatorId: string; }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId, modelName } = req.params;\n // Include disabled validators when fetching by ID\n const validators = await ValidatorRepo.findAll({ id: validatorId, modelType: modelName }, { withDisabled: true });\n\n if (!validators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in get ${ENTITY} request` });\n }\n});\n\n/**\n * Update\n */\nrouter.patch<{ modelName: string; validatorId: string; }, CustomValidator>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // Validate the request body\n const validatedPayload = await validations.update.validateAsync(req.body);\n\n // If schema is included in the update, validate that it's a valid AJV schema\n if (validatedPayload.schema) {\n validateValidatorSchema(validatedPayload.schema);\n }\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count, validators] = await ValidatorRepo.update(validatorId, validatedPayload as any);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n return res.status(StatusCodes.OK).json(validators[0]);\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in update ${ENTITY} request` });\n }\n});\n\n/**\n * Delete (disable)\n */\nrouter.delete<{ modelName: string; validatorId: string; }>('/:validatorId', async (req, res) => {\n try {\n const { validatorId } = req.params;\n\n // First verify the validator exists, including disabled ones\n const existingValidators = await ValidatorRepo.findAll({ id: validatorId }, { withDisabled: true });\n if (!existingValidators.length) {\n throw new ResourceNotFoundError('Validator not found');\n }\n\n const [count] = await ValidatorRepo.disable(validatorId);\n\n if (!count) {\n throw new ResourceNotFoundError('Validator failed to be disabled');\n }\n\n return res.status(StatusCodes.NO_CONTENT).send();\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in delete ${ENTITY} request` });\n }\n});\n\nexport default router;\n"],"mappings":"ocAUA,MAAMA,EAAoC,EAAO,CAAE,OAAA,EAAQ,CAAC,CACtD,EAAS,kBAKf,EAAO,KAA6B,IAAK,MAAO,EAAK,IAAQ,CAC3D,GAAM,CAAE,aAAc,EAAI,OAC1B,GAAI,CAEF,IAAM,EAAmB,MAAMC,EAAY,OAAO,cAAc,EAAI,KAAK,CAGzE,EAAwB,EAAiB,OAAO,CAEhD,IAAM,EAAY,MAAMC,EAAqB,CAC3C,GAAG,EACH,UAAW,EACZ,CAAC,CAEF,OAAO,EAAI,OAAO,EAAY,QAAQ,CAAC,KAAK,EAAU,OAC/C,EAAK,CACZ,OAAOC,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,mBAAmB,EAAO,UAAW,CAAC,GAEjG,CAKF,EAAO,IAKL,IAAK,MAAO,EAAK,IAAQ,CACzB,GAAI,CACF,GAAM,CAAE,aAAc,EAAI,OACpB,CAAE,WAAU,cAAe,EAAI,MAQ/B,EAAa,MAAMC,EANX,CACZ,UAAW,EACX,GAAI,GAAY,CAAE,WAAU,CAC5B,GAAI,GAAc,CAAE,aAAY,CACjC,CAEoD,CAErD,OAAO,EAAI,OAAO,EAAY,GAAG,CAAC,KAAK,CAAE,aAAY,CAAC,OAC/C,EAAK,CACZ,OAAOD,EAAY,EAAc,EAAK,CAAE,OAAA,EAAQ,QAAS,oBAAoB,EAAO,UAAW,CAAC,GAElG,CAKF,EAAO,IAAkE,gBAAiB,MAAO,EAAK,IAAQ,CAC5G,GAAI,CACF,GAAM,CAAE,cAAa,aAAc,EAAI,OAEjC,EAAa,MAAMC,EAAsB,CAAE,GAAI,EAAa,UAAW,EAAW,CAAE,CAAE,aAAc,GAAM,CAAC,CAEjH,GAAI,CAAC,EAAW,OACd,MAAM,IAAI,EAAsB,sBAAsB,CAGxD,OAAO,EAAI,OAAO,EAAY,G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=require(`../../../_virtual/rolldown_runtime.cjs`);let t=require(`joi`);t=e.__toESM(t);const n=t.default.object().unknown(!0),r=t.default.object({type:t.default.string().valid(`object`),properties:t.default.object({before:n,after:n}).required(),required:t.default.array().items(t.default.string()),allOf:t.default.array().items(t.default.object()),anyOf:t.default.array().items(t.default.object()),oneOf:t.default.array().items(t.default.object()),additionalProperties:t.default.alternatives().try(t.default.boolean(),t.default.object()),$id:t.default.string(),$schema:t.default.string(),if:t.default.object(),then:t.default.object(),else:t.default.object()}),i={create:t.default.object({entityId:t.default.string().uuid().required(),entityType:t.default.string().required(),schema:r.required()}),update:t.default.object({entityId:t.default.string().uuid(),entityType:t.default.string(),schema:r,disabled:t.default.boolean()}).min(1)};var a=i;exports.default=a;
|
|
2
|
-
//# sourceMappingURL=validations.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"validations.cjs","names":["Joi","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":"8FAEA,MAAM,EAAuBA,EAAAA,QAAI,QAAQ,CAAC,QAAQ,GAAK,CAoBjD,EAAeA,EAAAA,QAAI,OAAqB,CAC5C,KAAMA,EAAAA,QAAI,QAAQ,CAAC,MAAM,SAAS,CAClC,WAAYA,EAAAA,QAAI,OAAO,CACrB,OAAQ,EACR,MAAO,EACR,CAAC,CAAC,UAAU,CACb,SAAUA,EAAAA,QAAI,OAAO,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,CACzC,MAAOA,EAAAA,QAAI,OAAO,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,CACtC,MAAOA,EAAAA,QAAI,OAAO,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,CACtC,MAAOA,EAAAA,QAAI,OAAO,CAAC,MAAMA,EAAAA,QAAI,QAAQ,CAAC,CACtC,qBAAsBA,EAAAA,QAAI,cAAc,CAAC,IAAIA,EAAAA,QAAI,SAAS,CAAEA,EAAAA,QAAI,QAAQ,CAAC,CACzE,IAAKA,EAAAA,QAAI,QAAQ,CACjB,QAASA,EAAAA,QAAI,QAAQ,CACrB,GAAIA,EAAAA,QAAI,QAAQ,CAChB,KAAMA,EAAAA,QAAI,QAAQ,CAClB,KAAMA,EAAAA,QAAI,QAAQ,CACnB,CAAC,CAiBIC,EAAuC,CAC3C,OAAQD,EAAAA,QAAI,OAA+B,CACzC,SAAUA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAAC,UAAU,CACxC,WAAYA,EAAAA,QAAI,QAAQ,CAAC,UAAU,CACnC,OAAQ,EAAa,UAAU,CAChC,CAAC,CAEF,OAAQA,EAAAA,QAAI,OAA+B,CACzC,SAAUA,EAAAA,QAAI,QAAQ,CAAC,MAAM,CAC7B,WAAYA,EAAAA,QAAI,QAAQ,CACxB,OAAQ,EACR,SAAUA,EAAAA,QAAI,SAAS,CACxB,CAAC,CAAC,IAAI,EAAE,CACV,CAED,IAAA,EAAe"}
|
|
@@ -1,23 +0,0 @@
|
|
|
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 +0,0 @@
|
|
|
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"}
|
package/dist/errors/index.cjs
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
package/dist/errors/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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_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I,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"}
|
package/dist/events/index.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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
|
|
@@ -1 +0,0 @@
|
|
|
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"}
|
package/dist/events/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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"}
|
package/dist/hooks/enrich.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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,hasTypeId:!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));let y;if(!_)if(u.hasTypeId&&p.length>0&&p[0].typeId){let n=[...new Set(p.map(e=>e.typeId).filter(Boolean))];y=new Map,n.forEach(e=>y.set(e,new Set));let r=(await Promise.all(n.map(async n=>{let r=await e.findByModelTypeId(n,{withDisabled:!1,entityIds:h,modelType:t,modelOptions:l});return r.forEach(e=>y.get(n).add(e.id)),r}))).flat(),i=new Map;r.forEach(e=>{i.set(e.id,e)}),_=Promise.resolve(Array.from(i.values()))}else _=e.findByEntityIds(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_);let b=await _;if(b.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{b.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!g[n]&&(g[n]=[])})});let x=b.reduce((e,t)=>({...e,[t.id]:t}),{});b.forEach(e=>{let t=e.entityId;if(l?.useEntityIdFromInclude&&l.include){let n=l.include(m);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}g[t]&&g[t].push(e)});let S=p.map(e=>e.id),[C,w]=await Promise.all([o({instancesIds:S,options:f,sadotOptions:u}),a({instancesIds:S,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=C[t],i=r?s(r,x):{},a=u.useCustomFieldsEntries?w[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(t=>{y&&!y.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.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
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<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' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: 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 let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction)\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n customFieldDefinitionsPromise = Promise.resolve(Array.from(uniqueDefinitionsMap.values()));\n } else {\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 }\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: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\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 (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\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":"sKAUM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAA,EAAA,sBACzB,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAA,EAAA,qBACxB,EACA,GAAW,EAAE,CACd,EAGwB,QAA4C,EAAK,IAAM,CAC9E,GAAM,CAAE,WAAY,EAGpB,MAFA,GAAI,KAAa,EAAE,CACnB,EAAI,GAAS,KAAK,EAAE,CACb,GACN,EAAE,CAAC,CAMF,GACJ,EACA,IAEqB,EAAkB,QAAQ,EAAK,KAAS,CAC3D,GAAG,EACH,GACE,EAA2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QAAQ,IAAI,CAChF,EAAyB,CACvB,eACA,UACA,eACD,CAAC,CACF,EAAkC,CAChC,eACA,UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C,EAGJ,IAAA,EAAe"}
|
package/dist/hooks/enrich.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined","DefinitionRepo.findByModelTypeId","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' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: 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 let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction)\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n customFieldDefinitionsPromise = Promise.resolve(Array.from(uniqueDefinitionsMap.values()));\n } else {\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 }\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: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\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 (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\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":"+PAUA,MAAM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,WACA,WACA,eACD,CAgBY,EAAoC,MAAO,CACtD,eACA,UACA,kBAKwD,CACxD,GAAI,CAAC,EAAa,uBAChB,MAAO,EAAE,CAGX,IAAM,EAAqB,MAAMA,EAC/B,EACA,GAAW,EAAE,CACd,CAEK,EAAiC,OAAO,YAAY,EAAmB,IAAK,GAAoB,CACpG,GAAM,CAAE,UAAS,gBAAiB,GAAiB,YAAc,EAAE,CAC9D,KAGL,MAAO,CAAC,EAAS,EAAa,EAC9B,CAAC,OAAO,GAAK,IAAM,IAAA,GAAU,CAAC,CAMhC,OAJA,EAAa,QAAS,GAAe,CACnC,EAA+B,KAAgB,EAAE,EACjD,CAEK,GAGI,EAA2B,MAAO,CAC7C,eACA,UACA,kBAMI,EAAa,uBACR,EAAE,EAGe,MAAMC,EAC9B,EACA,GAAW,EAAE,CACd,EAGwB,QAA4C,EAAK,IAAM,CAC9E,GAAM,CAAE,WAAY,EAGpB,MAFA,GAAI,KAAa,EAAE,CACnB,EAAI,GAAS,KAAK,EAAE,CACb,GACN,EAAE,CAAC,CAMF,GACJ,EACA,IAEqB,EAAkB,QAAQ,EAAK,KAAS,CAC3D,GAAG,EACH,GACE,EAA2B,EAAI,0BAC5B,EAAG,EAA2B,EAAI,yBAAyB,MAAO,EAAI,MAAO,CAEnF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UACA,eACD,CAAC,CACH,CAAC,CAGF,EAAU,QAAS,GAAa,CAC9B,GAAM,CAAE,MAAO,EAET,EAAiB,EAAsB,GACvC,EAA+B,EAAiB,EAAsB,EAAgB,EAAe,CAAG,EAAE,CAE1G,EAAe,EAAa,uBAC9B,EAA+B,GAC/B,EAEJ,EAAgB,QAAS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,GAEE,CAD4B,EAAwB,IAAI,EAAS,OAAO,EAC9C,IAAI,EAAsB,GAAG,EAKzD,EAAa,EAAsB,QAAU,IAAA,KAC/C,EAAa,EAAsB,MAAQ,OAE7C,EAEJ,CACF,EAAS,aAAe,EACvB,EAAQ,oBAA6C,UAAW,GAAc,CAC7E,OAAO,EAAS,aAAa,GAE7B,OAAO,IAAW,IAClB,CAEE,IAAa,aAEf,GAAU,UAAU,eAAgB,GAAM,EAE5C"}
|
package/dist/hooks/find.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
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
|
package/dist/hooks/find.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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"}
|
package/dist/hooks/find.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
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"}
|
package/dist/hooks/hooks.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`../utils/constants/index.cjs`),r=require(`../errors/index.cjs`),i=require(`../repository/definition.cjs`),a=require(`../repository/validator.cjs`),o=require(`../utils/scopeAttributes.cjs`),s=require(`./utils/updateInstanceValues.cjs`);let c=require(`joi`);c=e.__toESM(c);let l=require(`@autofleet/errors`),u=require(`ajv`);u=e.__toESM(u);let d=require(`ajv-formats`);d=e.__toESM(d);let f=require(`ajv-errors`);f=e.__toESM(f);const p=[`id`,`schema`,`modelType`,`entityId`,`disabled`],m=new u.default({allErrors:!0,strict:!1,strictTypes:!1,$data:!0});(0,d.default)(m),(0,f.default)(m);const h=(e,t)=>({__proto__:null,...e,...t}),g=async(e,n)=>{if(!e.id||!e.customFields||Object.keys(e.customFields).length===0)return e.customFields||{};try{let r=await e.constructor.findOne({where:{id:e.id},attributes:[`customFields`],transaction:n.transaction,raw:!0});if(r?.customFields){let n=h(r.customFields,e.customFields);return t.default.debug(`sadot - fetched complete custom fields for validation`,{fieldsCount:Object.keys(n).length,updateFieldsCount:Object.keys(e.customFields).length}),n}}catch(e){t.default.error(`sadot - error fetching complete model for validation`,{error:e})}return e.customFields||{}},_=e=>{let t={...e.dataValues};(e.changed?.()||[]).forEach(n=>{let r=e.previous?.(n);r!==void 0&&(t[n]=r)});let n=e.previous?.(`customFields`);return n!==void 0&&(t.customFields=n),t},v=e=>e.reduce((e,t)=>{let n=((t.instancePath||``).split(`/`).filter(Boolean).join(`.`).replace(/^after\./,``)+(t.keyword===`required`?`.${t.params?.missingProperty}`:``)).replace(/^\./,``)||`root`;return e[n]=t.message||`Invalid value`,e},{}),y=async(e,n,r,i={},s=!1)=>{let c=e.constructor.name;t.default.debug(`sadot - validating model`,{isCreate:s,modelType:c});let u=o.default(e,r);if(t.default.debug(`sadot - identifiers`,{identifiers:u}),!u||Object.keys(u).length===0){t.default.debug(`sadot - skipping validation: no identifiers`);return}let d=Object.values(u)[0];if(t.default.debug(`sadot - entityId`,{entityId:d}),!d){t.default.debug(`sadot - skipping validation: no entityId`);return}let f,y;n.transaction&&(n.transaction.validationsCache??=new Map,y=`${c}-${d}`,f=n.transaction.validationsCache.get(y)),f||(f=a.findAllByModelType(c,d,{transaction:n.transaction,attributes:p,modelOptions:i}),n.transaction&&n?.transaction?.validationsCache.set(y,f));let b=await f;if(t.default.debug(`sadot - validators found`,{count:b.length}),!b.length){t.default.debug(`sadot - skipping validation: no validators found`);return}let x=null;s||(x=_(e));let S=s?e.customFields||{}:await g(e,n);for(let n of b){let{schema:r}=n,i=r;if(t.default.debug(`sadot - validating with schema`,{schema:r,hasAfterProps:!!i.properties?.after,hasBeforeProps:!!i.properties?.before}),s){if(i.properties?.after){let t=m.compile({...r,properties:{after:i.properties.after}});if(!t(JSON.parse(JSON.stringify({after:{...e.dataValues,customFields:S}})))){let e=t.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),n=v(t.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:n})}}}else{let n=m.compile(i),r=h(e.dataValues);r.customFields=S;let a={before:x,after:r},o=n(JSON.parse(JSON.stringify(a)));if(t.default.debug(`sadot - validation result`,{isValid:o,test:{before:x,after:r}}),!o){let e=n.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),t=v(n.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:t})}}}},b=async({modelType:e,modelOptions:t,identifiers:n,options:r})=>{let{include:a,useEntityIdFromInclude:o}=t,s={modelType:e,disabled:!1,...!o&&{entityId:n}};return await i.findAll(s,{withDisabled:!1,transaction:r.transaction,include:a?.(n)})},x=(e,t)=>{(e||[]).forEach(e=>{let{fieldType:i,name:a}=e;if([n.CustomFieldDefinitionType.DATE,n.CustomFieldDefinitionType.DATETIME].includes(i)){let e=t.customFields?.[a];if(e){let{value:n,error:i}=c.default.date().validate(e);if(i)throw new r.InvalidValueError(e,a,i);t.customFields[a]=n.toISOString()}}})},S=(e,n={},i={useCustomFieldsEntries:!1})=>async(a,c)=>{t.default.debug(`sadot - before create hook`);let{fields:l}=c,u=a.constructor.name,d=o.default(a,e),f=await b({modelType:u,modelOptions:n,identifiers:d,options:c}),p=f.filter(e=>![null,void 0].includes(e.defaultValue));p.length&&(a.customFields||={},p.filter(e=>a.customFields?.[e.name]===void 0).forEach(({name:e,defaultValue:t})=>{a.customFields[e]=t}));let m=Array.from(new Set(f.filter(({required:e})=>e).map(({name:e})=>e))),{customFields:h}=a,g=Object.keys(h??{}),_=m.filter(e=>!g.includes(e));if(_?.length)throw new r.MissingRequiredCustomFieldError(_);await y(a,c,e,n,!0),x(f,a);let v=l.indexOf(`customFields`);v===-1||!h||!Object.keys(h).length||(await s.default({modelId:a.id,modelType:u,identifiers:d,customFields:h,options:{useCustomFieldsEntries:i.useCustomFieldsEntries,transaction:c.transaction,modelOptions:n}}),l.splice(v,1))},C=(e,n={},r={useCustomFieldsEntries:!1})=>async(i,a)=>{t.default.debug(`sadot - before update hook`);let{fields:c}=a,l=i.constructor.name,u=o.default(i,e),d=await b({modelType:l,modelOptions:n,identifiers:u,options:a});await y(i,a,e,n,!1),x(d,i);let f=c.indexOf(`customFields`);if(f>-1){let{customFields:e}=i;if(!Object.keys(e).length)return;await s.default({modelId:i.id,modelType:l,identifiers:u,customFields:e,options:{useCustomFieldsEntries:r.useCustomFieldsEntries,transaction:a.transaction,modelOptions:n}}),c.splice(f,1)}},w=e=>{e.individualHooks=!0},T=e=>{e.individualHooks=!0};exports.beforeBulkCreate=w,exports.beforeBulkUpdate=T,exports.beforeCreate=S,exports.beforeUpdate=C;
|
|
2
|
-
//# sourceMappingURL=hooks.cjs.map
|
package/dist/hooks/hooks.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.cjs","names":["ajv","Ajv","beforeFull: any","applyScopeToInstance","cacheKey: string | undefined","BadRequest","where: WhereOptions","CustomFieldDefinitionType","Joi","InvalidValueError","MissingRequiredCustomFieldError","updateInstanceValues"],"sources":["../../src/hooks/hooks.ts"],"sourcesContent":["import type {\n BulkCreateOptions, CreateOptions, Transactionable, UpdateOptions, WhereOptions,\n} from 'sequelize';\nimport Ajv from 'ajv';\nimport Joi from 'joi';\nimport addFormats from 'ajv-formats';\nimport { BadRequest } from '@autofleet/errors';\nimport ajvErrors from 'ajv-errors';\nimport logger from '../utils/logger';\nimport * as ValidatorRepo from '../repository/validator';\nimport * as DefinitionRepo from '../repository/definition';\nimport { InvalidValueError, MissingRequiredCustomFieldError } from '../errors';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\nimport updateInstanceValues from './utils/updateInstanceValues';\nimport { CustomFieldDefinitionType } from '../utils/constants';\nimport type { CustomFieldDefinition } from '../models';\n\n// Include all required fields for proper validation\nconst CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL = ['id', 'schema', 'modelType', 'entityId', 'disabled'];\n\n// Initialize Ajv with relaxed settings to avoid warnings\nconst ajv = new Ajv({\n allErrors: true,\n strict: false, // Disable strict mode to avoid warnings\n strictTypes: false, // Disable strict type checking\n $data: true, // Enable $data references\n});\n\naddFormats(ajv);\najvErrors(ajv);\n\n/**\n * Helper function to manually copy object properties\n * This is more efficient for large objects and avoids excessive object creation\n */\nconst manualObjectCopy = (sourceObj: Record<string, any>, additionalProps?: Record<string, any>): Record<string, any> =>\n ({ __proto__: null, ...sourceObj, ...additionalProps });\n\n/**\n * Fetches complete custom fields for an instance by merging DB values with update values\n * This is needed for partial updates to ensure all related fields are available for validation\n */\nconst getCompleteCustomFields = async (instance: any, options: Transactionable): Promise<Record<string, any>> => {\n // If we don't have an instance id or no custom fields being updated, return original fields\n if (!instance.id || !instance.customFields || Object.keys(instance.customFields).length === 0) {\n return instance.customFields || {};\n }\n\n try {\n const ModelClass = instance.constructor;\n // Only select the customFields column to minimize data transfer\n const currentCustomFields = await ModelClass.findOne({\n where: { id: instance.id },\n attributes: ['customFields'],\n transaction: options.transaction,\n raw: true, // Get plain object instead of model instance for better performance\n });\n\n if (currentCustomFields?.customFields) {\n // Merge existing fields with update fields using our helper function\n const completeFields = manualObjectCopy(\n currentCustomFields.customFields,\n instance.customFields,\n );\n\n logger.debug('sadot - fetched complete custom fields for validation', {\n fieldsCount: Object.keys(completeFields).length,\n updateFieldsCount: Object.keys(instance.customFields).length,\n });\n\n return completeFields;\n }\n } catch (error) {\n logger.error('sadot - error fetching complete model for validation', { error });\n // Continue with partial data if we can't fetch the complete model\n }\n\n return instance.customFields || {};\n};\n\nconst buildPreChangeState = (instance: any) => {\n const beforeFull: any = { ...instance.dataValues };\n\n const changedKeys: string[] = instance.changed?.() || [];\n changedKeys.forEach((key) => {\n const prevVal = instance.previous?.(key);\n if (prevVal !== undefined) {\n beforeFull[key] = prevVal;\n }\n });\n\n const prevCF = instance.previous?.('customFields');\n if (prevCF !== undefined) {\n beforeFull.customFields = prevCF;\n }\n\n return beforeFull;\n};\n\nconst formatAjvErrors = (\n errors: {\n instancePath?: string;\n keyword: string;\n message?: string;\n params?: Record<string, any>;\n }[],\n): Record<string, string> => errors.reduce((acc, err) => {\n const basePath = (err.instancePath || '')\n .split('/')\n .filter(Boolean)\n .join('.')\n .replace(/^after\\./, '');\n\n const missingProp = err.keyword === 'required' ? `.${err.params?.missingProperty}` : '';\n const key = (basePath + missingProp).replace(/^\\./, '') || 'root';\n\n const message = err.message || 'Invalid value';\n acc[key] = message;\n\n return acc;\n}, {} as Record<string, string>);\n\n/**\n * Validates the model using custom validators\n */\nconst validateModel = async (\n instance: any,\n options: TransactionOptions,\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n isCreate = false,\n): Promise<void> => {\n const modelType = instance.constructor.name;\n\n logger.debug('sadot - validating model', { isCreate, modelType });\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n logger.debug('sadot - identifiers', { identifiers });\n\n // Skip if no identifiers\n if (!identifiers || Object.keys(identifiers).length === 0) {\n logger.debug('sadot - skipping validation: no identifiers');\n return;\n }\n\n // Find the entityId from identifiers (fleetId, businessModelId, etc.)\n const entityId = Object.values(identifiers)[0]; // Get the first value as entityId\n\n logger.debug('sadot - entityId', { entityId });\n\n if (!entityId) {\n logger.debug('sadot - skipping validation: no entityId');\n return;\n }\n\n let validatorsPromise;\n let cacheKey: string | undefined;\n if (options.transaction) {\n options.transaction.validationsCache ??= new Map();\n cacheKey = `${modelType}-${entityId}`;\n validatorsPromise = options.transaction.validationsCache.get(cacheKey);\n }\n\n if (!validatorsPromise) {\n validatorsPromise = ValidatorRepo.findAllByModelType(\n modelType,\n entityId,\n {\n transaction: options.transaction,\n attributes: CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL,\n modelOptions,\n },\n );\n if (options.transaction) {\n options?.transaction?.validationsCache!.set(cacheKey!, validatorsPromise);\n }\n }\n const validators = await validatorsPromise;\n\n logger.debug('sadot - validators found', { count: validators.length });\n\n if (!validators.length) {\n logger.debug('sadot - skipping validation: no validators found');\n return;\n }\n\n // For updates, get the previous values\n let originalValues = null;\n if (!isCreate) {\n originalValues = buildPreChangeState(instance);\n }\n\n // Get complete custom fields by merging DB values with update values\n // This is especially important for partial updates to ensure all related fields are available\n const completeCustomFields = !isCreate\n ? await getCompleteCustomFields(instance, options)\n : instance.customFields || {};\n\n for (const validator of validators) {\n const { schema } = validator;\n const typedSchema = schema as Record<string, any>;\n\n logger.debug('sadot - validating with schema', {\n schema,\n hasAfterProps: !!typedSchema.properties?.after,\n hasBeforeProps: !!typedSchema.properties?.before,\n });\n\n if (isCreate) {\n // For create operations, we only need the 'after' state\n if (typedSchema.properties?.after) {\n const validateSchema = ajv.compile({\n ...schema,\n // Focus only on the 'after' validation part for create\n properties: {\n after: typedSchema.properties.after,\n },\n });\n\n const isValid = validateSchema(JSON.parse(JSON.stringify({\n after: {\n ...instance.dataValues,\n customFields: completeCustomFields,\n },\n })));\n\n if (!isValid) {\n const errorDetails = validateSchema.errors?.map(err =>\n `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors!);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n } else {\n // For update operations, we need both before and after\n const validateSchema = ajv.compile(typedSchema);\n\n // Create after object with our helper function\n const afterObj = manualObjectCopy(instance.dataValues);\n\n // Add complete custom fields\n afterObj.customFields = completeCustomFields;\n\n // Create validation payload\n const payload = {\n before: originalValues,\n after: afterObj,\n };\n\n // Validate\n const isValid = validateSchema(JSON.parse(JSON.stringify(payload)));\n\n logger.debug('sadot - validation result', {\n isValid,\n test: {\n before: originalValues,\n after: afterObj,\n },\n });\n\n if (!isValid) {\n const errorDetails = validateSchema\n .errors\n ?.map(err => `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors!);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n }\n};\n\nconst getFieldDefinitions = async ({\n modelType,\n modelOptions,\n identifiers,\n options,\n}: {\n modelType: any;\n modelOptions: ModelOptions;\n identifiers: any[];\n options: any;\n}) => {\n const { include, useEntityIdFromInclude } = modelOptions;\n const where: WhereOptions = {\n modelType,\n disabled: false,\n ...(!useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, {\n withDisabled: false,\n transaction: options.transaction,\n include: include?.(identifiers),\n });\n return fieldDefinitions;\n};\n\nconst formatDates = (fieldDefinitions: CustomFieldDefinition[], instance: any) => {\n (fieldDefinitions || []).forEach((fieldDefinition) => {\n const { fieldType, name } = fieldDefinition;\n if ([CustomFieldDefinitionType.DATE, CustomFieldDefinitionType.DATETIME].includes(fieldType)) {\n const value = instance.customFields?.[name];\n if (value) {\n const { value: joiValue, error: validationError } = Joi.date().validate(value);\n if (validationError) {\n throw new InvalidValueError(value, name, validationError);\n }\n instance.customFields[name] = joiValue.toISOString();\n }\n }\n });\n};\n\n/**\n * Hook to handle validation and custom fields during creation\n */\nexport const beforeCreate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instance: any,\n options: CreateOptions,\n): Promise<void> => {\n logger.debug('sadot - before create hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n // Step 1: Handle custom fields default values and required fields\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options,\n });\n\n // Apply default values\n const fieldsWithDefaultValue = fieldDefinitions.filter(def => ![null, undefined].includes(def.defaultValue));\n if (fieldsWithDefaultValue.length) {\n instance.customFields ||= {};\n fieldsWithDefaultValue\n .filter(def => (instance.customFields?.[def.name] === undefined))\n .forEach(({ name, defaultValue }) => {\n instance.customFields[name] = defaultValue;\n });\n }\n\n // Check for required fields\n const requiredFieldsNames = Array.from(\n new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)),\n );\n const { customFields } = instance;\n const fieldsNames = Object.keys(customFields ?? {});\n const missingFields = requiredFieldsNames.filter(name => !fieldsNames.includes(name));\n if (missingFields?.length) {\n throw new MissingRequiredCustomFieldError(missingFields);\n }\n\n // Step 2: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, scopeAttributes, modelOptions, true);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 3: Save custom field values if they exist\n const customFieldsIdx = fields!.indexOf('customFields');\n if (customFieldsIdx === -1 || !customFields || !Object.keys(customFields).length) {\n // No custom fields to update\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n fields!.splice(customFieldsIdx, 1);\n};\n\n/**\n * Hook to handle validation and custom fields during update\n */\nexport const beforeUpdate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instance: any,\n options: UpdateOptions,\n): Promise<void> => {\n logger.debug('sadot - before update hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options,\n });\n\n // Step 1: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, scopeAttributes, modelOptions, false);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 2: Update custom field values if they exist\n const customFieldsIdx = fields!.indexOf('customFields');\n if (customFieldsIdx > -1) {\n const { customFields } = instance;\n\n if (!Object.keys(customFields).length) {\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n fields!.splice(customFieldsIdx, 1);\n }\n};\n\n/**\n * Hook to enable individual hooks for bulk create operations\n */\nexport const beforeBulkCreate = (options: BulkCreateOptions): void => {\n // This will activate the beforeCreate hook on each instance\n options.individualHooks = true;\n};\n\n/**\n * Hook to enable individual hooks for bulk update operations\n */\nexport const beforeBulkUpdate = (options: UpdateOptions): void => {\n // This will activate the beforeUpdate hook on each instance\n options.individualHooks = true;\n};\n"],"mappings":"+gBAmBA,MAAM,EAAsC,CAAC,KAAM,SAAU,YAAa,WAAY,WAAW,CAG3FA,EAAM,IAAIC,EAAAA,QAAI,CAClB,UAAW,GACX,OAAQ,GACR,YAAa,GACb,MAAO,GACR,CAAC,eAESD,EAAI,eACLA,EAAI,CAMd,MAAM,GAAoB,EAAgC,KACvD,CAAE,UAAW,KAAM,GAAG,EAAW,GAAG,EAAiB,EAMlD,EAA0B,MAAO,EAAe,IAA2D,CAE/G,GAAI,CAAC,EAAS,IAAM,CAAC,EAAS,cAAgB,OAAO,KAAK,EAAS,aAAa,CAAC,SAAW,EAC1F,OAAO,EAAS,cAAgB,EAAE,CAGpC,GAAI,CAGF,IAAM,EAAsB,MAFT,EAAS,YAEiB,QAAQ,CACnD,MAAO,CAAE,GAAI,EAAS,GAAI,CAC1B,WAAY,CAAC,eAAe,CAC5B,YAAa,EAAQ,YACrB,IAAK,GACN,CAAC,CAEF,GAAI,GAAqB,aAAc,CAErC,IAAM,EAAiB,EACrB,EAAoB,aACpB,EAAS,aACV,CAOD,OALA,EAAA,QAAO,MAAM,wDAAyD,CACpE,YAAa,OAAO,KAAK,EAAe,CAAC,OACzC,kBAAmB,OAAO,KAAK,EAAS,aAAa,CAAC,OACvD,CAAC,CAEK,SAEF,EAAO,CACd,EAAA,QAAO,MAAM,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,EAAmE,CAAE,uBAAwB,GAAO,GACjG,MACH,EACA,IACkB,CAClB,EAAA,QAAO,MAAM,6BAA6B,CAC1C,GAAM,CAAE,UAAW,EACb,EAAY,EAAS,YAAY,KACjC,EAAcR,EAAAA,QAAqB,EAAU,EAAgB,CAE7D,EAAmB,MAAM,EAAoB,CACjD,YAAW,eAAc,cAAa,UACvC,CAAC,CAGF,MAAM,EAAc,EAAU,EAA+B,EAAiB,EAAc,GAAM,CAGlG,EAAY,EAAkB,EAAS,CAGvC,IAAM,EAAkB,EAAQ,QAAQ,eAAe,CACvD,GAAI,EAAkB,GAAI,CACxB,GAAM,CAAE,gBAAiB,EAEzB,GAAI,CAAC,OAAO,KAAK,EAAa,CAAC,OAC7B,OAIF,MAAMQ,EAAAA,QAAqB,CACzB,QAAS,EAAS,GAClB,YACA,cACA,eACA,QAAS,CACP,uBAAwB,EAAa,uBACrC,YAAa,EAAQ,YACrB,eACD,CACF,CAAC,CAGF,EAAQ,OAAO,EAAiB,EAAE,GAOzB,EAAoB,GAAqC,CAEpE,EAAQ,gBAAkB,IAMf,EAAoB,GAAiC,CAEhE,EAAQ,gBAAkB"}
|
package/dist/hooks/hooks.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.js","names":["beforeFull: any","applyScopeToInstance","cacheKey: string | undefined","ValidatorRepo.findAllByModelType","where: WhereOptions","DefinitionRepo.findAll","updateInstanceValues"],"sources":["../../src/hooks/hooks.ts"],"sourcesContent":["import type {\n BulkCreateOptions, CreateOptions, Transactionable, UpdateOptions, WhereOptions,\n} from 'sequelize';\nimport Ajv from 'ajv';\nimport Joi from 'joi';\nimport addFormats from 'ajv-formats';\nimport { BadRequest } from '@autofleet/errors';\nimport ajvErrors from 'ajv-errors';\nimport logger from '../utils/logger';\nimport * as ValidatorRepo from '../repository/validator';\nimport * as DefinitionRepo from '../repository/definition';\nimport { InvalidValueError, MissingRequiredCustomFieldError } from '../errors';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\nimport updateInstanceValues from './utils/updateInstanceValues';\nimport { CustomFieldDefinitionType } from '../utils/constants';\nimport type { CustomFieldDefinition } from '../models';\n\n// Include all required fields for proper validation\nconst CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL = ['id', 'schema', 'modelType', 'entityId', 'disabled'];\n\n// Initialize Ajv with relaxed settings to avoid warnings\nconst ajv = new Ajv({\n allErrors: true,\n strict: false, // Disable strict mode to avoid warnings\n strictTypes: false, // Disable strict type checking\n $data: true, // Enable $data references\n});\n\naddFormats(ajv);\najvErrors(ajv);\n\n/**\n * Helper function to manually copy object properties\n * This is more efficient for large objects and avoids excessive object creation\n */\nconst manualObjectCopy = (sourceObj: Record<string, any>, additionalProps?: Record<string, any>): Record<string, any> =>\n ({ __proto__: null, ...sourceObj, ...additionalProps });\n\n/**\n * Fetches complete custom fields for an instance by merging DB values with update values\n * This is needed for partial updates to ensure all related fields are available for validation\n */\nconst getCompleteCustomFields = async (instance: any, options: Transactionable): Promise<Record<string, any>> => {\n // If we don't have an instance id or no custom fields being updated, return original fields\n if (!instance.id || !instance.customFields || Object.keys(instance.customFields).length === 0) {\n return instance.customFields || {};\n }\n\n try {\n const ModelClass = instance.constructor;\n // Only select the customFields column to minimize data transfer\n const currentCustomFields = await ModelClass.findOne({\n where: { id: instance.id },\n attributes: ['customFields'],\n transaction: options.transaction,\n raw: true, // Get plain object instead of model instance for better performance\n });\n\n if (currentCustomFields?.customFields) {\n // Merge existing fields with update fields using our helper function\n const completeFields = manualObjectCopy(\n currentCustomFields.customFields,\n instance.customFields,\n );\n\n logger.debug('sadot - fetched complete custom fields for validation', {\n fieldsCount: Object.keys(completeFields).length,\n updateFieldsCount: Object.keys(instance.customFields).length,\n });\n\n return completeFields;\n }\n } catch (error) {\n logger.error('sadot - error fetching complete model for validation', { error });\n // Continue with partial data if we can't fetch the complete model\n }\n\n return instance.customFields || {};\n};\n\nconst buildPreChangeState = (instance: any) => {\n const beforeFull: any = { ...instance.dataValues };\n\n const changedKeys: string[] = instance.changed?.() || [];\n changedKeys.forEach((key) => {\n const prevVal = instance.previous?.(key);\n if (prevVal !== undefined) {\n beforeFull[key] = prevVal;\n }\n });\n\n const prevCF = instance.previous?.('customFields');\n if (prevCF !== undefined) {\n beforeFull.customFields = prevCF;\n }\n\n return beforeFull;\n};\n\nconst formatAjvErrors = (\n errors: {\n instancePath?: string;\n keyword: string;\n message?: string;\n params?: Record<string, any>;\n }[],\n): Record<string, string> => errors.reduce((acc, err) => {\n const basePath = (err.instancePath || '')\n .split('/')\n .filter(Boolean)\n .join('.')\n .replace(/^after\\./, '');\n\n const missingProp = err.keyword === 'required' ? `.${err.params?.missingProperty}` : '';\n const key = (basePath + missingProp).replace(/^\\./, '') || 'root';\n\n const message = err.message || 'Invalid value';\n acc[key] = message;\n\n return acc;\n}, {} as Record<string, string>);\n\n/**\n * Validates the model using custom validators\n */\nconst validateModel = async (\n instance: any,\n options: TransactionOptions,\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n isCreate = false,\n): Promise<void> => {\n const modelType = instance.constructor.name;\n\n logger.debug('sadot - validating model', { isCreate, modelType });\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n logger.debug('sadot - identifiers', { identifiers });\n\n // Skip if no identifiers\n if (!identifiers || Object.keys(identifiers).length === 0) {\n logger.debug('sadot - skipping validation: no identifiers');\n return;\n }\n\n // Find the entityId from identifiers (fleetId, businessModelId, etc.)\n const entityId = Object.values(identifiers)[0]; // Get the first value as entityId\n\n logger.debug('sadot - entityId', { entityId });\n\n if (!entityId) {\n logger.debug('sadot - skipping validation: no entityId');\n return;\n }\n\n let validatorsPromise;\n let cacheKey: string | undefined;\n if (options.transaction) {\n options.transaction.validationsCache ??= new Map();\n cacheKey = `${modelType}-${entityId}`;\n validatorsPromise = options.transaction.validationsCache.get(cacheKey);\n }\n\n if (!validatorsPromise) {\n validatorsPromise = ValidatorRepo.findAllByModelType(\n modelType,\n entityId,\n {\n transaction: options.transaction,\n attributes: CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL,\n modelOptions,\n },\n );\n if (options.transaction) {\n options?.transaction?.validationsCache!.set(cacheKey!, validatorsPromise);\n }\n }\n const validators = await validatorsPromise;\n\n logger.debug('sadot - validators found', { count: validators.length });\n\n if (!validators.length) {\n logger.debug('sadot - skipping validation: no validators found');\n return;\n }\n\n // For updates, get the previous values\n let originalValues = null;\n if (!isCreate) {\n originalValues = buildPreChangeState(instance);\n }\n\n // Get complete custom fields by merging DB values with update values\n // This is especially important for partial updates to ensure all related fields are available\n const completeCustomFields = !isCreate\n ? await getCompleteCustomFields(instance, options)\n : instance.customFields || {};\n\n for (const validator of validators) {\n const { schema } = validator;\n const typedSchema = schema as Record<string, any>;\n\n logger.debug('sadot - validating with schema', {\n schema,\n hasAfterProps: !!typedSchema.properties?.after,\n hasBeforeProps: !!typedSchema.properties?.before,\n });\n\n if (isCreate) {\n // For create operations, we only need the 'after' state\n if (typedSchema.properties?.after) {\n const validateSchema = ajv.compile({\n ...schema,\n // Focus only on the 'after' validation part for create\n properties: {\n after: typedSchema.properties.after,\n },\n });\n\n const isValid = validateSchema(JSON.parse(JSON.stringify({\n after: {\n ...instance.dataValues,\n customFields: completeCustomFields,\n },\n })));\n\n if (!isValid) {\n const errorDetails = validateSchema.errors?.map(err =>\n `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors!);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n } else {\n // For update operations, we need both before and after\n const validateSchema = ajv.compile(typedSchema);\n\n // Create after object with our helper function\n const afterObj = manualObjectCopy(instance.dataValues);\n\n // Add complete custom fields\n afterObj.customFields = completeCustomFields;\n\n // Create validation payload\n const payload = {\n before: originalValues,\n after: afterObj,\n };\n\n // Validate\n const isValid = validateSchema(JSON.parse(JSON.stringify(payload)));\n\n logger.debug('sadot - validation result', {\n isValid,\n test: {\n before: originalValues,\n after: afterObj,\n },\n });\n\n if (!isValid) {\n const errorDetails = validateSchema\n .errors\n ?.map(err => `${(err as any).instancePath || ''} ${(err as any).message || 'Invalid value'}`).join(', ');\n\n const formattedErrors = formatAjvErrors(validateSchema.errors!);\n throw new BadRequest(\n [new Error(`Validation failed for ${modelType}: ${errorDetails}`)],\n undefined,\n {\n customError: formattedErrors,\n },\n );\n }\n }\n }\n};\n\nconst getFieldDefinitions = async ({\n modelType,\n modelOptions,\n identifiers,\n options,\n}: {\n modelType: any;\n modelOptions: ModelOptions;\n identifiers: any[];\n options: any;\n}) => {\n const { include, useEntityIdFromInclude } = modelOptions;\n const where: WhereOptions = {\n modelType,\n disabled: false,\n ...(!useEntityIdFromInclude && { entityId: identifiers }),\n };\n\n const fieldDefinitions = await DefinitionRepo.findAll(where, {\n withDisabled: false,\n transaction: options.transaction,\n include: include?.(identifiers),\n });\n return fieldDefinitions;\n};\n\nconst formatDates = (fieldDefinitions: CustomFieldDefinition[], instance: any) => {\n (fieldDefinitions || []).forEach((fieldDefinition) => {\n const { fieldType, name } = fieldDefinition;\n if ([CustomFieldDefinitionType.DATE, CustomFieldDefinitionType.DATETIME].includes(fieldType)) {\n const value = instance.customFields?.[name];\n if (value) {\n const { value: joiValue, error: validationError } = Joi.date().validate(value);\n if (validationError) {\n throw new InvalidValueError(value, name, validationError);\n }\n instance.customFields[name] = joiValue.toISOString();\n }\n }\n });\n};\n\n/**\n * Hook to handle validation and custom fields during creation\n */\nexport const beforeCreate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instance: any,\n options: CreateOptions,\n): Promise<void> => {\n logger.debug('sadot - before create hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n // Step 1: Handle custom fields default values and required fields\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options,\n });\n\n // Apply default values\n const fieldsWithDefaultValue = fieldDefinitions.filter(def => ![null, undefined].includes(def.defaultValue));\n if (fieldsWithDefaultValue.length) {\n instance.customFields ||= {};\n fieldsWithDefaultValue\n .filter(def => (instance.customFields?.[def.name] === undefined))\n .forEach(({ name, defaultValue }) => {\n instance.customFields[name] = defaultValue;\n });\n }\n\n // Check for required fields\n const requiredFieldsNames = Array.from(\n new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)),\n );\n const { customFields } = instance;\n const fieldsNames = Object.keys(customFields ?? {});\n const missingFields = requiredFieldsNames.filter(name => !fieldsNames.includes(name));\n if (missingFields?.length) {\n throw new MissingRequiredCustomFieldError(missingFields);\n }\n\n // Step 2: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, scopeAttributes, modelOptions, true);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 3: Save custom field values if they exist\n const customFieldsIdx = fields!.indexOf('customFields');\n if (customFieldsIdx === -1 || !customFields || !Object.keys(customFields).length) {\n // No custom fields to update\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n fields!.splice(customFieldsIdx, 1);\n};\n\n/**\n * Hook to handle validation and custom fields during update\n */\nexport const beforeUpdate = (\n scopeAttributes: string[],\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instance: any,\n options: UpdateOptions,\n): Promise<void> => {\n logger.debug('sadot - before update hook');\n const { fields } = options;\n const modelType = instance.constructor.name;\n const identifiers = applyScopeToInstance(instance, scopeAttributes);\n\n const fieldDefinitions = await getFieldDefinitions({\n modelType, modelOptions, identifiers, options,\n });\n\n // Step 1: Validate the model data (including custom fields)\n await validateModel(instance, options as TransactionOptions, scopeAttributes, modelOptions, false);\n\n // format date and datetime fields\n formatDates(fieldDefinitions, instance);\n\n // Step 2: Update custom field values if they exist\n const customFieldsIdx = fields!.indexOf('customFields');\n if (customFieldsIdx > -1) {\n const { customFields } = instance;\n\n if (!Object.keys(customFields).length) {\n return;\n }\n\n // Save custom field values\n await updateInstanceValues({\n modelId: instance.id,\n modelType,\n identifiers,\n customFields,\n options: {\n useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,\n transaction: options.transaction,\n modelOptions,\n },\n });\n\n // Remove customFields from fields array after handling\n fields!.splice(customFieldsIdx, 1);\n }\n};\n\n/**\n * Hook to enable individual hooks for bulk create operations\n */\nexport const beforeBulkCreate = (options: BulkCreateOptions): void => {\n // This will activate the beforeCreate hook on each instance\n options.individualHooks = true;\n};\n\n/**\n * Hook to enable individual hooks for bulk update operations\n */\nexport const beforeBulkUpdate = (options: UpdateOptions): void => {\n // This will activate the beforeUpdate hook on each instance\n options.individualHooks = true;\n};\n"],"mappings":"siBAmBA,MAAM,EAAsC,CAAC,KAAM,SAAU,YAAa,WAAY,WAAW,CAG3F,EAAM,IAAI,EAAI,CAClB,UAAW,GACX,OAAQ,GACR,YAAa,GACb,MAAO,GACR,CAAC,CAEF,EAAW,EAAI,CACf,EAAU,EAAI,CAMd,MAAM,GAAoB,EAAgC,KACvD,CAAE,UAAW,KAAM,GAAG,EAAW,GAAG,EAAiB,EAMlD,EAA0B,MAAO,EAAe,IAA2D,CAE/G,GAAI,CAAC,EAAS,IAAM,CAAC,EAAS,cAAgB,OAAO,KAAK,EAAS,aAAa,CAAC,SAAW,EAC1F,OAAO,EAAS,cAAgB,EAAE,CAGpC,GAAI,CAGF,IAAM,EAAsB,MAFT,EAAS,YAEiB,QAAQ,CACnD,MAAO,CAAE,GAAI,EAAS,GAAI,CAC1B,WA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AAwB,EAAa,uBACrC,YAAa,EAAQ,YACrB,eACD,CACF,CAAC,CAGF,EAAQ,OAAO,EAAiB,EAAE,GAMvB,GACX,EACA,EAA6B,EAAE,CAC/B,EAAmE,CAAE,uBAAwB,GAAO,GACjG,MACH,EACA,IACkB,CAClB,EAAO,MAAM,6BAA6B,CAC1C,GAAM,CAAE,UAAW,EACb,EAAY,EAAS,YAAY,KACjC,EAAcL,EAAqB,EAAU,EAAgB,CAE7D,EAAmB,MAAM,EAAoB,CACjD,YAAW,eAAc,cAAa,UACvC,CAAC,CAGF,MAAM,EAAc,EAAU,EAA+B,EAAiB,EAAc,GAAM,CAGlG,EAAY,EAAkB,EAAS,CAGvC,IAAM,EAAkB,EAAQ,QAAQ,eAAe,CACvD,GAAI,EAAkB,GAAI,CACxB,GAAM,CAAE,gBAAiB,EAEzB,GAAI,CAAC,OAAO,KAAK,EAAa,CAAC,OAC7B,OAIF,MAAMK,EAAqB,CACzB,QAAS,EAAS,GAClB,YACA,cACA,eACA,QAAS,CACP,uBAAwB,EAAa,uBACrC,YAAa,EAAQ,YACrB,eACD,CACF,CAAC,CAGF,EAAQ,OAAO,EAAiB,EAAE,GAOzB,EAAoB,GAAqC,CAEpE,EAAQ,gBAAkB,IAMf,EAAoB,GAAiC,CAEhE,EAAQ,gBAAkB"}
|
package/dist/hooks/index.cjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
const e=require(`./enrich.cjs`),t=require(`./find.cjs`),n=require(`./hooks.cjs`);
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../../repository/value.cjs`),t=require(`../../repository/entries.cjs`),n=async({modelId:n,modelType:r,identifiers:i,customFields:a,options:o={modelOptions:{},useCustomFieldsEntries:!1}})=>{if(await e.updateValues(r,n,i,a,{...o,modelOptions:o.modelOptions??{}}),!o?.useCustomFieldsEntries)return;let{dataValues:{customFields:s}}=await t.findEntriesByModelId(n,o)??{dataValues:{}},c={...s,...a};await t.updateEntries(n,r,c,i,{...o,modelOptions:o.modelOptions??{}})};var r=n;exports.default=r;
|
|
2
|
-
//# sourceMappingURL=updateInstanceValues.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"updateInstanceValues.cjs","names":[],"sources":["../../../src/hooks/utils/updateInstanceValues.ts"],"sourcesContent":["import type { Transaction } from 'sequelize';\nimport * as ValueRepo from '../../repository/value';\nimport * as EntriesRepo from '../../repository/entries';\nimport type { ModelOptions } from '../../types';\n\ninterface UpdateInstanceValuesParams {\n modelId: string;\n modelType: string;\n identifiers: string[];\n customFields: Record<string, any>;\n options?: {\n transaction?: Transaction | null;\n modelOptions?: ModelOptions;\n useCustomFieldsEntries?: boolean;\n };\n}\n\nconst updateInstanceValues = async ({\n modelId,\n modelType,\n identifiers,\n customFields,\n options = {\n modelOptions: {},\n useCustomFieldsEntries: false,\n },\n}: UpdateInstanceValuesParams): Promise<void> => {\n await ValueRepo.updateValues(\n modelType,\n modelId,\n identifiers,\n customFields,\n {\n ...options,\n modelOptions: options.modelOptions ?? {},\n },\n );\n\n /*\n T.Y TODO - Once we're ready to switch from custom_field_values to custom_field_entries, we should remove the ValueRepo.updateValues call.\n Currently, We're updating both tables to keep the data in sync, but not all microservices are using the new table yet.\n */\n\n if (!options?.useCustomFieldsEntries) {\n return;\n }\n\n const { dataValues: { customFields: oldCustomFields } } = await EntriesRepo.findEntriesByModelId(modelId, options) ?? { dataValues: {} };\n const newCustomFields = { ...oldCustomFields, ...customFields };\n\n await EntriesRepo.updateEntries(\n modelId,\n modelType,\n newCustomFields,\n identifiers,\n {\n ...options,\n modelOptions: options.modelOptions ?? {},\n },\n );\n};\n\nexport default updateInstanceValues;\n"],"mappings":"wFAiBM,EAAuB,MAAO,CAClC,UACA,YACA,cACA,eACA,UAAU,CACR,aAAc,EAAE,CAChB,uBAAwB,GACzB,IAC8C,CAiB/C,GAhBA,MAAA,EAAA,aACE,EACA,EACA,EACA,EACA,CACE,GAAG,EACH,aAAc,EAAQ,cAAgB,EAAE,CACzC,CACF,CAOG,CAAC,GAAS,uBACZ,OAGF,GAAM,CAAE,WAAY,CAAE,aAAc,IAAsB,MAAA,EAAA,qBAAuC,EAAS,EAAQ,EAAI,CAAE,WAAY,EAAE,CAAE,CAClI,EAAkB,CAAE,GAAG,EAAiB,GAAG,EAAc,CAE/D,MAAA,EAAA,cACE,EACA,EACA,EACA,EACA,CACE,GAAG,EACH,aAAc,EAAQ,cAAgB,EAAE,CACzC,CACF,EAGH,IAAA,EAAe"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"updateInstanceValues.js","names":["ValueRepo.updateValues","EntriesRepo.findEntriesByModelId","EntriesRepo.updateEntries"],"sources":["../../../src/hooks/utils/updateInstanceValues.ts"],"sourcesContent":["import type { Transaction } from 'sequelize';\nimport * as ValueRepo from '../../repository/value';\nimport * as EntriesRepo from '../../repository/entries';\nimport type { ModelOptions } from '../../types';\n\ninterface UpdateInstanceValuesParams {\n modelId: string;\n modelType: string;\n identifiers: string[];\n customFields: Record<string, any>;\n options?: {\n transaction?: Transaction | null;\n modelOptions?: ModelOptions;\n useCustomFieldsEntries?: boolean;\n };\n}\n\nconst updateInstanceValues = async ({\n modelId,\n modelType,\n identifiers,\n customFields,\n options = {\n modelOptions: {},\n useCustomFieldsEntries: false,\n },\n}: UpdateInstanceValuesParams): Promise<void> => {\n await ValueRepo.updateValues(\n modelType,\n modelId,\n identifiers,\n customFields,\n {\n ...options,\n modelOptions: options.modelOptions ?? {},\n },\n );\n\n /*\n T.Y TODO - Once we're ready to switch from custom_field_values to custom_field_entries, we should remove the ValueRepo.updateValues call.\n Currently, We're updating both tables to keep the data in sync, but not all microservices are using the new table yet.\n */\n\n if (!options?.useCustomFieldsEntries) {\n return;\n }\n\n const { dataValues: { customFields: oldCustomFields } } = await EntriesRepo.findEntriesByModelId(modelId, options) ?? { dataValues: {} };\n const newCustomFields = { ...oldCustomFields, ...customFields };\n\n await EntriesRepo.updateEntries(\n modelId,\n modelType,\n newCustomFields,\n identifiers,\n {\n ...options,\n modelOptions: options.modelOptions ?? {},\n },\n );\n};\n\nexport default updateInstanceValues;\n"],"mappings":"+IA8DA,IAAA,EA7C6B,MAAO,CAClC,UACA,YACA,cACA,eACA,UAAU,CACR,aAAc,EAAE,CAChB,uBAAwB,GACzB,IAC8C,CAiB/C,GAhBA,MAAMA,EACJ,EACA,EACA,EACA,EACA,CACE,GAAG,EACH,aAAc,EAAQ,cAAgB,EAAE,CACzC,CACF,CAOG,CAAC,GAAS,uBACZ,OAGF,GAAM,CAAE,WAAY,CAAE,aAAc,IAAsB,MAAMC,EAAiC,EAAS,EAAQ,EAAI,CAAE,WAAY,EAAE,CAAE,CAGxI,MAAMC,EACJ,EACA,EAJsB,CAAE,GAAG,EAAiB,GAAG,EAAc,CAM7D,EACA,CACE,GAAG,EACH,aAAc,EAAQ,cAAgB,EAAE,CACzC,CACF"}
|
package/dist/index.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
Object.defineProperty(exports,`__esModule`,{value:!0});const e=require(`./utils/logger/index.cjs`),t=require(`./utils/constants/index.cjs`),n=require(`./models/CustomFieldValue.cjs`),r=require(`./models/CustomFieldDefinition.cjs`),i=require(`./models/CustomFieldEntries.cjs`),a=require(`./models/CustomValidator.cjs`),o=require(`./models/index.cjs`),s=require(`./api/index.cjs`),c=require(`./utils/db/index.cjs`),l=require(`./utils/helpers/index.cjs`),u=require(`./scopes/filter.cjs`),d=require(`./utils/init.cjs`),f=require(`./utils/validations/schema/custom-fields.cjs`),p=async(t,n,r)=>{e.tryAddingTraceIdMiddleware();let{models:i,useCustomFieldsEntries:a,useModelTypeMapping:l}=r;t&&t.use(`/api`,s.default);let u=r.sequelize??c.default(r.databaseConfig);return process.env.NODE_ENV===`test`&&await o.initTestModels(u),d.addHooks(i,n,{useCustomFieldsEntries:a}),await o.initTables(u,r.getUser,{useCustomFieldsEntries:a,useModelTypeMapping:l}),d.addScopes(i,n,{useCustomFieldsEntries:a}),d.applyCustomAssociation(i),e.default.debug(`sadot - custom fields finished initializing with models`,i),u};var m=p;const h=(e,t)=>{d.removeHooks(e,t)};exports.CUSTOM_FIELDS_FILTER_SCOPE=t.CUSTOM_FIELDS_FILTER_SCOPE,exports.CustomFieldDefinition=r,exports.CustomFieldDefinitionType=t.CustomFieldDefinitionType,exports.CustomFieldEntries=i,exports.CustomFieldValue=n,exports.CustomFieldsSchema=f.CustomFieldsSchema,exports.CustomValidator=a,exports.customFieldsSortScope=u.customFieldsSortScope,exports.default=m,exports.disableCustomFields=h,exports.generateCustomFieldSearchQueryPayload=l.generateCustomFieldSearchQueryPayload,exports.generateRandomString=l.generateRandomString,exports.supportedEntities=t.supportedEntities;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["api","initDB","initTestModels","initTables"],"sources":["../src/index.ts"],"sourcesContent":["import type { Application } from 'express';\nimport type { Sequelize } from 'sequelize-typescript';\nimport {\n initTables, initTestModels,\n} from './models';\nimport api from './api';\nimport initDB from './utils/db';\nimport logger, { tryAddingTraceIdMiddleware } from './utils/logger';\nimport type { CustomFieldOptions, ModelFetcher, Models } from './types';\nimport {\n addHooks, addScopes, applyCustomAssociation, removeHooks,\n} from './utils/init';\n\nexport * from './utils/validations/schema/custom-fields';\n\nexport * from './utils/constants';\n\nexport * from './utils/helpers';\n\nexport { customFieldsSortScope } from './scopes/filter';\nexport {\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomFieldValue,\n CustomValidator,\n} from './models';\n\n/**\n * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file\n * @see {@link 'custom-fields/config'} for configurations\n */\nconst useCustomFields = async (\n app: Pick<Application, 'use'> | null,\n getModel: ModelFetcher,\n options: CustomFieldOptions,\n): Promise<Sequelize> => {\n tryAddingTraceIdMiddleware();\n const { models, useCustomFieldsEntries, useModelTypeMapping } = options;\n if (app) {\n app.use('/api', api);\n }\n const sequelize = options.sequelize ?? initDB(options.databaseConfig);\n if (process.env.NODE_ENV === 'test') {\n await initTestModels(sequelize);\n }\n // The order is important\n addHooks(models, getModel, { useCustomFieldsEntries });\n await initTables(sequelize, options.getUser, { useCustomFieldsEntries, useModelTypeMapping });\n addScopes(models, getModel, { useCustomFieldsEntries });\n applyCustomAssociation(models);\n\n logger.debug('sadot - custom fields finished initializing with models', models);\n return sequelize;\n};\n\nexport default useCustomFields;\n\nexport const disableCustomFields = (models: Models[], getModel: ModelFetcher): void => {\n removeHooks(models, getModel);\n};\n"],"mappings":"6jBA+BM,EAAkB,MACtB,EACA,EACA,IACuB,CACvB,EAAA,4BAA4B,CAC5B,GAAM,CAAE,SAAQ,yBAAwB,uBAAwB,EAC5D,GACF,EAAI,IAAI,OAAQA,EAAAA,QAAI,CAEtB,IAAM,EAAY,EAAQ,WAAaC,EAAAA,QAAO,EAAQ,eAAe,CAWrE,OAVI,QAAQ,IAAI,WAAa,QAC3B,MAAMC,EAAAA,eAAe,EAAU,CAGjC,EAAA,SAAS,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACtD,MAAMC,EAAAA,WAAW,EAAW,EAAQ,QAAS,CAAE,yBAAwB,sBAAqB,CAAC,CAC7F,EAAA,UAAU,EAAQ,EAAU,CAAE,yBAAwB,CAAC,CACvD,EAAA,uBAAuB,EAAO,CAE9B,EAAA,QAAO,MAAM,0DAA2D,EAAO,CACxE,GAGT,IAAA,EAAe,EAEf,MAAa,GAAuB,EAAkB,IAAiC,CACrF,EAAA,YAAY,EAAQ,EAAS"}
|