@autofleet/sadot 0.6.2-temp-file-6 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/.env +3 -0
  2. package/dist/api/v1/definition/validations.d.ts +2 -2
  3. package/dist/api/v1/definition/validations.js +6 -19
  4. package/dist/api/v1/errors.js +1 -1
  5. package/dist/hooks/create.d.ts +1 -2
  6. package/dist/hooks/create.js +4 -8
  7. package/dist/hooks/enrich.d.ts +1 -3
  8. package/dist/hooks/enrich.js +4 -22
  9. package/dist/hooks/update.d.ts +1 -2
  10. package/dist/hooks/update.js +3 -4
  11. package/dist/index.d.ts +2 -3
  12. package/dist/index.js +1 -3
  13. package/dist/models/CustomFieldDefinition.d.ts +1 -1
  14. package/dist/models/CustomFieldDefinition.js +6 -11
  15. package/dist/models/CustomFieldValue.js +8 -3
  16. package/dist/models/index.d.ts +1 -3
  17. package/dist/models/index.js +2 -8
  18. package/dist/repository/definition.d.ts +4 -7
  19. package/dist/repository/definition.js +15 -27
  20. package/dist/repository/value.d.ts +2 -6
  21. package/dist/repository/value.js +3 -13
  22. package/dist/scopes/filter.d.ts +1 -1
  23. package/dist/scopes/filter.js +4 -16
  24. package/dist/tests/helpers/database-config.d.ts +0 -1
  25. package/dist/tests/helpers/database-config.js +0 -1
  26. package/dist/tests/helpers/index.js +0 -2
  27. package/dist/tests/mocks/definition.mock.d.ts +3 -9
  28. package/dist/tests/mocks/definition.mock.js +10 -14
  29. package/dist/tests/mocks/testModel.d.ts +1 -1
  30. package/dist/types/index.d.ts +2 -20
  31. package/dist/utils/constants/index.d.ts +1 -18
  32. package/dist/utils/constants/index.js +3 -19
  33. package/dist/utils/init.d.ts +4 -5
  34. package/dist/utils/init.js +9 -16
  35. package/dist/utils/validations/custom-fields.d.ts +2 -0
  36. package/dist/utils/validations/{schema/custom-fields.js → custom-fields.js} +2 -1
  37. package/dist/utils/validations/custom.d.ts +15 -0
  38. package/dist/utils/validations/custom.js +42 -0
  39. package/dist/utils/validations/index.d.ts +2 -2
  40. package/dist/utils/validations/index.js +15 -15
  41. package/dist/utils/validations/type.d.ts +14 -10
  42. package/dist/utils/validations/type.js +48 -0
  43. package/dist/utils/validations/validators.d.ts +12 -0
  44. package/dist/utils/validations/validators.js +33 -0
  45. package/package.json +2 -2
  46. package/src/api/v1/definition/validations.ts +1 -1
  47. package/src/index.ts +1 -0
  48. package/src/models/CustomFieldDefinition.ts +7 -5
  49. package/src/utils/constants/index.ts +1 -15
  50. package/src/utils/helpers/index.ts +1 -1
  51. package/src/utils/validations/index.ts +1 -1
  52. package/src/utils/validations/type.ts +12 -13
  53. package/src/utils/validations/validators/index.ts +1 -10
  54. package/src/utils/validations/validators/select.validator.ts +3 -1
  55. package/src/utils/validations/validators/status.validator.ts +4 -2
  56. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +0 -10
  57. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +0 -55
  58. package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +0 -13
  59. package/dist/models/tests/contextAwareModels/ContextTestModel.js +0 -47
  60. package/dist/tests/functional/searching/index.d.ts +0 -8
  61. package/dist/tests/functional/searching/index.js +0 -44
  62. package/dist/utils/helpers/index.d.ts +0 -25
  63. package/dist/utils/helpers/index.js +0 -34
  64. package/dist/utils/scopeAttributes.d.ts +0 -2
  65. package/dist/utils/scopeAttributes.js +0 -11
  66. package/dist/utils/validations/schema/custom-fields.d.ts +0 -3
  67. package/dist/utils/validations/validators/index.d.ts +0 -14
  68. package/dist/utils/validations/validators/index.js +0 -40
  69. package/dist/utils/validations/validators/select.validator.d.ts +0 -5
  70. package/dist/utils/validations/validators/select.validator.js +0 -9
  71. package/dist/utils/validations/validators/status.validator.d.ts +0 -12
  72. package/dist/utils/validations/validators/status.validator.js +0 -9
package/.env ADDED
@@ -0,0 +1,3 @@
1
+ NODE_ENV=test
2
+ # LOG_LEVEL=debug
3
+ # SADOT_DEBUG=true
@@ -1,2 +1,2 @@
1
- export declare const validateCustomFieldDefinitionCreation: (payload: any) => Promise<any>;
2
- export declare const validateCustomFieldDefinitionUpdate: (payload: any) => Promise<any>;
1
+ export declare const validateCustomFieldDefinitionCreation: (payload: any) => any;
2
+ export declare const validateCustomFieldDefinitionUpdate: (payload: any) => any;
@@ -4,31 +4,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.validateCustomFieldDefinitionUpdate = exports.validateCustomFieldDefinitionCreation = void 0;
7
- const joi_1 = __importDefault(require("joi"));
8
- const constants_1 = require("../../../utils/constants");
9
- /**
10
- * Schema for the validation of custom field definition
11
- * The only custom validation is for
12
- * {@link CustomFieldDefinitionType.SELECT SELECT}
13
- * and
14
- * {@link CustomFieldDefinitionType.STATUS STATUS}
15
- * field types.
16
- * The rest of the field types are validated by Joi
17
- */
7
+ const joi_1 = __importDefault(require("@hapi/joi"));
8
+ const type_1 = require("../../../utils/validations/type");
18
9
  const ValidationSchema = joi_1.default.when('fieldType', {
19
- is: constants_1.CustomFieldDefinitionType.SELECT,
10
+ is: type_1.CustomFieldDefinitionType.SELECT,
20
11
  then: joi_1.default.array().items(joi_1.default.string()).min(1).unique(),
21
12
  otherwise: joi_1.default.any(),
22
- }).when('fieldType', {
23
- is: constants_1.CustomFieldDefinitionType.STATUS,
24
- then: joi_1.default.string().min(1).required(),
25
- otherwise: joi_1.default.any(),
26
13
  });
27
14
  const CustomFieldDefinitionCreationSchema = joi_1.default.object({
28
15
  name: joi_1.default.string().required(),
29
16
  displayName: joi_1.default.string().required(),
30
17
  validation: ValidationSchema,
31
- fieldType: joi_1.default.string().valid(...Object.values(constants_1.CustomFieldDefinitionType)).required(),
18
+ fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)).required(),
32
19
  entityId: joi_1.default.string().guid().required(),
33
20
  entityType: joi_1.default.string().required(),
34
21
  description: joi_1.default.string(),
@@ -38,8 +25,8 @@ const CustomFieldDefinitionCreationSchema = joi_1.default.object({
38
25
  const CustomFieldDefinitionUpdateSchema = joi_1.default.object({
39
26
  displayName: joi_1.default.string(),
40
27
  validation: ValidationSchema,
41
- fieldType: joi_1.default.string().valid(...Object.values(constants_1.CustomFieldDefinitionType)),
42
- description: joi_1.default.string().allow(null),
28
+ fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)),
29
+ description: joi_1.default.string(),
43
30
  required: joi_1.default.boolean(),
44
31
  disabled: joi_1.default.boolean(),
45
32
  });
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const errors_1 = require("@autofleet/errors");
4
- const joi_1 = require("joi");
4
+ const joi_1 = require("@hapi/joi");
5
5
  const sequelize_1 = require("sequelize");
6
6
  exports.default = (err, res, additionalData = undefined) => {
7
7
  let error = err;
@@ -1,4 +1,3 @@
1
- import type { ModelOptions } from '../types';
2
1
  /**
3
2
  * A hook to create the custom fields when updating a model (more then one instance).
4
3
  */
@@ -7,4 +6,4 @@ export declare const beforeBulkCreate: (options: any) => void;
7
6
  * A hook to create the custom fields when updating a model instance.
8
7
  * TODO - cleanup if update fail
9
8
  */
10
- export declare const beforeCreate: (scopeAttributes: string[], modelOptions?: ModelOptions) => (instance: any, options: any) => Promise<void>;
9
+ export declare const beforeCreate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
@@ -31,7 +31,6 @@ const logger_1 = __importDefault(require("../utils/logger"));
31
31
  const ValueRepo = __importStar(require("../repository/value"));
32
32
  const DefinitionRepo = __importStar(require("../repository/definition"));
33
33
  const errors_1 = require("../errors");
34
- const scopeAttributes_1 = __importDefault(require("../utils/scopeAttributes"));
35
34
  /**
36
35
  * A hook to create the custom fields when updating a model (more then one instance).
37
36
  */
@@ -45,13 +44,13 @@ exports.beforeBulkCreate = beforeBulkCreate;
45
44
  * A hook to create the custom fields when updating a model instance.
46
45
  * TODO - cleanup if update fail
47
46
  */
48
- const beforeCreate = (scopeAttributes, modelOptions = {}) => async (instance, options) => {
47
+ const beforeCreate = (scopeAttributes) => async (instance, options) => {
49
48
  logger_1.default.debug('sadot - before create hook');
50
49
  const { fields } = options;
51
50
  const modelType = instance.constructor.name;
52
- const identifiers = (0, scopeAttributes_1.default)(instance, scopeAttributes);
51
+ const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
53
52
  // get all model's required definitions
54
- const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers, modelOptions);
53
+ const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers);
55
54
  const customFieldsIdx = fields.indexOf('customFields');
56
55
  const { customFields } = instance;
57
56
  if (customFieldsIdx > -1 && customFields) {
@@ -60,10 +59,7 @@ const beforeCreate = (scopeAttributes, modelOptions = {}) => async (instance, op
60
59
  if (missingFields?.length > 0) {
61
60
  throw new errors_1.MissingRequiredCustomFieldError(missingFields);
62
61
  }
63
- await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, {
64
- transaction: options.transaction,
65
- modelOptions,
66
- });
62
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
67
63
  // eslint-disable-next-line no-param-reassign
68
64
  fields.splice(customFieldsIdx, 1);
69
65
  }
@@ -1,7 +1,5 @@
1
- import type { ModelOptions } from '../types';
2
- type SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';
3
1
  /**
4
2
  * A hook to attach the custom fields when fetching a model instances.
5
3
  */
6
- declare const enrichResults: (modelType: string, scopeAttributes: string[], hookType?: SupportedHookTypes, modelOptions?: ModelOptions) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
4
+ declare const enrichResults: (modelType: string, scopeAttributes: string[]) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
7
5
  export default enrichResults;
@@ -22,14 +22,10 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __importDefault = (this && this.__importDefault) || function (mod) {
26
- return (mod && mod.__esModule) ? mod : { "default": mod };
27
- };
28
25
  Object.defineProperty(exports, "__esModule", { value: true });
29
26
  /* eslint-disable no-param-reassign */
30
27
  const ValueRepo = __importStar(require("../repository/value"));
31
28
  const DefinitionRepo = __importStar(require("../repository/definition"));
32
- const scopeAttributes_1 = __importDefault(require("../utils/scopeAttributes"));
33
29
  /**
34
30
  * Serialize custom fields value into the format of {[name] -> [fieldData]}
35
31
  */
@@ -44,7 +40,7 @@ const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) =>
44
40
  /**
45
41
  * A hook to attach the custom fields when fetching a model instances.
46
42
  */
47
- const enrichResults = (modelType, scopeAttributes, hookType, modelOptions = {}) => async (instancesOrInstance, options) => {
43
+ const enrichResults = (modelType, scopeAttributes) => async (instancesOrInstance, options) => {
48
44
  if (options.originalAttributes?.length > 0
49
45
  && !options.originalAttributes?.includes?.('customFields')) {
50
46
  return;
@@ -54,23 +50,14 @@ const enrichResults = (modelType, scopeAttributes, hookType, modelOptions = {})
54
50
  ? instancesOrInstance
55
51
  : [instancesOrInstance];
56
52
  instances = instances.filter(Boolean);
57
- const identifiers = (0, scopeAttributes_1.default)(instances, scopeAttributes);
53
+ const identifiers = instances.map((instance) => scopeAttributes
54
+ .map((attr) => instance[attr])).flat();
58
55
  const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
59
56
  const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
60
57
  ...map,
61
58
  [identifier]: [],
62
59
  }), {});
63
- const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction, modelOptions });
64
- if (modelOptions?.include && modelOptions.useEntityIdFromInclude) {
65
- // if we pass useEntityIdFromInclude,
66
- // map the entity from the options to the identifierCustomFieldDefinitionsMapping
67
- modelOptions.include(identifiers).forEach(({ model }) => {
68
- customFieldDefinitions.forEach((cfd) => {
69
- const entityId = cfd[`${model.name}.entityId`];
70
- identifierCustomFieldDefinitionsMapping[entityId] = [];
71
- });
72
- });
73
- }
60
+ const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction });
74
61
  const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
75
62
  ...map,
76
63
  [definition.id]: definition,
@@ -116,11 +103,6 @@ const enrichResults = (modelType, scopeAttributes, hookType, modelOptions = {})
116
103
  // if raw:
117
104
  delete instance?.[attribute];
118
105
  });
119
- // sequelize will think customFields changed also in 'find', so we need to mark it as unchanged
120
- if (hookType === 'afterFind') {
121
- // changed() could be undefined, i.e in raw: true
122
- instance?.changed?.('customFields', false);
123
- }
124
106
  });
125
107
  };
126
108
  exports.default = enrichResults;
@@ -1,4 +1,3 @@
1
- import type { ModelOptions } from '../types';
2
1
  /**
3
2
  * A hook to update the custom fields when updating a model (more then one instance).
4
3
  */
@@ -7,4 +6,4 @@ export declare const beforeBulkUpdate: (options: any) => void;
7
6
  * A hook to update the custom fields when updating a model instance.
8
7
  * TODO - cleanup if update fail
9
8
  */
10
- export declare const beforeUpdate: (scopeAttributes: string[], modelOptions?: ModelOptions) => (instance: any, options: any) => Promise<void>;
9
+ export declare const beforeUpdate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
@@ -29,7 +29,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.beforeUpdate = exports.beforeBulkUpdate = void 0;
30
30
  const logger_1 = __importDefault(require("../utils/logger"));
31
31
  const ValueRepo = __importStar(require("../repository/value"));
32
- const scopeAttributes_1 = __importDefault(require("../utils/scopeAttributes"));
33
32
  /**
34
33
  * A hook to update the custom fields when updating a model (more then one instance).
35
34
  */
@@ -43,15 +42,15 @@ exports.beforeBulkUpdate = beforeBulkUpdate;
43
42
  * A hook to update the custom fields when updating a model instance.
44
43
  * TODO - cleanup if update fail
45
44
  */
46
- const beforeUpdate = (scopeAttributes, modelOptions = {}) => async (instance, options) => {
45
+ const beforeUpdate = (scopeAttributes) => async (instance, options) => {
47
46
  logger_1.default.debug('sadot - before update hook');
48
47
  const { fields } = options;
49
48
  const modelType = instance.constructor.name;
50
- const identifiers = (0, scopeAttributes_1.default)(instance, scopeAttributes);
49
+ const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
51
50
  const customFieldsIdx = fields.indexOf('customFields');
52
51
  if (customFieldsIdx > -1) {
53
52
  const { customFields } = instance;
54
- await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction, modelOptions });
53
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
55
54
  // eslint-disable-next-line no-param-reassign
56
55
  fields.splice(customFieldsIdx, 1);
57
56
  }
package/dist/index.d.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import type { Application } from 'express';
2
- import type { Sequelize } from 'sequelize-typescript';
2
+ import { Sequelize } from 'sequelize-typescript';
3
3
  import type { CustomFieldOptions, ModelFetcher } from './types';
4
- export * from './utils/validations/schema/custom-fields';
4
+ export * from './utils/validations/custom-fields';
5
5
  export * from './utils/constants';
6
- export * from './utils/helpers';
7
6
  /**
8
7
  * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
9
8
  * @see {@link 'custom-fields/config'} for configurations
package/dist/index.js CHANGED
@@ -23,9 +23,8 @@ const api_1 = __importDefault(require("./api"));
23
23
  const db_1 = __importDefault(require("./utils/db"));
24
24
  const logger_1 = __importDefault(require("./utils/logger"));
25
25
  const init_1 = require("./utils/init");
26
- __exportStar(require("./utils/validations/schema/custom-fields"), exports);
26
+ __exportStar(require("./utils/validations/custom-fields"), exports);
27
27
  __exportStar(require("./utils/constants"), exports);
28
- __exportStar(require("./utils/helpers"), exports);
29
28
  /**
30
29
  * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
31
30
  * @see {@link 'custom-fields/config'} for configurations
@@ -43,7 +42,6 @@ const useCustomFields = async (app, getModel, options) => {
43
42
  (0, init_1.addHooks)(models, getModel);
44
43
  await (0, models_1.initTables)(sequelize, options.getUser);
45
44
  (0, init_1.addScopes)(models, getModel);
46
- (0, init_1.applyCustomAssociation)(models);
47
45
  logger_1.default.debug('sadot - custom fields finished initializing with models', models);
48
46
  return sequelize;
49
47
  };
@@ -1,5 +1,5 @@
1
1
  import { Model } from 'sequelize-typescript';
2
- import { CustomFieldDefinitionType } from '../utils/constants';
2
+ import { CustomFieldDefinitionType } from '../utils/validations/type';
3
3
  import { CustomFieldValue } from '.';
4
4
  declare class CustomFieldDefinition extends Model {
5
5
  id: string;
@@ -8,17 +8,15 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  var __metadata = (this && this.__metadata) || function (k, v) {
9
9
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ /* eslint-disable @typescript-eslint/no-unused-vars */
13
+ /* eslint-disable indent */
15
14
  const sequelize_typescript_1 = require("sequelize-typescript");
16
- const constants_1 = require("../utils/constants");
17
- const validators_1 = require("../utils/validations/validators");
15
+ const custom_1 = require("../utils/validations/custom");
16
+ const type_1 = require("../utils/validations/type");
18
17
  const _1 = require(".");
19
18
  const events_1 = require("../events");
20
19
  const errors_1 = require("../errors");
21
- const logger_1 = __importDefault(require("../utils/logger"));
22
20
  let CustomFieldDefinition = class CustomFieldDefinition extends sequelize_typescript_1.Model {
23
21
  static displayNameDefaultValue(instance) {
24
22
  if (!instance?.displayName) {
@@ -59,7 +57,7 @@ __decorate([
59
57
  ], CustomFieldDefinition.prototype, "displayName", void 0);
60
58
  __decorate([
61
59
  (0, sequelize_typescript_1.Is)('SupportedType', (value) => {
62
- if (!Object.values(constants_1.CustomFieldDefinitionType).includes(value)) {
60
+ if (!Object.values(type_1.CustomFieldDefinitionType).includes(value)) {
63
61
  throw new errors_1.UnsupportedCustomFieldTypeError(`"${value}" is not a supported type.`);
64
62
  }
65
63
  }),
@@ -157,10 +155,7 @@ CustomFieldDefinition = __decorate([
157
155
  timestamps: true,
158
156
  validate: {
159
157
  validationByType() {
160
- // Verify the validation is provided if needed
161
- if (!this.validation && validators_1.CustomValidationTypes[this.fieldType]) {
162
- // TODO: enforce the validation-object schema based on the fieldType
163
- logger_1.default.error(`No custom validation for custom field type ${this.fieldType} found`);
158
+ if (!(0, custom_1.validateValidation)(this.fieldType, this.validation)) {
164
159
  throw new errors_1.UnsupportedCustomValidationError(`Validation provided for "${this.fieldType}" is not supported`);
165
160
  }
166
161
  },
@@ -31,11 +31,16 @@ var __importStar = (this && this.__importStar) || function (mod) {
31
31
  var __metadata = (this && this.__metadata) || function (k, v) {
32
32
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
33
33
  };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
34
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
+ /* eslint-disable @typescript-eslint/no-unused-vars */
39
+ /* eslint-disable indent */
35
40
  const sequelize_typescript_1 = require("sequelize-typescript");
36
41
  const events_1 = require("../events");
37
42
  const _1 = require(".");
38
- const validations_1 = require("../utils/validations");
43
+ const validations_1 = __importDefault(require("../utils/validations"));
39
44
  const CustomFieldDefinitionRepo = __importStar(require("../repository/definition"));
40
45
  const errors_1 = require("../errors");
41
46
  let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Model {
@@ -49,7 +54,7 @@ let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Mod
49
54
  instances.forEach((instance) => {
50
55
  const { validation, fieldType, } = definitions
51
56
  .find((definition) => definition.id === instance.customFieldDefinitionId);
52
- const isValid = (0, validations_1.validateValue)(instance.value, fieldType, validation);
57
+ const isValid = (0, validations_1.default)(instance.value, fieldType, validation);
53
58
  if (!isValid) {
54
59
  throw new errors_1.InvalidValueError(instance.value, fieldType);
55
60
  }
@@ -60,7 +65,7 @@ let CustomFieldValue = class CustomFieldValue extends sequelize_typescript_1.Mod
60
65
  // eslint-disable-next-line max-len
61
66
  const cfd = await CustomFieldDefinitionRepo.findById(customFieldDefinitionId, { withDisabled: true });
62
67
  const { validation, fieldType } = cfd;
63
- const isValid = (0, validations_1.validateValue)(instance.value, fieldType, validation);
68
+ const isValid = (0, validations_1.default)(instance.value, fieldType, validation);
64
69
  if (!isValid) {
65
70
  throw new errors_1.InvalidValueError(instance.value, fieldType);
66
71
  }
@@ -2,9 +2,7 @@ import type { Sequelize } from 'sequelize-typescript';
2
2
  import CustomFieldDefinition from './CustomFieldDefinition';
3
3
  import CustomFieldValue from './CustomFieldValue';
4
4
  import TestModel from './tests/TestModel';
5
- import ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';
6
- import ContextTestModel from './tests/contextAwareModels/ContextTestModel';
7
5
  import AssociatedTestModel from './tests/AssociatedTestModel';
8
6
  declare const initTables: (sequelize: Sequelize, getUser: any) => Promise<void>;
9
7
  declare const initTestModels: (sequelize: Sequelize) => Promise<void>;
10
- export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel, initTables, initTestModels, };
8
+ export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, initTables, initTestModels, };
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.initTestModels = exports.initTables = exports.ContextTestModel = exports.ContextAwareTestModel = exports.AssociatedTestModel = exports.TestModel = exports.CustomFieldDefinition = exports.CustomFieldValue = void 0;
6
+ exports.initTestModels = exports.initTables = exports.AssociatedTestModel = exports.TestModel = exports.CustomFieldDefinition = exports.CustomFieldValue = void 0;
7
7
  /* eslint-disable no-param-reassign */
8
8
  const sequelize_1 = require("sequelize");
9
9
  const logger_1 = __importDefault(require("../utils/logger"));
@@ -13,14 +13,10 @@ const CustomFieldValue_1 = __importDefault(require("./CustomFieldValue"));
13
13
  exports.CustomFieldValue = CustomFieldValue_1.default;
14
14
  const TestModel_1 = __importDefault(require("./tests/TestModel"));
15
15
  exports.TestModel = TestModel_1.default;
16
- const ContextAwareTestModel_1 = __importDefault(require("./tests/contextAwareModels/ContextAwareTestModel"));
17
- exports.ContextAwareTestModel = ContextAwareTestModel_1.default;
18
- const ContextTestModel_1 = __importDefault(require("./tests/contextAwareModels/ContextTestModel"));
19
- exports.ContextTestModel = ContextTestModel_1.default;
20
16
  const AssociatedTestModel_1 = __importDefault(require("./tests/AssociatedTestModel"));
21
17
  exports.AssociatedTestModel = AssociatedTestModel_1.default;
22
18
  const productionModels = [CustomFieldDefinition_1.default, CustomFieldValue_1.default];
23
- const testModels = [TestModel_1.default, AssociatedTestModel_1.default, ContextAwareTestModel_1.default, ContextTestModel_1.default];
19
+ const testModels = [TestModel_1.default, AssociatedTestModel_1.default];
24
20
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
25
21
  const SCHEMA_VERSION = 1;
26
22
  const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
@@ -86,8 +82,6 @@ const initTestModels = async (sequelize) => {
86
82
  logger_1.default.info('custom-fields: test models added');
87
83
  await TestModel_1.default.sync({ alter: true });
88
84
  await AssociatedTestModel_1.default.sync({ alter: true });
89
- await ContextTestModel_1.default.sync({ alter: true });
90
- await ContextAwareTestModel_1.default.sync({ alter: true });
91
85
  logger_1.default.info('custom-fields: test models synced');
92
86
  };
93
87
  exports.initTestModels = initTestModels;
@@ -1,14 +1,11 @@
1
- import { type FindOptions, type WhereOptions } from 'sequelize';
2
1
  import { CustomFieldDefinition } from '../models';
3
2
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
4
- import type { ModelOptions } from '../types';
5
3
  export declare const create: (data: CreateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
6
- export declare const findAll: (where: WhereOptions, options?: any) => Promise<CustomFieldDefinition[]>;
4
+ export declare const findAll: (where: any, options?: any) => Promise<CustomFieldDefinition[]>;
7
5
  export declare const findByIds: (ids: string[], options?: any) => Promise<CustomFieldDefinition[]>;
8
6
  export declare const findById: (id: string, options?: any) => Promise<CustomFieldDefinition | null>;
9
- export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: FindOptions & {
10
- modelOptions?: ModelOptions;
11
- }) => Promise<CustomFieldDefinition[]>;
7
+ export declare const findByEntityId: (entityId: string, options?: any) => Promise<CustomFieldDefinition[]>;
8
+ export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: any) => Promise<CustomFieldDefinition[]>;
12
9
  export declare const findByWhere: (where: any) => Promise<CustomFieldDefinition | null>;
13
10
  export declare const findDefinitionsByModels: (modelTypes: string[], options?: any) => Promise<CustomFieldDefinition[]>;
14
11
  export declare const update: (id: string, data: UpdateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
@@ -17,4 +14,4 @@ export declare const destroy: (id: string) => Promise<any>;
17
14
  /**
18
15
  * Return the names of the required fields for a given model
19
16
  */
20
- export declare const getRequiredFields: (modelType: string, modelId: string | string[], entityId: string | string[], modelOptions?: ModelOptions) => Promise<string[]>;
17
+ export declare const getRequiredFields: (modelType: string, modelId: string | string[], entityId: string | string[]) => Promise<string[]>;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRequiredFields = exports.destroy = exports.disable = exports.update = exports.findDefinitionsByModels = exports.findByWhere = exports.findByEntityIds = exports.findById = exports.findByIds = exports.findAll = exports.create = void 0;
3
+ exports.getRequiredFields = exports.destroy = exports.disable = exports.update = exports.findDefinitionsByModels = exports.findByWhere = exports.findByEntityIds = exports.findByEntityId = exports.findById = exports.findByIds = exports.findAll = exports.create = void 0;
4
4
  const sequelize_1 = require("sequelize");
5
5
  const models_1 = require("../models");
6
6
  const create = (data) => models_1.CustomFieldDefinition.create(data);
@@ -13,7 +13,6 @@ const findAll = (where, options = { withDisabled: false }) => {
13
13
  where,
14
14
  transaction: options.transaction,
15
15
  raw: true,
16
- include: options.include,
17
16
  });
18
17
  };
19
18
  exports.findAll = findAll;
@@ -27,21 +26,19 @@ const findById = (id, options = { withDisabled: false }) => {
27
26
  return models_1.CustomFieldDefinition.scope('userScope').findByPk(id);
28
27
  };
29
28
  exports.findById = findById;
30
- const findByEntityIds = async (modelType, entityIds, options = {}) => {
31
- const { include, useEntityIdFromInclude } = options.modelOptions;
32
- const where = {
29
+ const findByEntityId = async (entityId, options = {}) => models_1.CustomFieldDefinition.findAll({
30
+ where: { entityId },
31
+ transaction: options.transaction,
32
+ });
33
+ exports.findByEntityId = findByEntityId;
34
+ const findByEntityIds = async (modelType, entityIds, options = {}) => models_1.CustomFieldDefinition.findAll({
35
+ where: {
33
36
  modelType,
34
- };
35
- if (!useEntityIdFromInclude) {
36
- where.entityId = entityIds;
37
- }
38
- return models_1.CustomFieldDefinition.findAll({
39
- where,
40
- transaction: options.transaction,
41
- include: include?.(entityIds),
42
- raw: true,
43
- });
44
- };
37
+ entityId: entityIds,
38
+ },
39
+ transaction: options.transaction,
40
+ raw: true,
41
+ });
45
42
  exports.findByEntityIds = findByEntityIds;
46
43
  const findByWhere = (where) => models_1.CustomFieldDefinition.scope('userScope').findOne({
47
44
  where,
@@ -71,19 +68,10 @@ exports.destroy = destroy;
71
68
  /**
72
69
  * Return the names of the required fields for a given model
73
70
  */
74
- const getRequiredFields = async (modelType, modelId, entityId, modelOptions = {}) => {
71
+ const getRequiredFields = async (modelType, modelId, entityId) => {
75
72
  const entityIds = Array.isArray(entityId) ? entityId : [entityId];
76
- const { include, useEntityIdFromInclude } = modelOptions;
77
- const where = {
78
- modelType,
79
- required: true,
80
- };
81
- if (!useEntityIdFromInclude) {
82
- where.entityId = entityIds;
83
- }
84
73
  const requiredFields = await models_1.CustomFieldDefinition.findAll({
85
- where,
86
- include: include?.(entityIds),
74
+ where: { required: true, modelType, entityId: { [sequelize_1.Op.in]: entityIds } },
87
75
  logging: true,
88
76
  });
89
77
  const requiredFieldsNames = requiredFields.map((definition) => definition.name);
@@ -1,7 +1,5 @@
1
- import type { FindOptions } from 'sequelize';
2
1
  import { CustomFieldValue } from '../models';
3
- import type { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
4
- import type { ModelOptions } from '../types';
2
+ import { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
5
3
  export declare const findByModelIdAndDefinition: (modelId: string, customFieldDefinitionId: string) => Promise<CustomFieldValue[]>;
6
4
  export declare const create: (data: CreateCustomFieldValue, withAssociations?: boolean) => Promise<CustomFieldValue>;
7
5
  export declare const findAllValues: () => Promise<CustomFieldValue[]>;
@@ -22,7 +20,5 @@ export declare const findValuesByModelIds: (modelIds: string[], options?: any) =
22
20
  * Create new value record if not exists, but fails if value's definition not exist.
23
21
  * Return the updated values
24
22
  */
25
- export declare const updateValues: (modelType: string, modelId: string, identifiers: string[], valuesToUpdate: ValuesToUpdate, options?: FindOptions & {
26
- modelOptions?: ModelOptions;
27
- }) => Promise<CustomFieldValue[]>;
23
+ export declare const updateValues: (modelType: string, modelId: string, identifiers: string[], valuesToUpdate: ValuesToUpdate, options?: any) => Promise<CustomFieldValue[]>;
28
24
  export declare const deleteValue: (id: string, options?: any) => Promise<any>;
@@ -27,6 +27,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.deleteValue = exports.updateValues = exports.findValuesByModelIds = exports.findValuesByModelId = exports.findAllValues = exports.create = exports.findByModelIdAndDefinition = void 0;
30
+ /* eslint-disable max-len */
30
31
  const models_1 = require("../models");
31
32
  const DefinitionRepo = __importStar(require("./definition"));
32
33
  const logger_1 = __importDefault(require("../utils/logger"));
@@ -72,22 +73,11 @@ exports.findValuesByModelIds = findValuesByModelIds;
72
73
  * Return the updated values
73
74
  */
74
75
  const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
76
+ logger_1.default.info(`custom-fields: updating values for ${modelType} ${modelId}`, { valuesToUpdate });
75
77
  const names = Object.keys(valuesToUpdate);
76
- logger_1.default.info(`custom-fields: updating values for ${modelType} ${modelId}`, {
77
- names, options, valuesToUpdate, identifiers,
78
- });
79
- const { modelOptions, transaction } = options;
80
- const where = {
81
- modelType,
82
- name: names,
83
- };
84
- if (!options.modelOptions?.useEntityIdFromInclude) {
85
- where.entityId = identifiers;
86
- }
87
- const fieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true, transaction, include: modelOptions.include?.(identifiers) }) || [];
78
+ const fieldDefinitions = await DefinitionRepo.findAll({ modelType, name: names, entityId: identifiers }, { withDisabled: true, transaction: options.transaction }) || [];
88
79
  const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
89
80
  if (fieldDefinitions.length !== names.length) {
90
- logger_1.default.info(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });
91
81
  const missingDefinitions = names.filter((name) => !fieldDefinitions.some((def) => def.name === name));
92
82
  throw new errors_1.MissingDefinitionError(missingDefinitions);
93
83
  }
@@ -1,4 +1,4 @@
1
- import { type WhereOptions } from 'sequelize';
1
+ import { WhereOptions } from 'sequelize';
2
2
  /**
3
3
  * Type representing possible condition values.
4
4
  * Currently supporting strings and arrays of strings.
@@ -4,8 +4,7 @@ exports.scopeName = exports.customFieldsFilterScope = void 0;
4
4
  /* eslint-disable import/prefer-default-export */
5
5
  const sequelize_1 = require("sequelize");
6
6
  const sequelize_typescript_1 = require("sequelize-typescript");
7
- const common_types_1 = require("@autofleet/common-types");
8
- const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
7
+ const constants_1 = require("../utils/constants");
9
8
  /**
10
9
  * A Sequelize scope for filtering models by custom fields.
11
10
  * This scope builds a WHERE clause to be applied on the main query.
@@ -14,27 +13,16 @@ const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
14
13
  * @returns {Function} - A function that takes conditions and returns the Sequelize options object.
15
14
  */
16
15
  const customFieldsFilterScope = (name) => (conditions) => {
17
- if (!conditions || Object.keys(conditions).length === 0) {
18
- return {};
19
- }
20
16
  // Build the WHERE clause for custom field filtering
21
- const conditionsStrings = Object.entries(conditions)
17
+ const customFieldConditions = Object.entries(conditions)
22
18
  .map(([key, value]) => {
23
19
  if (Array.isArray(value)) {
24
- if (value.length === 0) {
25
- // if empty array, the condition is ignored
26
- return false;
27
- }
28
20
  const values = value.map((v) => `'${v}'`).join(',');
29
21
  return `custom_fields->>'${key}' IN (${values})`;
30
22
  }
31
23
  return `custom_fields->>'${key}' = '${value}'`;
32
24
  })
33
- .filter(Boolean);
34
- if (conditionsStrings.length === 0) {
35
- return {};
36
- }
37
- const customFieldConditions = conditionsStrings.join(' AND ');
25
+ .join(' AND ');
38
26
  const subQuery = `${'SELECT model_id FROM ('
39
27
  + 'SELECT cv.model_id, jsonb_object_agg(cd.name, cv.value) AS custom_fields '
40
28
  + 'FROM custom_field_values AS cv '
@@ -52,4 +40,4 @@ const customFieldsFilterScope = (name) => (conditions) => {
52
40
  };
53
41
  };
54
42
  exports.customFieldsFilterScope = customFieldsFilterScope;
55
- exports.scopeName = CUSTOM_FIELDS_FILTER_SCOPE;
43
+ exports.scopeName = constants_1.CUSTOM_FIELDS_FILTER_SCOPE;
@@ -4,7 +4,6 @@ declare const _default: {
4
4
  password: string;
5
5
  database: string;
6
6
  host: string;
7
- port: string | number;
8
7
  dialect: string;
9
8
  define: {
10
9
  underscored: boolean;
@@ -6,7 +6,6 @@ exports.default = {
6
6
  password: process.env.DB_PASSWORD || null,
7
7
  database: process.env.DB_NAME || 'sadot_package_test',
8
8
  host: process.env.DB_HOST || '127.0.0.1',
9
- port: process.env.DB_PORT || 5432,
10
9
  dialect: process.env.DB_TYPE || 'postgres',
11
10
  define: {
12
11
  underscored: true,
@@ -7,8 +7,6 @@ const cleanup = async () => {
7
7
  if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
8
8
  await models_1.CustomFieldDefinition.unscoped().destroy({ where: {} });
9
9
  await models_1.TestModel.destroy({ where: {} });
10
- await models_1.ContextAwareTestModel.destroy({ where: {} });
11
- await models_1.ContextTestModel.destroy({ where: {} });
12
10
  }
13
11
  };
14
12
  exports.cleanup = cleanup;