@autofleet/sadot 1.6.18-beta.7 → 1.6.18
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/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.cjs +1 -11
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorate.js +1 -10
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.cjs +1 -8
- package/dist/_virtual/_@oxc-project_runtime@0.103.0/helpers/decorateMetadata.js +1 -7
- package/dist/_virtual/rolldown_runtime.cjs +1 -43
- package/dist/_virtual/rolldown_runtime.js +1 -21
- package/dist/api/index.cjs +2 -12
- package/dist/api/index.cjs.map +1 -0
- package/dist/api/index.js +2 -11
- package/dist/api/index.js.map +1 -0
- package/dist/api/v1/definition/index.cjs +2 -113
- package/dist/api/v1/definition/index.cjs.map +1 -0
- package/dist/api/v1/definition/index.js +2 -112
- package/dist/api/v1/definition/index.js.map +1 -0
- package/dist/api/v1/definition/validations.cjs +2 -128
- package/dist/api/v1/definition/validations.cjs.map +1 -0
- package/dist/api/v1/definition/validations.js +2 -125
- package/dist/api/v1/definition/validations.js.map +1 -0
- package/dist/api/v1/errors.cjs +2 -14
- package/dist/api/v1/errors.cjs.map +1 -0
- package/dist/api/v1/errors.js +2 -13
- package/dist/api/v1/errors.js.map +1 -0
- package/dist/api/v1/index.cjs +2 -16
- package/dist/api/v1/index.cjs.map +1 -0
- package/dist/api/v1/index.js +2 -15
- package/dist/api/v1/index.js.map +1 -0
- package/dist/api/v1/validator/index.cjs +2 -115
- package/dist/api/v1/validator/index.cjs.map +1 -0
- package/dist/api/v1/validator/index.js +2 -114
- package/dist/api/v1/validator/index.js.map +1 -0
- package/dist/api/v1/validator/validations.cjs +2 -40
- package/dist/api/v1/validator/validations.cjs.map +1 -0
- package/dist/api/v1/validator/validations.d.cts +2 -1
- package/dist/api/v1/validator/validations.d.ts +2 -1
- package/dist/api/v1/validator/validations.js +2 -38
- package/dist/api/v1/validator/validations.js.map +1 -0
- package/dist/errors/index.cjs +3 -62
- package/dist/errors/index.cjs.map +1 -0
- package/dist/errors/index.js +3 -55
- package/dist/errors/index.js.map +1 -0
- package/dist/events/index.cjs +2 -52
- package/dist/events/index.cjs.map +1 -0
- package/dist/events/index.js +2 -50
- package/dist/events/index.js.map +1 -0
- package/dist/hooks/enrich.cjs +2 -175
- package/dist/hooks/enrich.cjs.map +1 -0
- package/dist/hooks/enrich.js +2 -175
- package/dist/hooks/enrich.js.map +1 -0
- package/dist/hooks/find.cjs +2 -22
- package/dist/hooks/find.cjs.map +1 -0
- package/dist/hooks/find.js +2 -22
- package/dist/hooks/find.js.map +1 -0
- package/dist/hooks/hooks.cjs +2 -310
- package/dist/hooks/hooks.cjs.map +1 -0
- package/dist/hooks/hooks.js +2 -302
- package/dist/hooks/hooks.js.map +1 -0
- package/dist/hooks/index.cjs +1 -3
- package/dist/hooks/index.js +1 -5
- package/dist/hooks/utils/updateInstanceValues.cjs +2 -27
- package/dist/hooks/utils/updateInstanceValues.cjs.map +1 -0
- package/dist/hooks/utils/updateInstanceValues.js +2 -27
- package/dist/hooks/utils/updateInstanceValues.js.map +1 -0
- package/dist/index.cjs +2 -83
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +2 -3
- package/dist/index.js +2 -62
- package/dist/index.js.map +1 -0
- package/dist/init-state.cjs +2 -56
- package/dist/init-state.cjs.map +1 -0
- package/dist/init-state.d.cts +2 -1
- package/dist/init-state.d.ts +2 -1
- package/dist/init-state.js +2 -55
- package/dist/init-state.js.map +1 -0
- package/dist/mat-path-state.cjs +2 -10
- package/dist/mat-path-state.cjs.map +1 -0
- package/dist/mat-path-state.js +2 -9
- package/dist/mat-path-state.js.map +1 -0
- package/dist/migrations/001-create-core-tables.cjs +7 -25
- package/dist/migrations/001-create-core-tables.cjs.map +1 -0
- package/dist/migrations/001-create-core-tables.js +7 -23
- package/dist/migrations/001-create-core-tables.js.map +1 -0
- package/dist/migrations/002-create-custom-field-entries.cjs +4 -16
- package/dist/migrations/002-create-custom-field-entries.cjs.map +1 -0
- package/dist/migrations/002-create-custom-field-entries.js +4 -14
- package/dist/migrations/002-create-custom-field-entries.js.map +1 -0
- package/dist/migrations/003-create-custom-field-model-type-map.cjs +6 -20
- package/dist/migrations/003-create-custom-field-model-type-map.cjs.map +1 -0
- package/dist/migrations/003-create-custom-field-model-type-map.js +6 -18
- package/dist/migrations/003-create-custom-field-model-type-map.js.map +1 -0
- package/dist/migrations/index.cjs +2 -88
- package/dist/migrations/index.cjs.map +1 -0
- package/dist/migrations/index.js +2 -89
- package/dist/migrations/index.js.map +1 -0
- package/dist/models/CustomFieldDefinition.cjs +2 -147
- package/dist/models/CustomFieldDefinition.cjs.map +1 -0
- package/dist/models/CustomFieldDefinition.d.cts +2 -1
- package/dist/models/CustomFieldDefinition.d.ts +2 -1
- package/dist/models/CustomFieldDefinition.js +2 -146
- package/dist/models/CustomFieldDefinition.js.map +1 -0
- package/dist/models/CustomFieldEntries.cjs +2 -71
- package/dist/models/CustomFieldEntries.cjs.map +1 -0
- package/dist/models/CustomFieldEntries.d.cts +2 -1
- package/dist/models/CustomFieldEntries.d.ts +2 -1
- package/dist/models/CustomFieldEntries.js +2 -70
- package/dist/models/CustomFieldEntries.js.map +1 -0
- package/dist/models/CustomFieldModelTypeMap.cjs +2 -62
- package/dist/models/CustomFieldModelTypeMap.cjs.map +1 -0
- package/dist/models/CustomFieldModelTypeMap.d.cts +2 -1
- package/dist/models/CustomFieldModelTypeMap.d.ts +2 -1
- package/dist/models/CustomFieldModelTypeMap.js +2 -61
- package/dist/models/CustomFieldModelTypeMap.js.map +1 -0
- package/dist/models/CustomFieldValue.cjs +2 -109
- package/dist/models/CustomFieldValue.cjs.map +1 -0
- package/dist/models/CustomFieldValue.d.cts +2 -1
- package/dist/models/CustomFieldValue.d.ts +2 -1
- package/dist/models/CustomFieldValue.js +2 -108
- package/dist/models/CustomFieldValue.js.map +1 -0
- package/dist/models/CustomValidator.cjs +2 -68
- package/dist/models/CustomValidator.cjs.map +1 -0
- package/dist/models/CustomValidator.d.cts +2 -1
- package/dist/models/CustomValidator.d.ts +2 -1
- package/dist/models/CustomValidator.js +2 -67
- package/dist/models/CustomValidator.js.map +1 -0
- package/dist/models/index.cjs +2 -163
- package/dist/models/index.cjs.map +1 -0
- package/dist/models/index.d.cts +7 -0
- package/dist/models/index.d.ts +0 -4
- package/dist/models/index.js +2 -161
- package/dist/models/index.js.map +1 -0
- package/dist/models/tests/AssociatedTestModel.cjs +2 -51
- package/dist/models/tests/AssociatedTestModel.cjs.map +1 -0
- package/dist/models/tests/AssociatedTestModel.js +2 -50
- package/dist/models/tests/AssociatedTestModel.js.map +1 -0
- package/dist/models/tests/TestModel.cjs +2 -43
- package/dist/models/tests/TestModel.cjs.map +1 -0
- package/dist/models/tests/TestModel.js +2 -42
- package/dist/models/tests/TestModel.js.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs +2 -35
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.cjs.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +2 -34
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs +2 -33
- package/dist/models/tests/contextAwareModels/ContextTestModel.cjs.map +1 -0
- package/dist/models/tests/contextAwareModels/ContextTestModel.js +2 -32
- package/dist/models/tests/contextAwareModels/ContextTestModel.js.map +1 -0
- package/dist/repository/definition.cjs +2 -221
- package/dist/repository/definition.cjs.map +1 -0
- package/dist/repository/definition.js +2 -212
- package/dist/repository/definition.js.map +1 -0
- package/dist/repository/entries.cjs +2 -69
- package/dist/repository/entries.cjs.map +1 -0
- package/dist/repository/entries.js +2 -67
- package/dist/repository/entries.js.map +1 -0
- package/dist/repository/utils/formatValues.cjs +2 -14
- package/dist/repository/utils/formatValues.cjs.map +1 -0
- package/dist/repository/utils/formatValues.js +2 -14
- package/dist/repository/utils/formatValues.js.map +1 -0
- package/dist/repository/validator.cjs +2 -58
- package/dist/repository/validator.cjs.map +1 -0
- package/dist/repository/validator.js +2 -54
- package/dist/repository/validator.js.map +1 -0
- package/dist/repository/value.cjs +2 -77
- package/dist/repository/value.cjs.map +1 -0
- package/dist/repository/value.js +2 -76
- package/dist/repository/value.js.map +1 -0
- package/dist/scopes/filter.cjs +2 -56
- package/dist/scopes/filter.cjs.map +1 -0
- package/dist/scopes/filter.d.cts +2 -1
- package/dist/scopes/filter.d.ts +2 -1
- package/dist/scopes/filter.js +2 -54
- package/dist/scopes/filter.js.map +1 -0
- package/dist/scopes/helpers/filter.helpers.cjs +25 -131
- package/dist/scopes/helpers/filter.helpers.cjs.map +1 -0
- package/dist/scopes/helpers/filter.helpers.d.cts +2 -1
- package/dist/scopes/helpers/filter.helpers.d.ts +2 -1
- package/dist/scopes/helpers/filter.helpers.js +25 -126
- package/dist/scopes/helpers/filter.helpers.js.map +1 -0
- package/dist/scopes/index.cjs +1 -1
- package/dist/scopes/index.js +1 -3
- package/dist/types/index.d.cts +4 -2
- package/dist/types/index.d.ts +4 -2
- package/dist/utils/constants/index.cjs +2 -32
- package/dist/utils/constants/index.cjs.map +1 -0
- package/dist/utils/constants/index.d.cts +2 -1
- package/dist/utils/constants/index.d.ts +2 -1
- package/dist/utils/constants/index.js +2 -29
- package/dist/utils/constants/index.js.map +1 -0
- package/dist/utils/db/index.cjs +2 -15
- package/dist/utils/db/index.cjs.map +1 -0
- package/dist/utils/db/index.js +2 -14
- package/dist/utils/db/index.js.map +1 -0
- package/dist/utils/helpers/index.cjs +2 -23
- package/dist/utils/helpers/index.cjs.map +1 -0
- package/dist/utils/helpers/index.d.cts +2 -1
- package/dist/utils/helpers/index.d.ts +2 -1
- package/dist/utils/helpers/index.js +2 -21
- package/dist/utils/helpers/index.js.map +1 -0
- package/dist/utils/init.cjs +2 -115
- package/dist/utils/init.cjs.map +1 -0
- package/dist/utils/init.js +2 -111
- package/dist/utils/init.js.map +1 -0
- package/dist/utils/logger/index.cjs +2 -15
- package/dist/utils/logger/index.cjs.map +1 -0
- package/dist/utils/logger/index.js +2 -12
- package/dist/utils/logger/index.js.map +1 -0
- package/dist/utils/scopeAttributes.cjs +2 -12
- package/dist/utils/scopeAttributes.cjs.map +1 -0
- package/dist/utils/scopeAttributes.js +2 -11
- package/dist/utils/scopeAttributes.js.map +1 -0
- package/dist/utils/validations/index.cjs +2 -34
- package/dist/utils/validations/index.cjs.map +1 -0
- package/dist/utils/validations/index.js +2 -32
- package/dist/utils/validations/index.js.map +1 -0
- package/dist/utils/validations/schema/custom-fields.cjs +2 -9
- package/dist/utils/validations/schema/custom-fields.cjs.map +1 -0
- package/dist/utils/validations/schema/custom-fields.d.cts +2 -1
- package/dist/utils/validations/schema/custom-fields.d.ts +2 -1
- package/dist/utils/validations/schema/custom-fields.js +2 -7
- package/dist/utils/validations/schema/custom-fields.js.map +1 -0
- package/dist/utils/validations/schema/validator-schema.cjs +2 -102
- package/dist/utils/validations/schema/validator-schema.cjs.map +1 -0
- package/dist/utils/validations/schema/validator-schema.js +2 -99
- package/dist/utils/validations/schema/validator-schema.js.map +1 -0
- package/dist/utils/validations/validators/index.cjs +2 -45
- package/dist/utils/validations/validators/index.cjs.map +1 -0
- package/dist/utils/validations/validators/index.js +2 -42
- package/dist/utils/validations/validators/index.js.map +1 -0
- package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs +2 -7
- package/dist/utils/validations/validators/multi-select-dropdown.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/multi-select-dropdown.validator.js +2 -7
- package/dist/utils/validations/validators/multi-select-dropdown.validator.js.map +1 -0
- package/dist/utils/validations/validators/multi-select-status.validator.cjs +2 -10
- package/dist/utils/validations/validators/multi-select-status.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/multi-select-status.validator.js +2 -10
- package/dist/utils/validations/validators/multi-select-status.validator.js.map +1 -0
- package/dist/utils/validations/validators/multi-select.helpers.cjs +2 -12
- package/dist/utils/validations/validators/multi-select.helpers.cjs.map +1 -0
- package/dist/utils/validations/validators/multi-select.helpers.js +2 -10
- package/dist/utils/validations/validators/multi-select.helpers.js.map +1 -0
- package/dist/utils/validations/validators/select.validator.cjs +2 -12
- package/dist/utils/validations/validators/select.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/select.validator.js +2 -10
- package/dist/utils/validations/validators/select.validator.js.map +1 -0
- package/dist/utils/validations/validators/status.validator.cjs +2 -12
- package/dist/utils/validations/validators/status.validator.cjs.map +1 -0
- package/dist/utils/validations/validators/status.validator.js +2 -10
- package/dist/utils/validations/validators/status.validator.js.map +1 -0
- package/package.json +3 -3
- package/dist/api/v1/field-policies/index.cjs +0 -84
- package/dist/api/v1/field-policies/index.js +0 -83
- package/dist/migrations/004-create-field-policy-tables.cjs +0 -29
- package/dist/migrations/004-create-field-policy-tables.js +0 -27
- package/dist/models/FieldPolicy.cjs +0 -50
- package/dist/models/FieldPolicy.d.cts +0 -23
- package/dist/models/FieldPolicy.d.ts +0 -23
- package/dist/models/FieldPolicy.js +0 -49
- package/dist/models/tests/AssociatedTestModel.d.ts +0 -2
- package/dist/models/tests/TestModel.d.ts +0 -2
- package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +0 -2
- package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +0 -1
- package/dist/repository/field-policy.cjs +0 -46
- package/dist/repository/field-policy.d.cts +0 -31
- package/dist/repository/field-policy.d.ts +0 -31
- package/dist/repository/field-policy.js +0 -37
package/dist/hooks/enrich.js
CHANGED
|
@@ -1,175 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
import { findEntriesByModelIds } from "../repository/entries.js";
|
|
4
|
-
import scopeAttributes_default from "../utils/scopeAttributes.js";
|
|
5
|
-
|
|
6
|
-
//#region src/hooks/enrich.ts
|
|
7
|
-
const CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [
|
|
8
|
-
"id",
|
|
9
|
-
"name",
|
|
10
|
-
"entityId",
|
|
11
|
-
"fieldType",
|
|
12
|
-
"displayName",
|
|
13
|
-
"validation",
|
|
14
|
-
"entityType",
|
|
15
|
-
"modelType",
|
|
16
|
-
"required",
|
|
17
|
-
"disabled",
|
|
18
|
-
"defaultValue"
|
|
19
|
-
];
|
|
20
|
-
const getCustomFieldEntriesByInstanceId = async ({ instancesIds, options, sadotOptions }) => {
|
|
21
|
-
if (!sadotOptions.useCustomFieldsEntries) return {};
|
|
22
|
-
const customFieldEntries = await findEntriesByModelIds(instancesIds, options ?? {});
|
|
23
|
-
const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {
|
|
24
|
-
const { modelId, customFields } = instanceEntries?.dataValues ?? {};
|
|
25
|
-
if (!modelId) return;
|
|
26
|
-
return [modelId, customFields];
|
|
27
|
-
}).filter((v) => v !== void 0));
|
|
28
|
-
instancesIds.forEach((instanceId) => {
|
|
29
|
-
customFieldEntriesByInstanceId[instanceId] ??= {};
|
|
30
|
-
});
|
|
31
|
-
return customFieldEntriesByInstanceId;
|
|
32
|
-
};
|
|
33
|
-
const getValuesGroupByInstance = async ({ instancesIds, options, sadotOptions }) => {
|
|
34
|
-
if (sadotOptions.useCustomFieldsEntries) return {};
|
|
35
|
-
return (await findValuesByModelIds(instancesIds, options ?? {})).reduce((acc, v) => {
|
|
36
|
-
const { modelId } = v;
|
|
37
|
-
acc[modelId] ??= [];
|
|
38
|
-
acc[modelId].push(v);
|
|
39
|
-
return acc;
|
|
40
|
-
}, {});
|
|
41
|
-
};
|
|
42
|
-
/**
|
|
43
|
-
* Serialize custom fields value into the format of {[name] -> [fieldData]}
|
|
44
|
-
*/
|
|
45
|
-
const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) => {
|
|
46
|
-
return customFieldValues.reduce((acc, cfv) => ({
|
|
47
|
-
...acc,
|
|
48
|
-
...customFieldDefinitionsHash[cfv.customFieldDefinitionId] && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }
|
|
49
|
-
}), {});
|
|
50
|
-
};
|
|
51
|
-
/**
|
|
52
|
-
* A hook to attach the custom fields when fetching a model instances.
|
|
53
|
-
*/
|
|
54
|
-
const enrichResults = (modelType, scopeAttributes, hookType, modelOptions = {}, sadotOptions = {
|
|
55
|
-
useCustomFieldsEntries: false,
|
|
56
|
-
hasTypeId: false
|
|
57
|
-
}) => async (instancesOrInstance, options) => {
|
|
58
|
-
if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.("customFields")) return;
|
|
59
|
-
const primaryKey = "id";
|
|
60
|
-
let instances = Array.isArray(instancesOrInstance) ? instancesOrInstance : [instancesOrInstance];
|
|
61
|
-
instances = instances.filter(Boolean);
|
|
62
|
-
const identifiers = scopeAttributes_default(instances, scopeAttributes);
|
|
63
|
-
const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
|
|
64
|
-
const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
|
|
65
|
-
...map,
|
|
66
|
-
[identifier]: []
|
|
67
|
-
}), {});
|
|
68
|
-
let customFieldDefinitionsPromise;
|
|
69
|
-
let cacheKey;
|
|
70
|
-
if (options.transaction) {
|
|
71
|
-
options.transaction.definitionCache ??= /* @__PURE__ */ new Map();
|
|
72
|
-
cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(",")}`;
|
|
73
|
-
customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);
|
|
74
|
-
}
|
|
75
|
-
let modelTypeDefinitionsMap;
|
|
76
|
-
if (!customFieldDefinitionsPromise) {
|
|
77
|
-
const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;
|
|
78
|
-
const fetchDefinitions = async (transaction = options.transaction) => {
|
|
79
|
-
if (shouldApplyTypeFiltering) {
|
|
80
|
-
const uniqueTypeIds = [...new Set(instances.map((instance) => instance.typeId).filter(Boolean))];
|
|
81
|
-
modelTypeDefinitionsMap = /* @__PURE__ */ new Map();
|
|
82
|
-
uniqueTypeIds.forEach((typeId) => modelTypeDefinitionsMap.set(typeId, /* @__PURE__ */ new Set()));
|
|
83
|
-
const allDefinitions = (await Promise.all(uniqueTypeIds.map(async (typeId) => {
|
|
84
|
-
const defs = await findByModelTypeId(typeId, {
|
|
85
|
-
withDisabled: false,
|
|
86
|
-
entityIds: uniqueIdentifiers,
|
|
87
|
-
modelType,
|
|
88
|
-
modelOptions,
|
|
89
|
-
transaction
|
|
90
|
-
});
|
|
91
|
-
defs.forEach((def) => modelTypeDefinitionsMap.get(typeId).add(def.id));
|
|
92
|
-
return defs;
|
|
93
|
-
}))).flat();
|
|
94
|
-
const uniqueDefinitionsMap = /* @__PURE__ */ new Map();
|
|
95
|
-
allDefinitions.forEach((def) => {
|
|
96
|
-
uniqueDefinitionsMap.set(def.id, def);
|
|
97
|
-
});
|
|
98
|
-
return Array.from(uniqueDefinitionsMap.values());
|
|
99
|
-
}
|
|
100
|
-
return findByEntityIds(modelType, uniqueIdentifiers, {
|
|
101
|
-
transaction,
|
|
102
|
-
modelOptions,
|
|
103
|
-
attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL
|
|
104
|
-
});
|
|
105
|
-
};
|
|
106
|
-
customFieldDefinitionsPromise = fetchDefinitions();
|
|
107
|
-
if (!shouldApplyTypeFiltering) options.transaction?.definitionCache?.set(cacheKey, customFieldDefinitionsPromise);
|
|
108
|
-
}
|
|
109
|
-
const customFieldDefinitions = await customFieldDefinitionsPromise;
|
|
110
|
-
if (customFieldDefinitions.length === 0) {
|
|
111
|
-
instances.forEach((instance) => {
|
|
112
|
-
instance.customFields = {};
|
|
113
|
-
});
|
|
114
|
-
return;
|
|
115
|
-
}
|
|
116
|
-
if (modelOptions?.include && modelOptions.useEntityIdFromInclude) modelOptions.include(identifiers).forEach(({ model }) => {
|
|
117
|
-
customFieldDefinitions.forEach((cfd) => {
|
|
118
|
-
const entityId = cfd[model.name]?.entityId || cfd[`${model.name}.entityId`];
|
|
119
|
-
if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) identifierCustomFieldDefinitionsMapping[entityId] = [];
|
|
120
|
-
});
|
|
121
|
-
});
|
|
122
|
-
const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
|
|
123
|
-
...map,
|
|
124
|
-
[definition.id]: definition
|
|
125
|
-
}), {});
|
|
126
|
-
customFieldDefinitions.forEach((cfd) => {
|
|
127
|
-
let entityIdToUse = cfd.entityId;
|
|
128
|
-
if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {
|
|
129
|
-
const contextIncludes = modelOptions.include(identifiers);
|
|
130
|
-
for (const { model } of contextIncludes) {
|
|
131
|
-
const joinedEntityId = cfd[model.name]?.entityId || cfd[`${model.name}.entityId`];
|
|
132
|
-
if (joinedEntityId) {
|
|
133
|
-
entityIdToUse = joinedEntityId;
|
|
134
|
-
break;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);
|
|
139
|
-
});
|
|
140
|
-
const instancesIds = instances.map((i) => i[primaryKey]);
|
|
141
|
-
const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([getValuesGroupByInstance({
|
|
142
|
-
instancesIds,
|
|
143
|
-
options,
|
|
144
|
-
sadotOptions
|
|
145
|
-
}), getCustomFieldEntriesByInstanceId({
|
|
146
|
-
instancesIds,
|
|
147
|
-
options,
|
|
148
|
-
sadotOptions
|
|
149
|
-
})]);
|
|
150
|
-
instances.forEach((instance) => {
|
|
151
|
-
const { id } = instance;
|
|
152
|
-
const instanceValues = valuesGroupByInstance[id];
|
|
153
|
-
const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};
|
|
154
|
-
const customFields = sadotOptions.useCustomFieldsEntries ? customFieldEntriesByInstanceId[id] : serializedCustomFieldsValues;
|
|
155
|
-
scopeAttributes.forEach((attribute) => {
|
|
156
|
-
const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[instance[attribute]];
|
|
157
|
-
if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
|
|
158
|
-
if (modelTypeDefinitionsMap) {
|
|
159
|
-
if (!modelTypeDefinitionsMap.get(instance.typeId)?.has(customFieldDefinition.id)) return;
|
|
160
|
-
}
|
|
161
|
-
if (customFields[customFieldDefinition.name] === void 0) customFields[customFieldDefinition.name] = null;
|
|
162
|
-
});
|
|
163
|
-
});
|
|
164
|
-
instance.customFields = customFields;
|
|
165
|
-
options.attributesToRemove?.forEach?.((attribute) => {
|
|
166
|
-
delete instance.dataValues?.[attribute];
|
|
167
|
-
delete instance?.[attribute];
|
|
168
|
-
});
|
|
169
|
-
if (hookType === "afterFind") instance?.changed?.("customFields", false);
|
|
170
|
-
});
|
|
171
|
-
};
|
|
172
|
-
var enrich_default = enrichResults;
|
|
173
|
-
|
|
174
|
-
//#endregion
|
|
175
|
-
export { enrich_default as default };
|
|
1
|
+
import{findByEntityIds as e,findByModelTypeId as t}from"../repository/definition.js";import{findValuesByModelIds as n}from"../repository/value.js";import{findEntriesByModelIds as r}from"../repository/entries.js";import i from"../utils/scopeAttributes.js";const a=[`id`,`name`,`entityId`,`fieldType`,`displayName`,`validation`,`entityType`,`modelType`,`required`,`disabled`,`defaultValue`],o=async({instancesIds:e,options:t,sadotOptions:n})=>{if(!n.useCustomFieldsEntries)return{};let i=await r(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},s=async({instancesIds:e,options:t,sadotOptions:r})=>r.useCustomFieldsEntries?{}:(await n(e,t??{})).reduce((e,t)=>{let{modelId:n}=t;return e[n]??=[],e[n].push(t),e},{}),c=(e,t)=>e.reduce((e,n)=>({...e,...t[n.customFieldDefinitionId]&&{[t[n.customFieldDefinitionId].name]:n.value}}),{});var l=(n,r,l,u={},d={useCustomFieldsEntries:!1,hasTypeId:!1})=>async(f,p)=>{if(p.originalAttributes?.length>0&&!p.originalAttributes?.includes?.(`customFields`))return;let m=Array.isArray(f)?f:[f];m=m.filter(Boolean);let h=i(m,r),g=[...new Set(h)].filter(Boolean),_=g.reduce((e,t)=>({...e,[t]:[]}),{}),v,y;p.transaction&&(p.transaction.definitionCache??=new Map,y=`${n}:${g.slice().sort().join(`,`)}`,v=p.transaction.definitionCache.get(y));let b;if(!v){let r=d.hasTypeId&&m.length>0&&m[0].typeId;v=(async(i=p.transaction)=>{if(r){let e=[...new Set(m.map(e=>e.typeId).filter(Boolean))];b=new Map,e.forEach(e=>b.set(e,new Set));let r=(await Promise.all(e.map(async e=>{let r=await t(e,{withDisabled:!1,entityIds:g,modelType:n,modelOptions:u,transaction:i});return r.forEach(t=>b.get(e).add(t.id)),r}))).flat(),a=new Map;return r.forEach(e=>{a.set(e.id,e)}),Array.from(a.values())}return e(n,g,{transaction:i,modelOptions:u,attributes:a})})(),r||p.transaction?.definitionCache?.set(y,v)}let x=await v;if(x.length===0){m.forEach(e=>{e.customFields={}});return}u?.include&&u.useEntityIdFromInclude&&u.include(h).forEach(({model:e})=>{x.forEach(t=>{let n=t[e.name]?.entityId||t[`${e.name}.entityId`];n&&!_[n]&&(_[n]=[])})});let S=x.reduce((e,t)=>({...e,[t.id]:t}),{});x.forEach(e=>{let t=e.entityId;if(u?.useEntityIdFromInclude&&u.include){let n=u.include(h);for(let{model:r}of n){let n=e[r.name]?.entityId||e[`${r.name}.entityId`];if(n){t=n;break}}}_[t]&&_[t].push(e)});let C=m.map(e=>e.id),[w,T]=await Promise.all([s({instancesIds:C,options:p,sadotOptions:d}),o({instancesIds:C,options:p,sadotOptions:d})]);m.forEach(e=>{let{id:t}=e,n=w[t],i=n?c(n,S):{},a=d.useCustomFieldsEntries?T[t]:i;r.forEach(t=>{let n=_[e[t]];n&&n.length>0&&n.forEach(t=>{b&&!b.get(e.typeId)?.has(t.id)||a[t.name]===void 0&&(a[t.name]=null)})}),e.customFields=a,p.attributesToRemove?.forEach?.(t=>{delete e.dataValues?.[t],delete e?.[t]}),l===`afterFind`&&e?.changed?.(`customFields`,!1)})};export{l as default};
|
|
2
|
+
//# sourceMappingURL=enrich.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"enrich.js","names":["EntriesRepo.findEntriesByModelIds","ValueRepo.findValuesByModelIds","applyScopeToInstance","cacheKey: string | undefined","modelTypeDefinitionsMap: Map<string, Set<string>> | undefined","DefinitionRepo.findByModelTypeId","DefinitionRepo.findByEntityIds"],"sources":["../../src/hooks/enrich.ts"],"sourcesContent":["import * as ValueRepo from '../repository/value';\nimport * as DefinitionRepo from '../repository/definition';\nimport * as EntriesRepo from '../repository/entries';\nimport type CustomFieldValue from '../models/CustomFieldValue';\nimport type CustomFieldDefinition from '../models/CustomFieldDefinition';\nimport type { SerializedCustomFields } from '../types/definition';\nimport type { CustomFieldOptions, ModelOptions, TransactionOptions } from '../types';\nimport applyScopeToInstance from '../utils/scopeAttributes';\n\n// Include all required fields for proper functioning\nconst CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL = [\n 'id',\n 'name',\n 'entityId',\n 'fieldType',\n 'displayName',\n 'validation',\n 'entityType',\n 'modelType',\n 'required',\n 'disabled',\n 'defaultValue',\n];\n\ntype SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';\n\ntype CustomFieldEntries = Record<string, any>;\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetValuesGroupByInstanceResponse {\n [modelId: string]: CustomFieldValue[];\n}\n\n// eslint-disable-next-line @typescript-eslint/consistent-indexed-object-style\ninterface GetCustomFieldEntriesByInstanceIdResponse {\n [modelId: string]: CustomFieldEntries;\n}\n\nexport const getCustomFieldEntriesByInstanceId = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetCustomFieldEntriesByInstanceIdResponse> => {\n if (!sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldEntries = await EntriesRepo.findEntriesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n const customFieldEntriesByInstanceId = Object.fromEntries(customFieldEntries.map((instanceEntries) => {\n const { modelId, customFields } = instanceEntries?.dataValues ?? {};\n if (!modelId) {\n return undefined;\n }\n return [modelId, customFields];\n }).filter(v => v !== undefined));\n\n instancesIds.forEach((instanceId) => {\n customFieldEntriesByInstanceId[instanceId] ??= {};\n });\n\n return customFieldEntriesByInstanceId;\n};\n\nexport const getValuesGroupByInstance = async ({\n instancesIds,\n options,\n sadotOptions,\n}: {\n instancesIds: string[];\n options?: TransactionOptions;\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries'>;\n}): Promise<GetValuesGroupByInstanceResponse> => {\n if (sadotOptions.useCustomFieldsEntries) {\n return {};\n }\n\n const customFieldValues = await ValueRepo.findValuesByModelIds(\n instancesIds,\n options ?? {},\n );\n\n // Group fields by modelId\n return customFieldValues.reduce<Record<string, CustomFieldValue[]>>((acc, v) => {\n const { modelId } = v;\n acc[modelId] ??= [];\n acc[modelId].push(v);\n return acc;\n }, {});\n};\n\n/**\n * Serialize custom fields value into the format of {[name] -> [fieldData]}\n */\nconst serializeCustomFields = (\n customFieldValues: CustomFieldValue[],\n customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,\n): SerializedCustomFields => {\n const customFields = customFieldValues.reduce((acc, cfv) => ({\n ...acc,\n ...(\n customFieldDefinitionsHash[cfv.customFieldDefinitionId]\n && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }\n ),\n }), {});\n return customFields;\n};\n/**\n * A hook to attach the custom fields when fetching a model instances.\n */\nconst enrichResults = (\n modelType: string,\n scopeAttributes: string[],\n hookType?: SupportedHookTypes,\n modelOptions: ModelOptions = {},\n sadotOptions: Pick<CustomFieldOptions, 'useCustomFieldsEntries' | 'hasTypeId'> = { useCustomFieldsEntries: false, hasTypeId: false },\n) => async (\n instancesOrInstance: any | any[],\n options: TransactionOptions,\n): Promise<void> => {\n if (options.originalAttributes?.length > 0 && !options.originalAttributes?.includes?.('customFields')) {\n return;\n }\n\n const primaryKey = 'id';\n let instances = Array.isArray(instancesOrInstance)\n ? instancesOrInstance\n : [instancesOrInstance];\n\n instances = instances.filter(Boolean);\n\n const identifiers = applyScopeToInstance(instances, scopeAttributes);\n\n const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);\n\n const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({\n ...map,\n [identifier]: [],\n }), {});\n\n // Cache for definitions by model type and transaction to avoid redundant DB queries\n let customFieldDefinitionsPromise;\n let cacheKey: string | undefined;\n\n if (options.transaction) {\n // Initialize definition cache Map if not already present directly on the transaction object\n options.transaction.definitionCache ??= new Map();\n cacheKey = `${modelType}:${uniqueIdentifiers.slice().sort().join(',')}`;\n customFieldDefinitionsPromise = options.transaction.definitionCache.get(cacheKey);\n }\n\n let modelTypeDefinitionsMap: Map<string, Set<string>> | undefined;\n\n // Fetch from database (either first time in this transaction or no transaction).\n if (!customFieldDefinitionsPromise) {\n const shouldApplyTypeFiltering = sadotOptions.hasTypeId && instances.length > 0 && instances[0].typeId;\n\n const fetchDefinitions = async (transaction = options.transaction) => {\n if (shouldApplyTypeFiltering) {\n const uniqueTypeIds = [...new Set(instances.map(instance => instance.typeId).filter(Boolean))];\n\n modelTypeDefinitionsMap = new Map<string, Set<string>>();\n uniqueTypeIds.forEach(typeId => modelTypeDefinitionsMap!.set(typeId, new Set()));\n\n const definitionsResults = await Promise.all(\n uniqueTypeIds.map(async (typeId) => {\n const defs = await DefinitionRepo.findByModelTypeId(typeId, { withDisabled: false, entityIds: uniqueIdentifiers, modelType, modelOptions, transaction });\n defs.forEach(def => modelTypeDefinitionsMap!.get(typeId)!.add(def.id));\n return defs;\n }),\n );\n\n const allDefinitions = definitionsResults.flat();\n const uniqueDefinitionsMap = new Map();\n allDefinitions.forEach((def) => {\n uniqueDefinitionsMap.set(def.id, def);\n });\n return Array.from(uniqueDefinitionsMap.values());\n }\n return DefinitionRepo.findByEntityIds(\n modelType,\n uniqueIdentifiers,\n { transaction, modelOptions, attributes: CUSTOM_FIELD_DEFINITION_ATTRIBUTES_TO_PULL },\n );\n };\n\n customFieldDefinitionsPromise = fetchDefinitions();\n\n if (!shouldApplyTypeFiltering) {\n options.transaction?.definitionCache?.set(cacheKey!, customFieldDefinitionsPromise);\n }\n }\n const customFieldDefinitions = await customFieldDefinitionsPromise;\n\n if (customFieldDefinitions.length === 0) {\n // if no custom fields, we can return\n instances.forEach((instance) => {\n instance.customFields = {};\n });\n return;\n }\n\n if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {\n // if we pass useEntityIdFromInclude,\n // map the entity from the options to the identifierCustomFieldDefinitionsMapping\n modelOptions.include(identifiers).forEach(({ model }) => {\n customFieldDefinitions.forEach((cfd: any) => {\n // try 2 ways to get the entityId from the joined model - for raw and non-raw\n const entityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (entityId && !identifierCustomFieldDefinitionsMapping[entityId]) {\n identifierCustomFieldDefinitionsMapping[entityId] = [];\n }\n });\n });\n }\n\n const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({\n ...map,\n [definition.id]: definition,\n }), {});\n\n customFieldDefinitions.forEach((cfd: any) => {\n let entityIdToUse = cfd.entityId;\n\n if (modelOptions?.useEntityIdFromInclude && modelOptions.include) {\n const contextIncludes = modelOptions.include(identifiers);\n for (const { model } of contextIncludes) {\n const joinedEntityId = cfd[model!.name]?.entityId || cfd[`${model!.name}.entityId` as keyof CustomFieldDefinition];\n if (joinedEntityId) {\n entityIdToUse = joinedEntityId;\n break;\n }\n }\n }\n\n if (identifierCustomFieldDefinitionsMapping[entityIdToUse]) {\n identifierCustomFieldDefinitionsMapping[entityIdToUse].push(cfd);\n }\n });\n\n // Get the values per instates ids:\n const instancesIds = instances.map(i => i[primaryKey]);\n\n // Group fields by modelId\n const [valuesGroupByInstance, customFieldEntriesByInstanceId] = await Promise.all([\n getValuesGroupByInstance({\n instancesIds,\n options,\n sadotOptions,\n }),\n getCustomFieldEntriesByInstanceId({\n instancesIds,\n options,\n sadotOptions,\n }),\n ]);\n\n // Attach custom fields to the instances\n instances.forEach((instance) => {\n const { id } = instance;\n\n const instanceValues = valuesGroupByInstance[id];\n const serializedCustomFieldsValues = instanceValues ? serializeCustomFields(instanceValues, definitionsMap) : {};\n\n const customFields = sadotOptions.useCustomFieldsEntries\n ? customFieldEntriesByInstanceId[id]\n : serializedCustomFieldsValues;\n\n scopeAttributes.forEach((attribute) => {\n const identifier = instance[attribute];\n\n const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier] as CustomFieldDefinition[] | undefined;\n if (entityCustomFieldDefinitions && entityCustomFieldDefinitions.length > 0) {\n entityCustomFieldDefinitions.forEach((customFieldDefinition) => {\n if (modelTypeDefinitionsMap) {\n const applicableDefinitionIds = modelTypeDefinitionsMap.get(instance.typeId);\n if (!applicableDefinitionIds?.has(customFieldDefinition.id)) {\n return;\n }\n }\n\n if (customFields[customFieldDefinition.name] === undefined) {\n customFields[customFieldDefinition.name] = null;\n }\n });\n }\n });\n instance.customFields = customFields;\n (options.attributesToRemove as string[] | undefined)?.forEach?.((attribute) => {\n delete instance.dataValues?.[attribute];\n // if raw:\n delete instance?.[attribute];\n });\n // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged\n if (hookType === 'afterFind') {\n // changed() could be undefined, i.e in raw: true\n instance?.changed?.('customFields', false);\n }\n });\n};\n\nexport default enrichResults;\n"],"mappings":"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"}
|
package/dist/hooks/find.cjs
CHANGED
|
@@ -1,22 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
|
|
3
|
-
//#region src/hooks/find.ts
|
|
4
|
-
const doScopeAttributesMissing = (scopeAttributes, queryAttributes) => {
|
|
5
|
-
const attributes = scopeAttributes.filter((attribute) => !queryAttributes.includes(attribute));
|
|
6
|
-
if (!queryAttributes.includes?.("id")) attributes.push("id");
|
|
7
|
-
return attributes;
|
|
8
|
-
};
|
|
9
|
-
const beforeFind = (scopeAttributes) => (options) => {
|
|
10
|
-
const { attributes: queryAttributes } = options;
|
|
11
|
-
if (queryAttributes?.includes?.("customFields")) {
|
|
12
|
-
const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes);
|
|
13
|
-
require_index.default.debug("sadot - before find hook");
|
|
14
|
-
if (missingScopeAttributes?.length > 0) {
|
|
15
|
-
queryAttributes.push(...missingScopeAttributes);
|
|
16
|
-
options.attributesToRemove = missingScopeAttributes;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
//#endregion
|
|
22
|
-
exports.beforeFind = beforeFind;
|
|
1
|
+
const e=require(`../utils/logger/index.cjs`),t=(e,t)=>{let n=e.filter(e=>!t.includes(e));return t.includes?.(`id`)||n.push(`id`),n},n=n=>r=>{let{attributes:i}=r;if(i?.includes?.(`customFields`)){let a=t(n,i);e.default.debug(`sadot - before find hook`),a?.length>0&&(i.push(...a),r.attributesToRemove=a)}};exports.beforeFind=n;
|
|
2
|
+
//# sourceMappingURL=find.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"find.cjs","names":[],"sources":["../../src/hooks/find.ts"],"sourcesContent":["import type { FindOptions } from 'sequelize';\nimport logger from '../utils/logger';\n\nconst doScopeAttributesMissing = (\n scopeAttributes: string[],\n queryAttributes: (string | string[])[],\n): string[] => {\n const attributes = scopeAttributes\n .filter(attribute => !queryAttributes.includes(attribute));\n if (!queryAttributes.includes?.('id')) {\n attributes.push('id');\n }\n return attributes;\n};\n\nexport const beforeFind = (scopeAttributes: string[]) => (options: FindOptions): void => {\n const { attributes: queryAttributes } = options;\n if ((queryAttributes as string[])?.includes?.('customFields')) {\n const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes as string[]);\n logger.debug('sadot - before find hook');\n if (missingScopeAttributes?.length > 0) {\n (queryAttributes as string[]).push(...missingScopeAttributes);\n (options as any).attributesToRemove = missingScopeAttributes;\n }\n }\n};\n"],"mappings":"6CAGM,GACJ,EACA,IACa,CACb,IAAM,EAAa,EAChB,OAAO,GAAa,CAAC,EAAgB,SAAS,EAAU,CAAC,CAI5D,OAHK,EAAgB,WAAW,KAAK,EACnC,EAAW,KAAK,KAAK,CAEhB,GAGI,EAAc,GAA+B,GAA+B,CACvF,GAAM,CAAE,WAAY,GAAoB,EACxC,GAAK,GAA8B,WAAW,eAAe,CAAE,CAC7D,IAAM,EAAyB,EAAyB,EAAiB,EAA4B,CACrG,EAAA,QAAO,MAAM,2BAA2B,CACpC,GAAwB,OAAS,IAClC,EAA6B,KAAK,GAAG,EAAuB,CAC5D,EAAgB,mBAAqB"}
|
package/dist/hooks/find.js
CHANGED
|
@@ -1,22 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
//#region src/hooks/find.ts
|
|
4
|
-
const doScopeAttributesMissing = (scopeAttributes, queryAttributes) => {
|
|
5
|
-
const attributes = scopeAttributes.filter((attribute) => !queryAttributes.includes(attribute));
|
|
6
|
-
if (!queryAttributes.includes?.("id")) attributes.push("id");
|
|
7
|
-
return attributes;
|
|
8
|
-
};
|
|
9
|
-
const beforeFind = (scopeAttributes) => (options) => {
|
|
10
|
-
const { attributes: queryAttributes } = options;
|
|
11
|
-
if (queryAttributes?.includes?.("customFields")) {
|
|
12
|
-
const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes);
|
|
13
|
-
logger_default.debug("sadot - before find hook");
|
|
14
|
-
if (missingScopeAttributes?.length > 0) {
|
|
15
|
-
queryAttributes.push(...missingScopeAttributes);
|
|
16
|
-
options.attributesToRemove = missingScopeAttributes;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
};
|
|
20
|
-
|
|
21
|
-
//#endregion
|
|
22
|
-
export { beforeFind };
|
|
1
|
+
import e from"../utils/logger/index.js";const t=(e,t)=>{let n=e.filter(e=>!t.includes(e));return t.includes?.(`id`)||n.push(`id`),n},n=n=>r=>{let{attributes:i}=r;if(i?.includes?.(`customFields`)){let a=t(n,i);e.debug(`sadot - before find hook`),a?.length>0&&(i.push(...a),r.attributesToRemove=a)}};export{n as beforeFind};
|
|
2
|
+
//# sourceMappingURL=find.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"find.js","names":[],"sources":["../../src/hooks/find.ts"],"sourcesContent":["import type { FindOptions } from 'sequelize';\nimport logger from '../utils/logger';\n\nconst doScopeAttributesMissing = (\n scopeAttributes: string[],\n queryAttributes: (string | string[])[],\n): string[] => {\n const attributes = scopeAttributes\n .filter(attribute => !queryAttributes.includes(attribute));\n if (!queryAttributes.includes?.('id')) {\n attributes.push('id');\n }\n return attributes;\n};\n\nexport const beforeFind = (scopeAttributes: string[]) => (options: FindOptions): void => {\n const { attributes: queryAttributes } = options;\n if ((queryAttributes as string[])?.includes?.('customFields')) {\n const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes as string[]);\n logger.debug('sadot - before find hook');\n if (missingScopeAttributes?.length > 0) {\n (queryAttributes as string[]).push(...missingScopeAttributes);\n (options as any).attributesToRemove = missingScopeAttributes;\n }\n }\n};\n"],"mappings":"wCAGA,MAAM,GACJ,EACA,IACa,CACb,IAAM,EAAa,EAChB,OAAO,GAAa,CAAC,EAAgB,SAAS,EAAU,CAAC,CAI5D,OAHK,EAAgB,WAAW,KAAK,EACnC,EAAW,KAAK,KAAK,CAEhB,GAGI,EAAc,GAA+B,GAA+B,CACvF,GAAM,CAAE,WAAY,GAAoB,EACxC,GAAK,GAA8B,WAAW,eAAe,CAAE,CAC7D,IAAM,EAAyB,EAAyB,EAAiB,EAA4B,CACrG,EAAO,MAAM,2BAA2B,CACpC,GAAwB,OAAS,IAClC,EAA6B,KAAK,GAAG,EAAuB,CAC5D,EAAgB,mBAAqB"}
|
package/dist/hooks/hooks.cjs
CHANGED
|
@@ -1,310 +1,2 @@
|
|
|
1
|
-
const
|
|
2
|
-
|
|
3
|
-
const require_index$1 = require('../utils/constants/index.cjs');
|
|
4
|
-
const require_index$2 = require('../errors/index.cjs');
|
|
5
|
-
const require_definition = require('../repository/definition.cjs');
|
|
6
|
-
const require_validator = require('../repository/validator.cjs');
|
|
7
|
-
const require_scopeAttributes = require('../utils/scopeAttributes.cjs');
|
|
8
|
-
const require_updateInstanceValues = require('./utils/updateInstanceValues.cjs');
|
|
9
|
-
let joi = require("joi");
|
|
10
|
-
joi = require_rolldown_runtime.__toESM(joi);
|
|
11
|
-
let _autofleet_errors = require("@autofleet/errors");
|
|
12
|
-
let ajv = require("ajv");
|
|
13
|
-
ajv = require_rolldown_runtime.__toESM(ajv);
|
|
14
|
-
let ajv_formats = require("ajv-formats");
|
|
15
|
-
ajv_formats = require_rolldown_runtime.__toESM(ajv_formats);
|
|
16
|
-
let ajv_errors = require("ajv-errors");
|
|
17
|
-
ajv_errors = require_rolldown_runtime.__toESM(ajv_errors);
|
|
18
|
-
|
|
19
|
-
//#region src/hooks/hooks.ts
|
|
20
|
-
const CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL = [
|
|
21
|
-
"id",
|
|
22
|
-
"schema",
|
|
23
|
-
"modelType",
|
|
24
|
-
"entityId",
|
|
25
|
-
"disabled"
|
|
26
|
-
];
|
|
27
|
-
const ajv$1 = new ajv.default({
|
|
28
|
-
allErrors: true,
|
|
29
|
-
strict: false,
|
|
30
|
-
strictTypes: false,
|
|
31
|
-
$data: true
|
|
32
|
-
});
|
|
33
|
-
(0, ajv_formats.default)(ajv$1);
|
|
34
|
-
(0, ajv_errors.default)(ajv$1);
|
|
35
|
-
/**
|
|
36
|
-
* Helper function to manually copy object properties
|
|
37
|
-
* This is more efficient for large objects and avoids excessive object creation
|
|
38
|
-
*/
|
|
39
|
-
const manualObjectCopy = (sourceObj, additionalProps) => ({
|
|
40
|
-
__proto__: null,
|
|
41
|
-
...sourceObj,
|
|
42
|
-
...additionalProps
|
|
43
|
-
});
|
|
44
|
-
/**
|
|
45
|
-
* Fetches complete custom fields for an instance by merging DB values with update values
|
|
46
|
-
* This is needed for partial updates to ensure all related fields are available for validation
|
|
47
|
-
*/
|
|
48
|
-
const getCompleteCustomFields = async (instance, options) => {
|
|
49
|
-
if (!instance.id || !instance.customFields || Object.keys(instance.customFields).length === 0) return instance.customFields || {};
|
|
50
|
-
try {
|
|
51
|
-
const currentCustomFields = await instance.constructor.findOne({
|
|
52
|
-
where: { id: instance.id },
|
|
53
|
-
attributes: ["customFields"],
|
|
54
|
-
transaction: options.transaction,
|
|
55
|
-
raw: true
|
|
56
|
-
});
|
|
57
|
-
if (currentCustomFields?.customFields) {
|
|
58
|
-
const completeFields = manualObjectCopy(currentCustomFields.customFields, instance.customFields);
|
|
59
|
-
require_index.default.debug("sadot - fetched complete custom fields for validation", {
|
|
60
|
-
fieldsCount: Object.keys(completeFields).length,
|
|
61
|
-
updateFieldsCount: Object.keys(instance.customFields).length
|
|
62
|
-
});
|
|
63
|
-
return completeFields;
|
|
64
|
-
}
|
|
65
|
-
} catch (error) {
|
|
66
|
-
require_index.default.error("sadot - error fetching complete model for validation", { error });
|
|
67
|
-
}
|
|
68
|
-
return instance.customFields || {};
|
|
69
|
-
};
|
|
70
|
-
const buildPreChangeState = (instance) => {
|
|
71
|
-
const beforeFull = { ...instance.dataValues };
|
|
72
|
-
(instance.changed?.() || []).forEach((key) => {
|
|
73
|
-
const prevVal = instance.previous?.(key);
|
|
74
|
-
if (prevVal !== void 0) beforeFull[key] = prevVal;
|
|
75
|
-
});
|
|
76
|
-
const prevCF = instance.previous?.("customFields");
|
|
77
|
-
if (prevCF !== void 0) beforeFull.customFields = prevCF;
|
|
78
|
-
return beforeFull;
|
|
79
|
-
};
|
|
80
|
-
const formatAjvErrors = (errors) => errors.reduce((acc, err) => {
|
|
81
|
-
const key = ((err.instancePath || "").split("/").filter(Boolean).join(".").replace(/^after\./, "") + (err.keyword === "required" ? `.${err.params?.missingProperty}` : "")).replace(/^\./, "") || "root";
|
|
82
|
-
acc[key] = err.message || "Invalid value";
|
|
83
|
-
return acc;
|
|
84
|
-
}, {});
|
|
85
|
-
/**
|
|
86
|
-
* Validates the model using custom validators
|
|
87
|
-
*/
|
|
88
|
-
const validateModel = async (instance, options, scopeAttributes, modelOptions = {}, isCreate = false) => {
|
|
89
|
-
const modelType = instance.constructor.name;
|
|
90
|
-
require_index.default.debug("sadot - validating model", {
|
|
91
|
-
isCreate,
|
|
92
|
-
modelType
|
|
93
|
-
});
|
|
94
|
-
const identifiers = require_scopeAttributes.default(instance, scopeAttributes);
|
|
95
|
-
require_index.default.debug("sadot - identifiers", { identifiers });
|
|
96
|
-
if (!identifiers || Object.keys(identifiers).length === 0) {
|
|
97
|
-
require_index.default.debug("sadot - skipping validation: no identifiers");
|
|
98
|
-
return;
|
|
99
|
-
}
|
|
100
|
-
const entityId = Object.values(identifiers)[0];
|
|
101
|
-
require_index.default.debug("sadot - entityId", { entityId });
|
|
102
|
-
if (!entityId) {
|
|
103
|
-
require_index.default.debug("sadot - skipping validation: no entityId");
|
|
104
|
-
return;
|
|
105
|
-
}
|
|
106
|
-
let validatorsPromise;
|
|
107
|
-
let cacheKey;
|
|
108
|
-
if (options.transaction) {
|
|
109
|
-
options.transaction.validationsCache ??= /* @__PURE__ */ new Map();
|
|
110
|
-
cacheKey = `${modelType}-${entityId}`;
|
|
111
|
-
validatorsPromise = options.transaction.validationsCache.get(cacheKey);
|
|
112
|
-
}
|
|
113
|
-
if (!validatorsPromise) {
|
|
114
|
-
validatorsPromise = require_validator.findAllByModelType(modelType, entityId, {
|
|
115
|
-
transaction: options.transaction,
|
|
116
|
-
attributes: CUSTOM_VALIDATOR_ATTRIBUTES_TO_PULL,
|
|
117
|
-
modelOptions
|
|
118
|
-
});
|
|
119
|
-
if (options.transaction) options?.transaction?.validationsCache.set(cacheKey, validatorsPromise);
|
|
120
|
-
}
|
|
121
|
-
const validators = await validatorsPromise;
|
|
122
|
-
require_index.default.debug("sadot - validators found", { count: validators.length });
|
|
123
|
-
if (!validators.length) {
|
|
124
|
-
require_index.default.debug("sadot - skipping validation: no validators found");
|
|
125
|
-
return;
|
|
126
|
-
}
|
|
127
|
-
let originalValues = null;
|
|
128
|
-
if (!isCreate) originalValues = buildPreChangeState(instance);
|
|
129
|
-
const completeCustomFields = !isCreate ? await getCompleteCustomFields(instance, options) : instance.customFields || {};
|
|
130
|
-
for (const validator of validators) {
|
|
131
|
-
const { schema } = validator;
|
|
132
|
-
const typedSchema = schema;
|
|
133
|
-
require_index.default.debug("sadot - validating with schema", {
|
|
134
|
-
schema,
|
|
135
|
-
hasAfterProps: !!typedSchema.properties?.after,
|
|
136
|
-
hasBeforeProps: !!typedSchema.properties?.before
|
|
137
|
-
});
|
|
138
|
-
if (isCreate) {
|
|
139
|
-
if (typedSchema.properties?.after) {
|
|
140
|
-
const validateSchema = ajv$1.compile({
|
|
141
|
-
...schema,
|
|
142
|
-
properties: { after: typedSchema.properties.after }
|
|
143
|
-
});
|
|
144
|
-
if (!validateSchema(JSON.parse(JSON.stringify({ after: {
|
|
145
|
-
...instance.dataValues,
|
|
146
|
-
customFields: completeCustomFields
|
|
147
|
-
} })))) {
|
|
148
|
-
const errorDetails = validateSchema.errors?.map((err) => `${err.instancePath || ""} ${err.message || "Invalid value"}`).join(", ");
|
|
149
|
-
const formattedErrors = formatAjvErrors(validateSchema.errors);
|
|
150
|
-
throw new _autofleet_errors.BadRequest([/* @__PURE__ */ new Error(`Validation failed for ${modelType}: ${errorDetails}`)], void 0, { customError: formattedErrors });
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
} else {
|
|
154
|
-
const validateSchema = ajv$1.compile(typedSchema);
|
|
155
|
-
const afterObj = manualObjectCopy(instance.dataValues);
|
|
156
|
-
afterObj.customFields = completeCustomFields;
|
|
157
|
-
const payload = {
|
|
158
|
-
before: originalValues,
|
|
159
|
-
after: afterObj
|
|
160
|
-
};
|
|
161
|
-
const isValid = validateSchema(JSON.parse(JSON.stringify(payload)));
|
|
162
|
-
require_index.default.debug("sadot - validation result", {
|
|
163
|
-
isValid,
|
|
164
|
-
test: {
|
|
165
|
-
before: originalValues,
|
|
166
|
-
after: afterObj
|
|
167
|
-
}
|
|
168
|
-
});
|
|
169
|
-
if (!isValid) {
|
|
170
|
-
const errorDetails = validateSchema.errors?.map((err) => `${err.instancePath || ""} ${err.message || "Invalid value"}`).join(", ");
|
|
171
|
-
const formattedErrors = formatAjvErrors(validateSchema.errors);
|
|
172
|
-
throw new _autofleet_errors.BadRequest([/* @__PURE__ */ new Error(`Validation failed for ${modelType}: ${errorDetails}`)], void 0, { customError: formattedErrors });
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
};
|
|
177
|
-
const getFieldDefinitions = async ({ modelType, modelOptions, identifiers, options, instance, sadotOptions }) => {
|
|
178
|
-
const { include, useEntityIdFromInclude } = modelOptions;
|
|
179
|
-
if (sadotOptions.hasTypeId && instance?.typeId) return require_definition.findByModelTypeId(instance.typeId, {
|
|
180
|
-
withDisabled: false,
|
|
181
|
-
transaction: options.transaction,
|
|
182
|
-
entityIds: identifiers,
|
|
183
|
-
modelType,
|
|
184
|
-
modelOptions
|
|
185
|
-
});
|
|
186
|
-
const where = {
|
|
187
|
-
modelType,
|
|
188
|
-
disabled: false,
|
|
189
|
-
...!useEntityIdFromInclude && { entityId: identifiers }
|
|
190
|
-
};
|
|
191
|
-
return require_definition.findAll(where, {
|
|
192
|
-
withDisabled: false,
|
|
193
|
-
transaction: options.transaction,
|
|
194
|
-
include: include?.(identifiers)
|
|
195
|
-
});
|
|
196
|
-
};
|
|
197
|
-
const formatDates = (fieldDefinitions, instance) => {
|
|
198
|
-
(fieldDefinitions || []).forEach((fieldDefinition) => {
|
|
199
|
-
const { fieldType, name } = fieldDefinition;
|
|
200
|
-
if ([require_index$1.CustomFieldDefinitionType.DATE, require_index$1.CustomFieldDefinitionType.DATETIME].includes(fieldType)) {
|
|
201
|
-
const value = instance.customFields?.[name];
|
|
202
|
-
if (value) {
|
|
203
|
-
const { value: joiValue, error: validationError } = joi.default.date().validate(value);
|
|
204
|
-
if (validationError) throw new require_index$2.InvalidValueError(value, name, validationError);
|
|
205
|
-
instance.customFields[name] = joiValue.toISOString();
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
});
|
|
209
|
-
};
|
|
210
|
-
/**
|
|
211
|
-
* Hook to handle validation and custom fields during creation
|
|
212
|
-
*/
|
|
213
|
-
const beforeCreate = (scopeAttributes, modelOptions = {}, sadotOptions = { useCustomFieldsEntries: false }) => async (instance, options) => {
|
|
214
|
-
require_index.default.debug("sadot - before create hook");
|
|
215
|
-
const { fields } = options;
|
|
216
|
-
const modelType = instance.constructor.name;
|
|
217
|
-
const identifiers = require_scopeAttributes.default(instance, scopeAttributes);
|
|
218
|
-
const fieldDefinitions = await getFieldDefinitions({
|
|
219
|
-
modelType,
|
|
220
|
-
modelOptions,
|
|
221
|
-
identifiers,
|
|
222
|
-
options,
|
|
223
|
-
instance,
|
|
224
|
-
sadotOptions
|
|
225
|
-
});
|
|
226
|
-
const fieldsWithDefaultValue = fieldDefinitions.filter((def) => ![null, void 0].includes(def.defaultValue));
|
|
227
|
-
if (fieldsWithDefaultValue.length) {
|
|
228
|
-
instance.customFields ||= {};
|
|
229
|
-
fieldsWithDefaultValue.filter((def) => instance.customFields?.[def.name] === void 0).forEach(({ name, defaultValue }) => {
|
|
230
|
-
instance.customFields[name] = defaultValue;
|
|
231
|
-
});
|
|
232
|
-
}
|
|
233
|
-
let requiredFieldsNames;
|
|
234
|
-
if (sadotOptions.getRequiredCustomFields) requiredFieldsNames = await Promise.resolve(sadotOptions.getRequiredCustomFields(instance, fieldDefinitions, options));
|
|
235
|
-
else requiredFieldsNames = Array.from(new Set(fieldDefinitions.filter(({ required }) => required).map(({ name }) => name)));
|
|
236
|
-
const { customFields } = instance;
|
|
237
|
-
const fieldsNames = Object.keys(customFields ?? {});
|
|
238
|
-
const missingFields = requiredFieldsNames.filter((name) => !fieldsNames.includes(name));
|
|
239
|
-
if (missingFields?.length) throw new require_index$2.MissingRequiredCustomFieldError(missingFields);
|
|
240
|
-
await validateModel(instance, options, scopeAttributes, modelOptions, true);
|
|
241
|
-
formatDates(fieldDefinitions, instance);
|
|
242
|
-
const customFieldsIdx = fields.indexOf("customFields");
|
|
243
|
-
if (customFieldsIdx === -1 || !customFields || !Object.keys(customFields).length) return;
|
|
244
|
-
await require_updateInstanceValues.default({
|
|
245
|
-
modelId: instance.id,
|
|
246
|
-
modelType,
|
|
247
|
-
identifiers,
|
|
248
|
-
customFields,
|
|
249
|
-
options: {
|
|
250
|
-
useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,
|
|
251
|
-
transaction: options.transaction,
|
|
252
|
-
modelOptions
|
|
253
|
-
}
|
|
254
|
-
});
|
|
255
|
-
fields.splice(customFieldsIdx, 1);
|
|
256
|
-
};
|
|
257
|
-
/**
|
|
258
|
-
* Hook to handle validation and custom fields during update
|
|
259
|
-
*/
|
|
260
|
-
const beforeUpdate = (scopeAttributes, modelOptions = {}, sadotOptions = { useCustomFieldsEntries: false }) => async (instance, options) => {
|
|
261
|
-
require_index.default.debug("sadot - before update hook");
|
|
262
|
-
const { fields } = options;
|
|
263
|
-
const modelType = instance.constructor.name;
|
|
264
|
-
const identifiers = require_scopeAttributes.default(instance, scopeAttributes);
|
|
265
|
-
const fieldDefinitions = await getFieldDefinitions({
|
|
266
|
-
modelType,
|
|
267
|
-
modelOptions,
|
|
268
|
-
identifiers,
|
|
269
|
-
options,
|
|
270
|
-
instance,
|
|
271
|
-
sadotOptions
|
|
272
|
-
});
|
|
273
|
-
await validateModel(instance, options, scopeAttributes, modelOptions, false);
|
|
274
|
-
formatDates(fieldDefinitions, instance);
|
|
275
|
-
const customFieldsIdx = fields.indexOf("customFields");
|
|
276
|
-
if (customFieldsIdx > -1) {
|
|
277
|
-
const { customFields } = instance;
|
|
278
|
-
if (!Object.keys(customFields).length) return;
|
|
279
|
-
await require_updateInstanceValues.default({
|
|
280
|
-
modelId: instance.id,
|
|
281
|
-
modelType,
|
|
282
|
-
identifiers,
|
|
283
|
-
customFields,
|
|
284
|
-
options: {
|
|
285
|
-
useCustomFieldsEntries: sadotOptions.useCustomFieldsEntries,
|
|
286
|
-
transaction: options.transaction,
|
|
287
|
-
modelOptions
|
|
288
|
-
}
|
|
289
|
-
});
|
|
290
|
-
fields.splice(customFieldsIdx, 1);
|
|
291
|
-
}
|
|
292
|
-
};
|
|
293
|
-
/**
|
|
294
|
-
* Hook to enable individual hooks for bulk create operations
|
|
295
|
-
*/
|
|
296
|
-
const beforeBulkCreate = (options) => {
|
|
297
|
-
options.individualHooks = true;
|
|
298
|
-
};
|
|
299
|
-
/**
|
|
300
|
-
* Hook to enable individual hooks for bulk update operations
|
|
301
|
-
*/
|
|
302
|
-
const beforeBulkUpdate = (options) => {
|
|
303
|
-
options.individualHooks = true;
|
|
304
|
-
};
|
|
305
|
-
|
|
306
|
-
//#endregion
|
|
307
|
-
exports.beforeBulkCreate = beforeBulkCreate;
|
|
308
|
-
exports.beforeBulkUpdate = beforeBulkUpdate;
|
|
309
|
-
exports.beforeCreate = beforeCreate;
|
|
310
|
-
exports.beforeUpdate = beforeUpdate;
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`../utils/constants/index.cjs`),r=require(`../errors/index.cjs`),i=require(`../repository/definition.cjs`),a=require(`../repository/validator.cjs`),o=require(`../utils/scopeAttributes.cjs`),s=require(`./utils/updateInstanceValues.cjs`);let c=require(`joi`);c=e.__toESM(c);let l=require(`@autofleet/errors`),u=require(`ajv`);u=e.__toESM(u);let d=require(`ajv-formats`);d=e.__toESM(d);let f=require(`ajv-errors`);f=e.__toESM(f);const p=[`id`,`schema`,`modelType`,`entityId`,`disabled`],m=new u.default({allErrors:!0,strict:!1,strictTypes:!1,$data:!0});(0,d.default)(m),(0,f.default)(m);const h=(e,t)=>({__proto__:null,...e,...t}),g=async(e,n)=>{if(!e.id||!e.customFields||Object.keys(e.customFields).length===0)return e.customFields||{};try{let r=await e.constructor.findOne({where:{id:e.id},attributes:[`customFields`],transaction:n.transaction,raw:!0});if(r?.customFields){let n=h(r.customFields,e.customFields);return t.default.debug(`sadot - fetched complete custom fields for validation`,{fieldsCount:Object.keys(n).length,updateFieldsCount:Object.keys(e.customFields).length}),n}}catch(e){t.default.error(`sadot - error fetching complete model for validation`,{error:e})}return e.customFields||{}},_=e=>{let t={...e.dataValues};(e.changed?.()||[]).forEach(n=>{let r=e.previous?.(n);r!==void 0&&(t[n]=r)});let n=e.previous?.(`customFields`);return n!==void 0&&(t.customFields=n),t},v=e=>e.reduce((e,t)=>{let n=((t.instancePath||``).split(`/`).filter(Boolean).join(`.`).replace(/^after\./,``)+(t.keyword===`required`?`.${t.params?.missingProperty}`:``)).replace(/^\./,``)||`root`;return e[n]=t.message||`Invalid value`,e},{}),y=async(e,n,r,i={},s=!1)=>{let c=e.constructor.name;t.default.debug(`sadot - validating model`,{isCreate:s,modelType:c});let u=o.default(e,r);if(t.default.debug(`sadot - identifiers`,{identifiers:u}),!u||Object.keys(u).length===0){t.default.debug(`sadot - skipping validation: no identifiers`);return}let d=Object.values(u)[0];if(t.default.debug(`sadot - entityId`,{entityId:d}),!d){t.default.debug(`sadot - skipping validation: no entityId`);return}let f,y;n.transaction&&(n.transaction.validationsCache??=new Map,y=`${c}-${d}`,f=n.transaction.validationsCache.get(y)),f||(f=a.findAllByModelType(c,d,{transaction:n.transaction,attributes:p,modelOptions:i}),n.transaction&&n?.transaction?.validationsCache.set(y,f));let b=await f;if(t.default.debug(`sadot - validators found`,{count:b.length}),!b.length){t.default.debug(`sadot - skipping validation: no validators found`);return}let x=null;s||(x=_(e));let S=s?e.customFields||{}:await g(e,n);for(let n of b){let{schema:r}=n,i=r;if(t.default.debug(`sadot - validating with schema`,{schema:r,hasAfterProps:!!i.properties?.after,hasBeforeProps:!!i.properties?.before}),s){if(i.properties?.after){let t=m.compile({...r,properties:{after:i.properties.after}});if(!t(JSON.parse(JSON.stringify({after:{...e.dataValues,customFields:S}})))){let e=t.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),n=v(t.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:n})}}}else{let n=m.compile(i),r=h(e.dataValues);r.customFields=S;let a={before:x,after:r},o=n(JSON.parse(JSON.stringify(a)));if(t.default.debug(`sadot - validation result`,{isValid:o,test:{before:x,after:r}}),!o){let e=n.errors?.map(e=>`${e.instancePath||``} ${e.message||`Invalid value`}`).join(`, `),t=v(n.errors);throw new l.BadRequest([Error(`Validation failed for ${c}: ${e}`)],void 0,{customError:t})}}}},b=async({modelType:e,modelOptions:t,identifiers:n,options:r,instance:a,sadotOptions:o})=>{let{include:s,useEntityIdFromInclude:c}=t;if(o.hasTypeId&&a?.typeId)return i.findByModelTypeId(a.typeId,{withDisabled:!1,transaction:r.transaction,entityIds:n,modelType:e,modelOptions:t});let l={modelType:e,disabled:!1,...!c&&{entityId:n}};return i.findAll(l,{withDisabled:!1,transaction:r.transaction,include:s?.(n)})},x=(e,t)=>{(e||[]).forEach(e=>{let{fieldType:i,name:a}=e;if([n.CustomFieldDefinitionType.DATE,n.CustomFieldDefinitionType.DATETIME].includes(i)){let e=t.customFields?.[a];if(e){let{value:n,error:i}=c.default.date().validate(e);if(i)throw new r.InvalidValueError(e,a,i);t.customFields[a]=n.toISOString()}}})},S=(e,n={},i={useCustomFieldsEntries:!1})=>async(a,c)=>{t.default.debug(`sadot - before create hook`);let{fields:l}=c,u=a.constructor.name,d=o.default(a,e),f=await b({modelType:u,modelOptions:n,identifiers:d,options:c,instance:a,sadotOptions:i}),p=f.filter(e=>![null,void 0].includes(e.defaultValue));p.length&&(a.customFields||={},p.filter(e=>a.customFields?.[e.name]===void 0).forEach(({name:e,defaultValue:t})=>{a.customFields[e]=t}));let m;m=i.getRequiredCustomFields?await Promise.resolve(i.getRequiredCustomFields(a,f,c)):Array.from(new Set(f.filter(({required:e})=>e).map(({name:e})=>e)));let{customFields:h}=a,g=Object.keys(h??{}),_=m.filter(e=>!g.includes(e));if(_?.length)throw new r.MissingRequiredCustomFieldError(_);await y(a,c,e,n,!0),x(f,a);let v=l.indexOf(`customFields`);v===-1||!h||!Object.keys(h).length||(await s.default({modelId:a.id,modelType:u,identifiers:d,customFields:h,options:{useCustomFieldsEntries:i.useCustomFieldsEntries,transaction:c.transaction,modelOptions:n}}),l.splice(v,1))},C=(e,n={},r={useCustomFieldsEntries:!1})=>async(i,a)=>{t.default.debug(`sadot - before update hook`);let{fields:c}=a,l=i.constructor.name,u=o.default(i,e),d=await b({modelType:l,modelOptions:n,identifiers:u,options:a,instance:i,sadotOptions:r});await y(i,a,e,n,!1),x(d,i);let f=c.indexOf(`customFields`);if(f>-1){let{customFields:e}=i;if(!Object.keys(e).length)return;await s.default({modelId:i.id,modelType:l,identifiers:u,customFields:e,options:{useCustomFieldsEntries:r.useCustomFieldsEntries,transaction:a.transaction,modelOptions:n}}),c.splice(f,1)}},w=e=>{e.individualHooks=!0},T=e=>{e.individualHooks=!0};exports.beforeBulkCreate=w,exports.beforeBulkUpdate=T,exports.beforeCreate=S,exports.beforeUpdate=C;
|
|
2
|
+
//# sourceMappingURL=hooks.cjs.map
|