@autofleet/sadot 0.5.5-beta.9 → 0.6.0

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 (51) hide show
  1. package/dist/hooks/create.d.ts +2 -1
  2. package/dist/hooks/create.js +8 -4
  3. package/dist/hooks/enrich.d.ts +2 -1
  4. package/dist/hooks/enrich.js +17 -4
  5. package/dist/hooks/update.d.ts +2 -1
  6. package/dist/hooks/update.js +4 -3
  7. package/dist/index.d.ts +0 -1
  8. package/dist/index.js +1 -1
  9. package/dist/models/index.d.ts +3 -1
  10. package/dist/models/index.js +8 -2
  11. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.d.ts +10 -0
  12. package/dist/models/tests/contextAwareModels/ContextAwareTestModel.js +55 -0
  13. package/dist/models/tests/contextAwareModels/ContextTestModel.d.ts +13 -0
  14. package/dist/models/tests/contextAwareModels/ContextTestModel.js +47 -0
  15. package/dist/repository/definition.d.ts +7 -4
  16. package/dist/repository/definition.js +27 -15
  17. package/dist/repository/value.d.ts +5 -1
  18. package/dist/repository/value.js +13 -3
  19. package/dist/tests/helpers/database-config.d.ts +1 -0
  20. package/dist/tests/helpers/database-config.js +1 -0
  21. package/dist/tests/helpers/index.js +2 -0
  22. package/dist/tests/mocks/definition.mock.d.ts +6 -0
  23. package/dist/tests/mocks/definition.mock.js +7 -1
  24. package/dist/types/index.d.ts +20 -2
  25. package/dist/utils/init.d.ts +5 -4
  26. package/dist/utils/init.js +13 -7
  27. package/dist/utils/scopeAttributes.d.ts +2 -0
  28. package/dist/utils/scopeAttributes.js +11 -0
  29. package/package.json +20 -2
  30. package/src/api/v1/definition/index.ts +2 -4
  31. package/src/hooks/create.ts +13 -5
  32. package/src/hooks/enrich.ts +20 -4
  33. package/src/hooks/update.ts +6 -3
  34. package/src/index.ts +4 -2
  35. package/src/models/index.ts +7 -1
  36. package/src/models/tests/contextAwareModels/ContextAwareTestModel.ts +45 -0
  37. package/src/models/tests/contextAwareModels/ContextTestModel.ts +38 -0
  38. package/src/repository/definition.ts +38 -19
  39. package/src/repository/value.ts +18 -7
  40. package/src/tests/helpers/database-config.ts +1 -0
  41. package/src/tests/helpers/index.ts +5 -1
  42. package/src/tests/mocks/definition.mock.ts +7 -0
  43. package/src/types/index.ts +23 -3
  44. package/src/utils/init.ts +19 -10
  45. package/src/utils/scopeAttributes.ts +12 -0
  46. package/dist/tests/functional/searching/index.d.ts +0 -8
  47. package/dist/tests/functional/searching/index.js +0 -46
  48. package/dist/utils/helpers/index.d.ts +0 -22
  49. package/dist/utils/helpers/index.js +0 -28
  50. package/src/tests/functional/searching/index.ts +0 -39
  51. package/src/utils/helpers/index.ts +0 -50
@@ -1,3 +1,4 @@
1
+ import { ModelOptions } from '../types';
1
2
  /**
2
3
  * A hook to create the custom fields when updating a model (more then one instance).
3
4
  */
@@ -6,4 +7,4 @@ export declare const beforeBulkCreate: (options: any) => void;
6
7
  * A hook to create the custom fields when updating a model instance.
7
8
  * TODO - cleanup if update fail
8
9
  */
9
- export declare const beforeCreate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
10
+ export declare const beforeCreate: (scopeAttributes: string[], modelOptions?: ModelOptions) => (instance: any, options: any) => Promise<void>;
@@ -31,6 +31,7 @@ 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"));
34
35
  /**
35
36
  * A hook to create the custom fields when updating a model (more then one instance).
36
37
  */
@@ -44,13 +45,13 @@ exports.beforeBulkCreate = beforeBulkCreate;
44
45
  * A hook to create the custom fields when updating a model instance.
45
46
  * TODO - cleanup if update fail
46
47
  */
47
- const beforeCreate = (scopeAttributes) => async (instance, options) => {
48
+ const beforeCreate = (scopeAttributes, modelOptions = {}) => async (instance, options) => {
48
49
  logger_1.default.debug('sadot - before create hook');
49
50
  const { fields } = options;
50
51
  const modelType = instance.constructor.name;
51
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
52
+ const identifiers = (0, scopeAttributes_1.default)(instance, scopeAttributes);
52
53
  // get all model's required definitions
53
- const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers);
54
+ const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers, modelOptions);
54
55
  const customFieldsIdx = fields.indexOf('customFields');
55
56
  const { customFields } = instance;
56
57
  if (customFieldsIdx > -1 && customFields) {
@@ -59,7 +60,10 @@ const beforeCreate = (scopeAttributes) => async (instance, options) => {
59
60
  if (missingFields?.length > 0) {
60
61
  throw new errors_1.MissingRequiredCustomFieldError(missingFields);
61
62
  }
62
- await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
63
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, {
64
+ transaction: options.transaction,
65
+ modelOptions,
66
+ });
63
67
  // eslint-disable-next-line no-param-reassign
64
68
  fields.splice(customFieldsIdx, 1);
65
69
  }
@@ -1,6 +1,7 @@
1
+ import { ModelOptions } from '../types';
1
2
  type SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';
2
3
  /**
3
4
  * A hook to attach the custom fields when fetching a model instances.
4
5
  */
5
- declare const enrichResults: (modelType: string, scopeAttributes: string[], hookType?: SupportedHookTypes) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
6
+ declare const enrichResults: (modelType: string, scopeAttributes: string[], hookType?: SupportedHookTypes, modelOptions?: ModelOptions) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
6
7
  export default enrichResults;
@@ -22,10 +22,14 @@ 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
+ };
25
28
  Object.defineProperty(exports, "__esModule", { value: true });
26
29
  /* eslint-disable no-param-reassign */
27
30
  const ValueRepo = __importStar(require("../repository/value"));
28
31
  const DefinitionRepo = __importStar(require("../repository/definition"));
32
+ const scopeAttributes_1 = __importDefault(require("../utils/scopeAttributes"));
29
33
  /**
30
34
  * Serialize custom fields value into the format of {[name] -> [fieldData]}
31
35
  */
@@ -40,7 +44,7 @@ const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) =>
40
44
  /**
41
45
  * A hook to attach the custom fields when fetching a model instances.
42
46
  */
43
- const enrichResults = (modelType, scopeAttributes, hookType) => async (instancesOrInstance, options) => {
47
+ const enrichResults = (modelType, scopeAttributes, hookType, modelOptions = {}) => async (instancesOrInstance, options) => {
44
48
  if (options.originalAttributes?.length > 0
45
49
  && !options.originalAttributes?.includes?.('customFields')) {
46
50
  return;
@@ -50,14 +54,23 @@ const enrichResults = (modelType, scopeAttributes, hookType) => async (instances
50
54
  ? instancesOrInstance
51
55
  : [instancesOrInstance];
52
56
  instances = instances.filter(Boolean);
53
- const identifiers = instances.map((instance) => scopeAttributes
54
- .map((attr) => instance[attr])).flat();
57
+ const identifiers = (0, scopeAttributes_1.default)(instances, scopeAttributes);
55
58
  const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
56
59
  const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
57
60
  ...map,
58
61
  [identifier]: [],
59
62
  }), {});
60
- const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction });
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
+ }
61
74
  const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
62
75
  ...map,
63
76
  [definition.id]: definition,
@@ -1,3 +1,4 @@
1
+ import { ModelOptions } from '../types';
1
2
  /**
2
3
  * A hook to update the custom fields when updating a model (more then one instance).
3
4
  */
@@ -6,4 +7,4 @@ export declare const beforeBulkUpdate: (options: any) => void;
6
7
  * A hook to update the custom fields when updating a model instance.
7
8
  * TODO - cleanup if update fail
8
9
  */
9
- export declare const beforeUpdate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
10
+ export declare const beforeUpdate: (scopeAttributes: string[], modelOptions?: ModelOptions) => (instance: any, options: any) => Promise<void>;
@@ -29,6 +29,7 @@ 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"));
32
33
  /**
33
34
  * A hook to update the custom fields when updating a model (more then one instance).
34
35
  */
@@ -42,15 +43,15 @@ exports.beforeBulkUpdate = beforeBulkUpdate;
42
43
  * A hook to update the custom fields when updating a model instance.
43
44
  * TODO - cleanup if update fail
44
45
  */
45
- const beforeUpdate = (scopeAttributes) => async (instance, options) => {
46
+ const beforeUpdate = (scopeAttributes, modelOptions = {}) => async (instance, options) => {
46
47
  logger_1.default.debug('sadot - before update hook');
47
48
  const { fields } = options;
48
49
  const modelType = instance.constructor.name;
49
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
50
+ const identifiers = (0, scopeAttributes_1.default)(instance, scopeAttributes);
50
51
  const customFieldsIdx = fields.indexOf('customFields');
51
52
  if (customFieldsIdx > -1) {
52
53
  const { customFields } = instance;
53
- await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
54
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction, modelOptions });
54
55
  // eslint-disable-next-line no-param-reassign
55
56
  fields.splice(customFieldsIdx, 1);
56
57
  }
package/dist/index.d.ts CHANGED
@@ -3,7 +3,6 @@ import { Sequelize } from 'sequelize-typescript';
3
3
  import type { CustomFieldOptions, ModelFetcher } from './types';
4
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
@@ -25,7 +25,6 @@ const logger_1 = __importDefault(require("./utils/logger"));
25
25
  const init_1 = require("./utils/init");
26
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,6 +42,7 @@ 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);
45
+ (0, init_1.applyCustomAssociation)(models);
46
46
  logger_1.default.debug('sadot - custom fields finished initializing with models', models);
47
47
  return sequelize;
48
48
  };
@@ -2,7 +2,9 @@ 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';
5
7
  import AssociatedTestModel from './tests/AssociatedTestModel';
6
8
  declare const initTables: (sequelize: Sequelize, getUser: any) => Promise<void>;
7
9
  declare const initTestModels: (sequelize: Sequelize) => Promise<void>;
8
- export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, initTables, initTestModels, };
10
+ export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel, 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.AssociatedTestModel = exports.TestModel = exports.CustomFieldDefinition = exports.CustomFieldValue = void 0;
6
+ exports.initTestModels = exports.initTables = exports.ContextTestModel = exports.ContextAwareTestModel = 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,10 +13,14 @@ 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;
16
20
  const AssociatedTestModel_1 = __importDefault(require("./tests/AssociatedTestModel"));
17
21
  exports.AssociatedTestModel = AssociatedTestModel_1.default;
18
22
  const productionModels = [CustomFieldDefinition_1.default, CustomFieldValue_1.default];
19
- const testModels = [TestModel_1.default, AssociatedTestModel_1.default];
23
+ const testModels = [TestModel_1.default, AssociatedTestModel_1.default, ContextAwareTestModel_1.default, ContextTestModel_1.default];
20
24
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
21
25
  const SCHEMA_VERSION = 1;
22
26
  const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
@@ -82,6 +86,8 @@ const initTestModels = async (sequelize) => {
82
86
  logger_1.default.info('custom-fields: test models added');
83
87
  await TestModel_1.default.sync({ alter: true });
84
88
  await AssociatedTestModel_1.default.sync({ alter: true });
89
+ await ContextTestModel_1.default.sync({ alter: true });
90
+ await ContextAwareTestModel_1.default.sync({ alter: true });
85
91
  logger_1.default.info('custom-fields: test models synced');
86
92
  };
87
93
  exports.initTestModels = initTestModels;
@@ -0,0 +1,10 @@
1
+ import { Model } from 'sequelize-typescript';
2
+ import ContextTestModel from './ContextTestModel';
3
+ declare class ContextAwareTestModel extends Model {
4
+ id: string;
5
+ contextId: string;
6
+ coolAttribute?: boolean;
7
+ customFields?: any;
8
+ context: ContextTestModel;
9
+ }
10
+ export default ContextAwareTestModel;
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ /* eslint-disable @typescript-eslint/no-unused-vars */
16
+ const sequelize_typescript_1 = require("sequelize-typescript");
17
+ const ContextTestModel_1 = __importDefault(require("./ContextTestModel"));
18
+ let ContextAwareTestModel = class ContextAwareTestModel extends sequelize_typescript_1.Model {
19
+ };
20
+ __decorate([
21
+ sequelize_typescript_1.PrimaryKey,
22
+ (0, sequelize_typescript_1.Column)({
23
+ type: sequelize_typescript_1.DataType.UUID,
24
+ defaultValue: sequelize_typescript_1.DataType.UUIDV4,
25
+ allowNull: false,
26
+ }),
27
+ __metadata("design:type", String)
28
+ ], ContextAwareTestModel.prototype, "id", void 0);
29
+ __decorate([
30
+ (0, sequelize_typescript_1.ForeignKey)(() => ContextTestModel_1.default),
31
+ (0, sequelize_typescript_1.Column)({
32
+ type: sequelize_typescript_1.DataType.UUID,
33
+ }),
34
+ __metadata("design:type", String)
35
+ ], ContextAwareTestModel.prototype, "contextId", void 0);
36
+ __decorate([
37
+ (0, sequelize_typescript_1.Column)({
38
+ type: sequelize_typescript_1.DataType.BOOLEAN,
39
+ }),
40
+ __metadata("design:type", Boolean)
41
+ ], ContextAwareTestModel.prototype, "coolAttribute", void 0);
42
+ __decorate([
43
+ (0, sequelize_typescript_1.Column)({
44
+ type: sequelize_typescript_1.DataType.VIRTUAL,
45
+ }),
46
+ __metadata("design:type", Object)
47
+ ], ContextAwareTestModel.prototype, "customFields", void 0);
48
+ __decorate([
49
+ (0, sequelize_typescript_1.BelongsTo)(() => ContextTestModel_1.default),
50
+ __metadata("design:type", ContextTestModel_1.default)
51
+ ], ContextAwareTestModel.prototype, "context", void 0);
52
+ ContextAwareTestModel = __decorate([
53
+ (0, sequelize_typescript_1.Table)({ createdAt: false, updatedAt: false })
54
+ ], ContextAwareTestModel);
55
+ exports.default = ContextAwareTestModel;
@@ -0,0 +1,13 @@
1
+ import { Model } from 'sequelize-typescript';
2
+ declare enum EEntityTypes {
3
+ BUSINESS_MODEL = "businessModel",
4
+ CONTEXT = "context",
5
+ DEMAND_SOURCE = "demandSource",
6
+ FLEET = "fleet"
7
+ }
8
+ declare class ContextTestModel extends Model {
9
+ id: string;
10
+ entityId: string;
11
+ entityType: EEntityTypes;
12
+ }
13
+ export default ContextTestModel;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ /* eslint-disable @typescript-eslint/no-unused-vars */
13
+ const sequelize_typescript_1 = require("sequelize-typescript");
14
+ // eslint-disable-next-line no-shadow
15
+ var EEntityTypes;
16
+ (function (EEntityTypes) {
17
+ EEntityTypes["BUSINESS_MODEL"] = "businessModel";
18
+ EEntityTypes["CONTEXT"] = "context";
19
+ EEntityTypes["DEMAND_SOURCE"] = "demandSource";
20
+ EEntityTypes["FLEET"] = "fleet";
21
+ })(EEntityTypes || (EEntityTypes = {}));
22
+ let ContextTestModel = class ContextTestModel extends sequelize_typescript_1.Model {
23
+ };
24
+ __decorate([
25
+ sequelize_typescript_1.PrimaryKey,
26
+ (0, sequelize_typescript_1.Column)({
27
+ defaultValue: sequelize_typescript_1.DataType.UUIDV4,
28
+ type: sequelize_typescript_1.DataType.UUID,
29
+ }),
30
+ __metadata("design:type", String)
31
+ ], ContextTestModel.prototype, "id", void 0);
32
+ __decorate([
33
+ (0, sequelize_typescript_1.Column)({
34
+ type: sequelize_typescript_1.DataType.UUID,
35
+ }),
36
+ __metadata("design:type", String)
37
+ ], ContextTestModel.prototype, "entityId", void 0);
38
+ __decorate([
39
+ (0, sequelize_typescript_1.Column)({
40
+ type: sequelize_typescript_1.DataType.ENUM(...Object.values(EEntityTypes)),
41
+ }),
42
+ __metadata("design:type", String)
43
+ ], ContextTestModel.prototype, "entityType", void 0);
44
+ ContextTestModel = __decorate([
45
+ (0, sequelize_typescript_1.Table)({ createdAt: false, updatedAt: false })
46
+ ], ContextTestModel);
47
+ exports.default = ContextTestModel;
@@ -1,11 +1,14 @@
1
+ import { FindOptions, WhereOptions } from 'sequelize';
1
2
  import { CustomFieldDefinition } from '../models';
2
3
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
4
+ import { ModelOptions } from '../types';
3
5
  export declare const create: (data: CreateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
4
- export declare const findAll: (where: any, options?: any) => Promise<CustomFieldDefinition[]>;
6
+ export declare const findAll: (where: WhereOptions, options?: any) => Promise<CustomFieldDefinition[]>;
5
7
  export declare const findByIds: (ids: string[], options?: any) => Promise<CustomFieldDefinition[]>;
6
8
  export declare const findById: (id: string, options?: any) => Promise<CustomFieldDefinition | null>;
7
- export declare const findByEntityId: (entityId: string, options?: any) => Promise<CustomFieldDefinition[]>;
8
- export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: any) => Promise<CustomFieldDefinition[]>;
9
+ export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: FindOptions & {
10
+ modelOptions?: ModelOptions;
11
+ }) => Promise<CustomFieldDefinition[]>;
9
12
  export declare const findByWhere: (where: any) => Promise<CustomFieldDefinition | null>;
10
13
  export declare const findDefinitionsByModels: (modelTypes: string[], options?: any) => Promise<CustomFieldDefinition[]>;
11
14
  export declare const update: (id: string, data: UpdateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
@@ -14,4 +17,4 @@ export declare const destroy: (id: string) => Promise<any>;
14
17
  /**
15
18
  * Return the names of the required fields for a given model
16
19
  */
17
- export declare const getRequiredFields: (modelType: string, modelId: string | string[], entityId: string | string[]) => Promise<string[]>;
20
+ export declare const getRequiredFields: (modelType: string, modelId: string | string[], entityId: string | string[], modelOptions?: ModelOptions) => 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.findByEntityId = 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.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,6 +13,7 @@ const findAll = (where, options = { withDisabled: false }) => {
13
13
  where,
14
14
  transaction: options.transaction,
15
15
  raw: true,
16
+ include: options.include,
16
17
  });
17
18
  };
18
19
  exports.findAll = findAll;
@@ -26,19 +27,21 @@ const findById = (id, options = { withDisabled: false }) => {
26
27
  return models_1.CustomFieldDefinition.scope('userScope').findByPk(id);
27
28
  };
28
29
  exports.findById = findById;
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: {
30
+ const findByEntityIds = async (modelType, entityIds, options = {}) => {
31
+ const { include, useEntityIdFromInclude } = options.modelOptions;
32
+ const where = {
36
33
  modelType,
37
- entityId: entityIds,
38
- },
39
- transaction: options.transaction,
40
- raw: true,
41
- });
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
+ };
42
45
  exports.findByEntityIds = findByEntityIds;
43
46
  const findByWhere = (where) => models_1.CustomFieldDefinition.scope('userScope').findOne({
44
47
  where,
@@ -68,10 +71,19 @@ exports.destroy = destroy;
68
71
  /**
69
72
  * Return the names of the required fields for a given model
70
73
  */
71
- const getRequiredFields = async (modelType, modelId, entityId) => {
74
+ const getRequiredFields = async (modelType, modelId, entityId, modelOptions = {}) => {
72
75
  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
+ }
73
84
  const requiredFields = await models_1.CustomFieldDefinition.findAll({
74
- where: { required: true, modelType, entityId: { [sequelize_1.Op.in]: entityIds } },
85
+ where,
86
+ include: include?.(entityIds),
75
87
  logging: true,
76
88
  });
77
89
  const requiredFieldsNames = requiredFields.map((definition) => definition.name);
@@ -1,5 +1,7 @@
1
+ import type { FindOptions } from 'sequelize';
1
2
  import { CustomFieldValue } from '../models';
2
3
  import { CreateCustomFieldValue, ValuesToUpdate } from '../types/value';
4
+ import { ModelOptions } from '../types';
3
5
  export declare const findByModelIdAndDefinition: (modelId: string, customFieldDefinitionId: string) => Promise<CustomFieldValue[]>;
4
6
  export declare const create: (data: CreateCustomFieldValue, withAssociations?: boolean) => Promise<CustomFieldValue>;
5
7
  export declare const findAllValues: () => Promise<CustomFieldValue[]>;
@@ -20,5 +22,7 @@ export declare const findValuesByModelIds: (modelIds: string[], options?: any) =
20
22
  * Create new value record if not exists, but fails if value's definition not exist.
21
23
  * Return the updated values
22
24
  */
23
- export declare const updateValues: (modelType: string, modelId: string, identifiers: string[], valuesToUpdate: ValuesToUpdate, options?: any) => Promise<CustomFieldValue[]>;
25
+ export declare const updateValues: (modelType: string, modelId: string, identifiers: string[], valuesToUpdate: ValuesToUpdate, options?: FindOptions & {
26
+ modelOptions?: ModelOptions;
27
+ }) => Promise<CustomFieldValue[]>;
24
28
  export declare const deleteValue: (id: string, options?: any) => Promise<any>;
@@ -27,7 +27,6 @@ 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 */
31
30
  const models_1 = require("../models");
32
31
  const DefinitionRepo = __importStar(require("./definition"));
33
32
  const logger_1 = __importDefault(require("../utils/logger"));
@@ -73,11 +72,22 @@ exports.findValuesByModelIds = findValuesByModelIds;
73
72
  * Return the updated values
74
73
  */
75
74
  const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
76
- logger_1.default.info(`custom-fields: updating values for ${modelType} ${modelId}`, { valuesToUpdate });
77
75
  const names = Object.keys(valuesToUpdate);
78
- const fieldDefinitions = await DefinitionRepo.findAll({ modelType, name: names, entityId: identifiers }, { withDisabled: true, transaction: options.transaction }) || [];
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) }) || [];
79
88
  const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
80
89
  if (fieldDefinitions.length !== names.length) {
90
+ logger_1.default.info(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });
81
91
  const missingDefinitions = names.filter((name) => !fieldDefinitions.some((def) => def.name === name));
82
92
  throw new errors_1.MissingDefinitionError(missingDefinitions);
83
93
  }
@@ -4,6 +4,7 @@ declare const _default: {
4
4
  password: string;
5
5
  database: string;
6
6
  host: string;
7
+ port: string | number;
7
8
  dialect: string;
8
9
  define: {
9
10
  underscored: boolean;
@@ -6,6 +6,7 @@ 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,
9
10
  dialect: process.env.DB_TYPE || 'postgres',
10
11
  define: {
11
12
  underscored: true,
@@ -7,6 +7,8 @@ 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: {} });
10
12
  }
11
13
  };
12
14
  exports.cleanup = cleanup;
@@ -1,4 +1,10 @@
1
1
  import { CreateCustomFieldDefinition, CustomFieldDefinitionDTO } from '../../types/definition';
2
+ export declare const contextAwareFieldDefinition: {
3
+ name: string;
4
+ modelType: string;
5
+ fieldType: string;
6
+ entityType: string;
7
+ };
2
8
  export declare const coolFieldDefinition: CreateCustomFieldDefinition;
3
9
  export declare const coolFieldDefinition2: {
4
10
  name: string;
@@ -1,7 +1,13 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createDefinitions = exports.createDefinition = exports.rangeField = exports.enumField = exports.booleanField = exports.coolFieldDefinition3 = exports.coolFieldDefinition2 = exports.coolFieldDefinition = void 0;
3
+ exports.createDefinitions = exports.createDefinition = exports.rangeField = exports.enumField = exports.booleanField = exports.coolFieldDefinition3 = exports.coolFieldDefinition2 = exports.coolFieldDefinition = exports.contextAwareFieldDefinition = void 0;
4
4
  const uuid_1 = require("uuid");
5
+ exports.contextAwareFieldDefinition = {
6
+ name: 'cool field',
7
+ modelType: 'ContextAwareTestModel',
8
+ fieldType: 'number',
9
+ entityType: 'fleetId',
10
+ };
5
11
  exports.coolFieldDefinition = {
6
12
  name: 'cool field',
7
13
  modelType: 'TestModel',
@@ -1,13 +1,31 @@
1
+ import { IncludeOptions } from 'sequelize';
2
+ import { ModelCtor } from 'sequelize-typescript';
1
3
  export type ModelFetcher = (name: string) => any;
2
4
  export type ModelOptions = {
5
+ /**
6
+ * Include options for the model
7
+ */
8
+ include?: (entityIds: string[]) => IncludeOptions[];
9
+ /**
10
+ * Custom association for the model
11
+ * @param model - The model to associate with
12
+ */
13
+ customAssociation?: (model: ModelCtor) => void;
14
+ /**
15
+ * Whether to use the entity id from the instance per scope attribute
16
+ */
17
+ useEntityIdFromInclude?: boolean;
18
+ };
19
+ export type Models = {
3
20
  name: string;
4
- scopeAttributes: string[];
21
+ scopeAttributes: any[];
22
+ modelOptions?: ModelOptions;
5
23
  creationWebhookHandler?: (instance: any) => any;
6
24
  updateWebhookHandler?: (instance: any) => any;
7
25
  deletionWebhookHandler?: (instance: any) => any;
8
26
  };
9
27
  export type CustomFieldOptions = {
10
- models: ModelOptions[];
28
+ models: Models[];
11
29
  databaseConfig: any;
12
30
  getUser: () => any;
13
31
  };
@@ -1,4 +1,5 @@
1
- import type { ModelFetcher, ModelOptions } from '../types';
2
- export declare const addHooks: (models: ModelOptions[], getModel: ModelFetcher) => void;
3
- export declare const removeHooks: (models: ModelOptions[], getModel: ModelFetcher) => void;
4
- export declare const addScopes: (models: ModelOptions[], getModel: ModelFetcher) => void;
1
+ import type { ModelFetcher, Models } from '../types';
2
+ export declare const addHooks: (models: Models[], getModel: ModelFetcher) => void;
3
+ export declare const removeHooks: (models: Models[], getModel: ModelFetcher) => void;
4
+ export declare const addScopes: (models: Models[], getModel: ModelFetcher) => void;
5
+ export declare const applyCustomAssociation: (models: Models[]) => void;