@autofleet/sadot 1.1.6 → 1.1.7-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 -29
- 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 -20
- 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 -6
- 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 +28 -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 -45
- 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 +38 -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 +479 -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 +119 -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 -31
- 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/CustomFieldValue.cjs +0 -2
- package/dist/models/CustomFieldValue.cjs.map +0 -1
- package/dist/models/CustomFieldValue.d.cts +0 -22
- 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 -6
- 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 -45
- 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
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import Ajv from 'ajv';
|
|
2
|
+
import addFormats from 'ajv-formats';
|
|
3
|
+
import { BadRequest } from '@autofleet/errors';
|
|
4
|
+
import logger from '../../logger';
|
|
5
|
+
|
|
6
|
+
// Instantiate Ajv for meta-validation
|
|
7
|
+
const metaValidator = new Ajv({
|
|
8
|
+
allErrors: true,
|
|
9
|
+
strict: false,
|
|
10
|
+
strictTypes: false,
|
|
11
|
+
$data: true, // Enable $data references
|
|
12
|
+
});
|
|
13
|
+
addFormats(metaValidator);
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Schema for validating JSON Schema objects in custom validators
|
|
17
|
+
* This is a meta-schema to ensure that custom validator schemas are valid Ajv schemas
|
|
18
|
+
*/
|
|
19
|
+
const validatorMetaSchema = {
|
|
20
|
+
type: 'object',
|
|
21
|
+
properties: {
|
|
22
|
+
type: { type: 'string', enum: ['object'] },
|
|
23
|
+
properties: {
|
|
24
|
+
type: 'object',
|
|
25
|
+
properties: {
|
|
26
|
+
before: {
|
|
27
|
+
type: 'object',
|
|
28
|
+
properties: {
|
|
29
|
+
type: { type: 'string', enum: ['object'] },
|
|
30
|
+
properties: { type: 'object' },
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
after: {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
type: { type: 'string', enum: ['object'] },
|
|
37
|
+
properties: { type: 'object' },
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
},
|
|
42
|
+
required: {
|
|
43
|
+
type: 'array',
|
|
44
|
+
items: { type: 'string' },
|
|
45
|
+
},
|
|
46
|
+
if: { type: 'object' },
|
|
47
|
+
then: { type: 'object' },
|
|
48
|
+
else: { type: 'object' },
|
|
49
|
+
},
|
|
50
|
+
required: ['type', 'properties'],
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Validates that a given schema is a valid Ajv schema
|
|
55
|
+
* This function is used to validate schemas passed to custom validators
|
|
56
|
+
*
|
|
57
|
+
* @param schema The schema to validate
|
|
58
|
+
* @returns true if valid, throws an error if invalid
|
|
59
|
+
*/
|
|
60
|
+
export const validateValidatorSchema = (schema: Record<string, unknown>): boolean => {
|
|
61
|
+
try {
|
|
62
|
+
// First validate the schema structure
|
|
63
|
+
const validateMetaSchema = metaValidator.compile(validatorMetaSchema);
|
|
64
|
+
const isValidStructure = validateMetaSchema(schema);
|
|
65
|
+
|
|
66
|
+
if (!isValidStructure) {
|
|
67
|
+
const errorDetails = validateMetaSchema.errors?.map((err) =>
|
|
68
|
+
`${(err as unknown as { instancePath: string }).instancePath || ''} ${(err as unknown as { message: string }).message || 'Invalid schema structure'}`).join(', ');
|
|
69
|
+
|
|
70
|
+
logger.error('Invalid validator schema structure', {
|
|
71
|
+
errors: validateMetaSchema.errors,
|
|
72
|
+
schema,
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
throw new BadRequest(
|
|
76
|
+
[new Error(`Invalid validator schema structure: ${errorDetails}`)],
|
|
77
|
+
['Invalid validator schema structure'],
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Then try to compile the schema with Ajv to verify it's a valid JSON Schema
|
|
82
|
+
try {
|
|
83
|
+
metaValidator.compile(schema);
|
|
84
|
+
return true;
|
|
85
|
+
} catch (compileError) {
|
|
86
|
+
logger.error('Failed to compile validator schema', { error: compileError, schema });
|
|
87
|
+
|
|
88
|
+
throw new BadRequest(
|
|
89
|
+
[new Error(`Failed to compile validator schema: ${(compileError as Error).message}`)],
|
|
90
|
+
['Invalid validator schema'],
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error instanceof BadRequest) {
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
logger.error('Error validating validator schema', { error, schema });
|
|
99
|
+
throw new BadRequest(
|
|
100
|
+
[new Error(`Error validating validator schema: ${(error as Error).message}`)],
|
|
101
|
+
['Invalid validator schema'],
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
export default validateValidatorSchema;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ValidationResult } from 'joi';
|
|
2
|
+
import type { CustomFieldDefinitionType } from '../constants';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Validator is a function that validates a custom-field `value`,
|
|
6
|
+
* against a custom-field definition `validation object`.
|
|
7
|
+
* @returns `true` if the value is valid, `false` otherwise.
|
|
8
|
+
*/
|
|
9
|
+
export type Validator<Value, DefinitionValidationObject> = (
|
|
10
|
+
value: Value,
|
|
11
|
+
validation?: DefinitionValidationObject
|
|
12
|
+
) => ValidationResult;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Validators is a map of custom-field types to their respective validators.
|
|
16
|
+
* The key is the custom-field type, and the value is the validator function.
|
|
17
|
+
*/
|
|
18
|
+
export type Validators = {
|
|
19
|
+
[K in CustomFieldDefinitionType]: Validator<unknown, unknown>;
|
|
20
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import Joi from 'joi';
|
|
2
|
+
import { CustomFieldDefinitionType } from '../../constants';
|
|
3
|
+
import type { Validators } from '../type';
|
|
4
|
+
import { validateSelect } from './select.validator';
|
|
5
|
+
import { validateStatus } from './status.validator';
|
|
6
|
+
|
|
7
|
+
type CustomValidationTypes = Extract<CustomFieldDefinitionType, 'select' | 'status'>;
|
|
8
|
+
/**
|
|
9
|
+
* Custom field types that must have custom validation.
|
|
10
|
+
* TODO: remove this after moving to schema-based validation
|
|
11
|
+
*/
|
|
12
|
+
export const CustomValidationTypes = {
|
|
13
|
+
[CustomFieldDefinitionType.SELECT]: CustomFieldDefinitionType.SELECT,
|
|
14
|
+
[CustomFieldDefinitionType.STATUS]: CustomFieldDefinitionType.STATUS,
|
|
15
|
+
} as const;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Validators for custom fields
|
|
19
|
+
*/
|
|
20
|
+
export const validators: Validators = {
|
|
21
|
+
[CustomFieldDefinitionType.SELECT]: validateSelect,
|
|
22
|
+
[CustomFieldDefinitionType.STATUS]: validateStatus,
|
|
23
|
+
[CustomFieldDefinitionType.TEXT]: (value) => Joi.string().min(0).validate(value),
|
|
24
|
+
[CustomFieldDefinitionType.NUMBER]: (value) => Joi.number().strict(true).validate(value),
|
|
25
|
+
[CustomFieldDefinitionType.BOOLEAN]: (value) => Joi.boolean().strict().validate(value),
|
|
26
|
+
[CustomFieldDefinitionType.DATE]: (value) => Joi.date().validate(value),
|
|
27
|
+
[CustomFieldDefinitionType.DATETIME]: (value) => Joi.date().validate(value),
|
|
28
|
+
[CustomFieldDefinitionType.IMAGE]: (value) => Joi.array().min(1).unique()
|
|
29
|
+
.items(Joi.string().uri())
|
|
30
|
+
.validate(value),
|
|
31
|
+
[CustomFieldDefinitionType.FILE]: (value) => Joi.array().min(1).unique().items(Joi.object({
|
|
32
|
+
name: Joi.string().required(),
|
|
33
|
+
type: Joi.string(),
|
|
34
|
+
size: Joi.string(),
|
|
35
|
+
addedBy: Joi.string().uuid(),
|
|
36
|
+
}))
|
|
37
|
+
.validate(value),
|
|
38
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import Joi from 'joi';
|
|
2
|
+
import type { Validator } from '../type';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Validate that the value is one of the select values
|
|
6
|
+
*/
|
|
7
|
+
export const validateSelect: Validator<string, string[]> = (
|
|
8
|
+
value,
|
|
9
|
+
selectValues,
|
|
10
|
+
) => (
|
|
11
|
+
Joi.string().allow(null).valid(...selectValues).validate(value)
|
|
12
|
+
);
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import Joi from 'joi';
|
|
2
|
+
import type { Validator } from '../type';
|
|
3
|
+
|
|
4
|
+
type StatusColor = string | null; // TODO: Takes from @autofleet/colors ?
|
|
5
|
+
type StatusValue = string;
|
|
6
|
+
type StatusOption = {
|
|
7
|
+
value: StatusValue;
|
|
8
|
+
color: StatusColor;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Validate that the value is one of the status values
|
|
13
|
+
*/
|
|
14
|
+
export const validateStatus: Validator<StatusValue, StatusOption[]> = (
|
|
15
|
+
value,
|
|
16
|
+
statusValues,
|
|
17
|
+
) => (
|
|
18
|
+
Joi.string()
|
|
19
|
+
.allow(null)
|
|
20
|
+
.valid(...statusValues.map((statusValue) => statusValue.value))
|
|
21
|
+
.validate(value)
|
|
22
|
+
);
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "es2020",
|
|
4
|
+
"module": "commonjs",
|
|
5
|
+
"declaration": true,
|
|
6
|
+
"outDir": "./dist",
|
|
7
|
+
"esModuleInterop": true,
|
|
8
|
+
"experimentalDecorators": true,
|
|
9
|
+
"emitDecoratorMetadata": true,
|
|
10
|
+
"allowJs": true
|
|
11
|
+
},
|
|
12
|
+
"include": [
|
|
13
|
+
"src/**/*",
|
|
14
|
+
],
|
|
15
|
+
"exclude": ["node_modules"]
|
|
16
|
+
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}exports.__decorate=e;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}export{e as __decorate};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}exports.__decorateMetadata=e;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function e(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}export{e as __decorateMetadata};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));exports.__toESM=s;
|
package/dist/api/index.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./v1/index.cjs`);let r=require(`@autofleet/node-common`);const i=(0,r.Router)({logger:t.default});i.use(`/v1`,n.default);var a=i;exports.default=a;
|
|
2
|
-
//# sourceMappingURL=index.cjs.map
|
package/dist/api/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","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":"+JAKA,MAAMA,GAAAA,EAAAA,EAAAA,QAA2C,CAAE,OAAA,EAAA,QAAQ,CAAC,CAE5D,EAAO,IAAI,MAAOC,EAAAA,QAAG,CAErB,IAAA,EAAe"}
|
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}}=e,s=l(a);try{let e={modelType:s,...o&&o.length>0&&{entityId:o}},t=await n.findAll(e,{withDisabled:!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","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[]; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: 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,EAAwB,CAEpF,GAAI,CAAC,EACH,MAAM,IAAIC,EAAAA,sBAGZ,OAAO,EAAI,KAAK,EAAsB,OAC/B,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,0CAA2C,EAAI,CACrDD,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,QAAS,gBAAgB,EAAO,UAAW,CAAC,GAE9F,CAKF,EAAO,IAAuF,IAAK,MAAO,EAAK,IAAQ,CACrH,GAAM,CAAE,OAAQ,CAAE,aAAa,MAAO,CAAE,cAAgB,EAElD,EAAY,EAAa,EAAU,CACzC,GAAI,CACF,IAAM,EAAQ,CACZ,YACA,GAAI,GAAa,EAAU,OAAS,GAAK,CAAE,SAAU,EAAW,CACjE,CACK,EAAyB,MAAA,EAAA,QAA6B,EAAO,CAAE,aAAc,GAAM,CAAC,CAC1F,OAAO,EAAI,KAAK,EAAuB,OAChC,EAAK,CAEZ,OADA,EAAA,QAAO,MAAM,2CAA4C,EAAI,CACtDA,EAAAA,QAAY,EAAc,EAAK,CAAE,OAAA,EAAA,QAAQ,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,IAAME,EAAgD,MAAMC,EAAAA,oCAAoC,EAAI,KAAK,CAOzG,GAAI,CAL0B,MAAA,EAAA,YAAiC,CAC7D,GAAI,EACJ,YACD,CAAC,CAGA,MAAM,IAAIF,EAAAA,sBAGZ,IAAM,EAA+B,MAAA,EAAA,OACnC,EACA,CAAE,GAAG,EAAkB,YAAW,CACnC,CAED,OAAO,EAAI,OAAO,IAAI,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","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[]; }>('/', async (req, res) => {\n const { params: { modelName }, query: { entityIds } } = req;\n\n const modelType = toPascalCase(modelName);\n try {\n const where = {\n modelType,\n ...(entityIds && entityIds.length > 0 && { entityId: entityIds }),\n };\n const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: 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":"yZASA,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,IAA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AAO,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()}).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()}).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}).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}).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,C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,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"}
|
|
@@ -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}).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}).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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AAI,QAAQ,CAAC,MAAM,GAAG,OAAO,OAAO,EAA0B,CAAC,CAAC,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,CAClC,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,CAClC,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();\n } catch (err) {\n return handleError(err as Error, res, { logger, message: `Error in delete ${ENTITY} request` });\n }\n});\n\nexport default router;\n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AK,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});\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),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_DEFINITION';\n }\n}\n"],"mappings":"+CAIA,IAAa,EAAb,cAAqD,CAAW,CAC9D,YAAY,E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AC,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})=>async(d,f)=>{if(f.originalAttributes?.length>0&&!f.originalAttributes?.includes?.(`customFields`))return;let p=Array.isArray(d)?d:[d];p=p.filter(Boolean);let m=r.default(p,n),h=[...new Set(m)].filter(Boolean),g=h.reduce((e,t)=>({...e,[t]:[]}),{}),_,v;f.transaction&&(f.transaction.definitionCache??=new Map,v=`${t}:${h.slice().sort().join(`,`)}`,_=f.transaction.definitionCache.get(v)),_||(_=e.findByEntityIds(t,h,{transaction:f.transaction,modelOptions:l,attributes:i}),f.transaction?.definitionCache?.set(v,_));let y=await _;if(y.length===0){p.forEach(e=>{e.customFields={}});return}l?.include&&l.useEntityIdFromInclude&&l.include(m).forEach(({model:e})=>{y.forEach(t=>{let n=t[`${e.name}.entityId`];g[n]=[]})});let b=y.reduce((e,t)=>({...e,[t.id]:t}),{});y.forEach(e=>{g[e.entityId].push(e)});let x=p.map(e=>e.id),[S,C]=await Promise.all([o({instancesIds:x,options:f,sadotOptions:u}),a({instancesIds:x,options:f,sadotOptions:u})]);p.forEach(e=>{let{id:t}=e,r=S[t],i=r?s(r,b):{},a=u.useCustomFieldsEntries?C[t]:i;n.forEach(t=>{let n=g[e[t]];n&&n.length>0&&n.forEach(e=>{a[e.name]===void 0&&(a[e.name]=null)})}),e.customFields=a,f.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),c===`afterFind`&&e?.changed?.(`customFields`,!1)})};var l=c;exports.default=l;
|
|
2
|
-
//# sourceMappingURL=enrich.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"enrich.cjs","names":["applyScopeToInstance","cacheKey: string | undefined"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"sKAUM,EAA6C,CACjD,KACA,OACA,WACA,YACA,cACA,aACA,aACA,YACA,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AS,GAAc,CAGrC,IAAM,EAA+B,EAFlB,EAAS,IAGxB,GAAgC,EAA6B,OAAS,GACxE,EAA6B,QAAS,GAA0B,CAC1D,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","DefinitionRepo.findByEntityIds"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'> = { useCustomFieldsEntries: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n if (!customFieldDefinitionsPromise) {\n // Fetch from database (either first time in this transaction or no transaction)\n customFieldDefinitionsPromise = DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction: options.transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd) => {\n const entityId = cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd) => {\n identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);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