@autofleet/sadot 0.5.4-beta.2 → 0.5.4-beta.21

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 (47) hide show
  1. package/.env +3 -0
  2. package/dist/api/v1/definition/index.js +1 -1
  3. package/dist/hooks/create.d.ts +2 -1
  4. package/dist/hooks/create.js +7 -5
  5. package/dist/hooks/enrich.d.ts +2 -1
  6. package/dist/hooks/enrich.js +11 -5
  7. package/dist/hooks/update.d.ts +2 -1
  8. package/dist/hooks/update.js +4 -2
  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/ContextModel.d.ts +13 -0
  14. package/dist/models/tests/contextAwareModels/ContextModel.js +47 -0
  15. package/dist/repository/definition.d.ts +2 -2
  16. package/dist/repository/definition.js +13 -8
  17. package/dist/repository/value.js +8 -2
  18. package/dist/tests/helpers/database-config.d.ts +1 -0
  19. package/dist/tests/helpers/database-config.js +1 -0
  20. package/dist/tests/helpers/index.js +2 -0
  21. package/dist/tests/mocks/definition.mock.d.ts +6 -0
  22. package/dist/tests/mocks/definition.mock.js +7 -1
  23. package/dist/tests/mocks/testModel.d.ts +1 -1
  24. package/dist/tests/mocks/testModel.js +1 -1
  25. package/dist/types/index.d.ts +5 -1
  26. package/dist/utils/init.d.ts +4 -4
  27. package/dist/utils/init.js +6 -6
  28. package/dist/utils/scopeAttributes.d.ts +3 -0
  29. package/dist/utils/scopeAttributes.js +16 -0
  30. package/package.json +21 -3
  31. package/src/api/v1/definition/index.ts +2 -4
  32. package/src/hooks/create.ts +10 -5
  33. package/src/hooks/enrich.ts +14 -5
  34. package/src/hooks/find.ts +1 -0
  35. package/src/hooks/update.ts +6 -2
  36. package/src/models/index.ts +7 -1
  37. package/src/models/tests/contextAwareModels/ContextAwareTestModel.ts +45 -0
  38. package/src/models/tests/contextAwareModels/ContextModel.ts +38 -0
  39. package/src/repository/definition.ts +15 -13
  40. package/src/repository/value.ts +11 -5
  41. package/src/tests/helpers/database-config.ts +1 -0
  42. package/src/tests/helpers/index.ts +5 -1
  43. package/src/tests/mocks/definition.mock.ts +7 -0
  44. package/src/tests/mocks/testModel.ts +1 -1
  45. package/src/types/index.ts +6 -2
  46. package/src/utils/init.ts +12 -10
  47. package/src/utils/scopeAttributes.ts +18 -0
package/.env ADDED
@@ -0,0 +1,3 @@
1
+ DB_USERNAME=emiltayeb
2
+ DB_PASSWORD=123456
3
+ NODE_ENV=test
@@ -83,7 +83,7 @@ router.get('/', async (req, res) => {
83
83
  if (entityIds?.length > 0) {
84
84
  where.entityId = entityIds;
85
85
  }
86
- const customFieldDefinitions = await DefinitionRepo.findAll({ ...where }, { withDisabled: true });
86
+ const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true });
87
87
  return res.json(customFieldDefinitions);
88
88
  }
89
89
  catch (err) {
@@ -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>;
@@ -27,10 +27,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
29
  exports.beforeCreate = exports.beforeBulkCreate = void 0;
30
- const logger_1 = __importDefault(require("../utils/logger"));
31
30
  const ValueRepo = __importStar(require("../repository/value"));
32
31
  const DefinitionRepo = __importStar(require("../repository/definition"));
33
32
  const errors_1 = require("../errors");
33
+ const scopeAttributes_1 = __importDefault(require("../utils/scopeAttributes"));
34
34
  /**
35
35
  * A hook to create the custom fields when updating a model (more then one instance).
36
36
  */
@@ -44,11 +44,11 @@ exports.beforeBulkCreate = beforeBulkCreate;
44
44
  * A hook to create the custom fields when updating a model instance.
45
45
  * TODO - cleanup if update fail
46
46
  */
47
- const beforeCreate = (scopeAttributes) => async (instance, options) => {
48
- logger_1.default.debug('sadot - before create hook');
47
+ const beforeCreate = (scopeAttributes, modelOptions = {}) => async (instance, options) => {
49
48
  const { fields } = options;
50
49
  const modelType = instance.constructor.name;
51
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
50
+ const { scopeAttributeReplacer } = modelOptions;
51
+ const identifiers = await (0, scopeAttributes_1.default)(instance, scopeAttributes, scopeAttributeReplacer);
52
52
  // get all model's required definitions
53
53
  const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers);
54
54
  const customFieldsIdx = fields.indexOf('customFields');
@@ -59,7 +59,9 @@ const beforeCreate = (scopeAttributes) => async (instance, options) => {
59
59
  if (missingFields?.length > 0) {
60
60
  throw new errors_1.MissingRequiredCustomFieldError(missingFields);
61
61
  }
62
- await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
62
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, {
63
+ transaction: options.transaction,
64
+ });
63
65
  // eslint-disable-next-line no-param-reassign
64
66
  fields.splice(customFieldsIdx, 1);
65
67
  }
@@ -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[], getScope: any, hookType?: SupportedHookTypes, modelOptions?: ModelOptions) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
6
7
  export default enrichResults;
@@ -22,10 +22,15 @@ 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 logger_1 = __importDefault(require("../utils/logger"));
33
+ const scopeAttributes_1 = __importDefault(require("../utils/scopeAttributes"));
29
34
  /**
30
35
  * Serialize custom fields value into the format of {[name] -> [fieldData]}
31
36
  */
@@ -40,7 +45,8 @@ const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) =>
40
45
  /**
41
46
  * A hook to attach the custom fields when fetching a model instances.
42
47
  */
43
- const enrichResults = (modelType, scopeAttributes, hookType) => async (instancesOrInstance, options) => {
48
+ const enrichResults = (modelType, scopeAttributes, getScope, hookType, modelOptions = {}) => async (instancesOrInstance, options) => {
49
+ const { scopeAttributeReplacer } = modelOptions;
44
50
  if (options.originalAttributes?.length > 0
45
51
  && !options.originalAttributes?.includes?.('customFields')) {
46
52
  return;
@@ -50,20 +56,20 @@ const enrichResults = (modelType, scopeAttributes, hookType) => async (instances
50
56
  ? instancesOrInstance
51
57
  : [instancesOrInstance];
52
58
  instances = instances.filter(Boolean);
53
- const identifiers = instances.map((instance) => scopeAttributes
54
- .map((attr) => instance[attr])).flat();
59
+ const identifiers = await (0, scopeAttributes_1.default)(instances, scopeAttributes, scopeAttributeReplacer);
60
+ logger_1.default.info('enrichResults - sadot - indentifiers: ', identifiers);
55
61
  const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
56
62
  const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
57
63
  ...map,
58
64
  [identifier]: [],
59
65
  }), {});
60
- const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction });
66
+ const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction, getScope });
61
67
  const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
62
68
  ...map,
63
69
  [definition.id]: definition,
64
70
  }), {});
65
71
  customFieldDefinitions.forEach((cfd) => {
66
- identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
72
+ identifierCustomFieldDefinitionsMapping[cfd.entityId]?.push(cfd);
67
73
  });
68
74
  // Get the values per instates ids:
69
75
  const instancesIds = instances.map((i) => i[primaryKey]);
@@ -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,11 +43,12 @@ 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;
49
+ const { scopeAttributeReplacer } = modelOptions;
48
50
  const modelType = instance.constructor.name;
49
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
51
+ const identifiers = await (0, scopeAttributes_1.default)(instance, scopeAttributes, scopeAttributeReplacer);
50
52
  const customFieldsIdx = fields.indexOf('customFields');
51
53
  if (customFieldsIdx > -1) {
52
54
  const { customFields } = instance;
@@ -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 ContextModel from './tests/contextAwareModels/ContextModel';
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, ContextModel, 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.ContextModel = 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 ContextModel_1 = __importDefault(require("./tests/contextAwareModels/ContextModel"));
19
+ exports.ContextModel = ContextModel_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, ContextModel_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 ContextModel_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 ContextModel from './ContextModel';
3
+ declare class ContextAwareTestModel extends Model {
4
+ id: string;
5
+ contextId: string;
6
+ coolAttribute?: boolean;
7
+ customFields?: any;
8
+ context: ContextModel;
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 ContextModel_1 = __importDefault(require("./ContextModel"));
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)(() => ContextModel_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)(() => ContextModel_1.default),
50
+ __metadata("design:type", ContextModel_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 ContextModel extends Model {
9
+ id: string;
10
+ entityId: string;
11
+ entityType: EEntityTypes;
12
+ }
13
+ export default ContextModel;
@@ -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 ContextModel = class ContextModel 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
+ ], ContextModel.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
+ ], ContextModel.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
+ ], ContextModel.prototype, "entityType", void 0);
44
+ ContextModel = __decorate([
45
+ (0, sequelize_typescript_1.Table)({ createdAt: false, updatedAt: false })
46
+ ], ContextModel);
47
+ exports.default = ContextModel;
@@ -1,10 +1,10 @@
1
+ import { WhereOptions } from 'sequelize';
1
2
  import { CustomFieldDefinition } from '../models';
2
3
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
3
4
  export declare const create: (data: CreateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
4
- export declare const findAll: (where: any, options?: any) => Promise<CustomFieldDefinition[]>;
5
+ export declare const findAll: (where: WhereOptions, options?: any) => Promise<CustomFieldDefinition[]>;
5
6
  export declare const findByIds: (ids: string[], options?: any) => Promise<CustomFieldDefinition[]>;
6
7
  export declare const findById: (id: string, options?: any) => Promise<CustomFieldDefinition | null>;
7
- export declare const findByEntityId: (entityId: string, options?: any) => Promise<CustomFieldDefinition[]>;
8
8
  export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: any) => Promise<CustomFieldDefinition[]>;
9
9
  export declare const findByWhere: (where: any) => Promise<CustomFieldDefinition | null>;
10
10
  export declare const findDefinitionsByModels: (modelTypes: string[], options?: any) => Promise<CustomFieldDefinition[]>;
@@ -1,18 +1,23 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  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;
6
+ 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
7
  const sequelize_1 = require("sequelize");
5
8
  const models_1 = require("../models");
9
+ const logger_1 = __importDefault(require("../utils/logger"));
6
10
  const create = (data) => models_1.CustomFieldDefinition.create(data);
7
11
  exports.create = create;
8
12
  const findAll = (where, options = { withDisabled: false }) => {
9
13
  const queryModel = options.withDisabled
10
14
  ? models_1.CustomFieldDefinition.unscoped()
11
15
  : models_1.CustomFieldDefinition;
16
+ logger_1.default.info('sadot - whereQuery', { options });
12
17
  return queryModel.scope('userScope').findAll({
13
18
  where,
14
- transaction: options.transaction,
15
19
  raw: true,
20
+ logging: true,
16
21
  });
17
22
  };
18
23
  exports.findAll = findAll;
@@ -26,17 +31,13 @@ const findById = (id, options = { withDisabled: false }) => {
26
31
  return models_1.CustomFieldDefinition.scope('userScope').findByPk(id);
27
32
  };
28
33
  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
34
  const findByEntityIds = async (modelType, entityIds, options = {}) => models_1.CustomFieldDefinition.findAll({
35
35
  where: {
36
36
  modelType,
37
37
  entityId: entityIds,
38
38
  },
39
39
  transaction: options.transaction,
40
+ include: options.include,
40
41
  raw: true,
41
42
  });
42
43
  exports.findByEntityIds = findByEntityIds;
@@ -71,7 +72,11 @@ exports.destroy = destroy;
71
72
  const getRequiredFields = async (modelType, modelId, entityId) => {
72
73
  const entityIds = Array.isArray(entityId) ? entityId : [entityId];
73
74
  const requiredFields = await models_1.CustomFieldDefinition.findAll({
74
- where: { required: true, modelType, entityId: { [sequelize_1.Op.in]: entityIds } },
75
+ where: {
76
+ required: true,
77
+ modelType,
78
+ entityId: { [sequelize_1.Op.in]: entityIds },
79
+ },
75
80
  logging: true,
76
81
  });
77
82
  const requiredFieldsNames = requiredFields.map((definition) => definition.name);
@@ -73,9 +73,15 @@ exports.findValuesByModelIds = findValuesByModelIds;
73
73
  * Return the updated values
74
74
  */
75
75
  const updateValues = async (modelType, modelId, identifiers, valuesToUpdate, options = {}) => {
76
- logger_1.default.info(`custom-fields: updating values for ${modelType} ${modelId}`, { valuesToUpdate });
77
76
  const names = Object.keys(valuesToUpdate);
78
- const fieldDefinitions = await DefinitionRepo.findAll({ modelType, name: names, entityId: identifiers }, { withDisabled: true, transaction: options.transaction }) || [];
77
+ logger_1.default.info(`custom-fields: updating values for ${modelType} ${modelId}`, {
78
+ names, options, valuesToUpdate, entityId: identifiers,
79
+ });
80
+ const fieldDefinitions = (await DefinitionRepo.findAll({
81
+ modelType,
82
+ name: names,
83
+ entityId: identifiers,
84
+ }, { withDisabled: true, transaction: options.transaction })) || [];
79
85
  const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
80
86
  if (fieldDefinitions.length !== names.length) {
81
87
  logger_1.default.info(`custom-fields: missing definitions for ${modelType} ${modelId}`, { names, fieldDefinitions });
@@ -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.ContextModel.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,5 +1,5 @@
1
1
  import { TestModel } from '../../models';
2
- export declare const createTestModel: (payload?: {}) => Promise<TestModel>;
2
+ export declare const createTestModel: (payload?: {}, model?: any) => any;
3
3
  export declare const createTestModels: (fleetId: any, total: number) => Promise<TestModel[]>;
4
4
  export declare const upsertTestModel: (payload: any) => Promise<[TestModel, boolean]>;
5
5
  export declare const destroyTestModels: () => Promise<number>;
@@ -2,7 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getTestModelWithAssociation = exports.createTestModelWithAssociation = exports.updateTestModel = exports.getSomeTestModels = exports.getTestModel = exports.destroyTestModels = exports.upsertTestModel = exports.createTestModels = exports.createTestModel = void 0;
4
4
  const models_1 = require("../../models");
5
- const createTestModel = (payload = {}) => models_1.TestModel.create(payload);
5
+ const createTestModel = (payload = {}, model = models_1.TestModel) => model.create(payload);
6
6
  exports.createTestModel = createTestModel;
7
7
  const createTestModels = (fleetId, total) => {
8
8
  const models = [];
@@ -1,13 +1,17 @@
1
1
  export type ModelFetcher = (name: string) => any;
2
2
  export type ModelOptions = {
3
+ scopeAttributeReplacer?: (attributes?: string[]) => Promise<any>;
4
+ };
5
+ export type Models = {
3
6
  name: string;
4
7
  scopeAttributes: string[];
8
+ modelOptions?: ModelOptions;
5
9
  creationWebhookHandler?: (instance: any) => any;
6
10
  updateWebhookHandler?: (instance: any) => any;
7
11
  deletionWebhookHandler?: (instance: any) => any;
8
12
  };
9
13
  export type CustomFieldOptions = {
10
- models: ModelOptions[];
14
+ models: Models[];
11
15
  databaseConfig: any;
12
16
  getUser: () => any;
13
17
  };
@@ -1,4 +1,4 @@
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;
@@ -12,7 +12,7 @@ const scopes_1 = require("../scopes");
12
12
  const logger_1 = __importDefault(require("./logger"));
13
13
  const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
14
14
  const addHooks = (models, getModel) => {
15
- models.forEach(async ({ name, scopeAttributes }) => {
15
+ models.forEach(async ({ name, scopeAttributes, modelOptions, }) => {
16
16
  try {
17
17
  const model = getModel(name);
18
18
  if (!model) {
@@ -31,11 +31,11 @@ const addHooks = (models, getModel) => {
31
31
  model.addHook('beforeFind', 'sadot-beforeFind', (0, hooks_1.beforeFind)(scopeAttributes));
32
32
  model.addHook('beforeBulkCreate', 'sadot-beforeBulkCreate', hooks_1.beforeBulkCreate);
33
33
  model.addHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate', hooks_1.beforeBulkUpdate);
34
- model.addHook('beforeCreate', 'sadot-beforeCreate', (0, hooks_1.beforeCreate)(scopeAttributes));
35
- model.addHook('beforeUpdate', 'sadot-beforeUpdate', (0, hooks_1.beforeUpdate)(scopeAttributes));
36
- model.addHook('afterFind', 'sadot-afterFind', (0, hooks_1.enrichResults)(name, scopeAttributes, 'afterFind'));
37
- model.addHook('afterUpdate', 'sadot-afterUpdate', (0, hooks_1.enrichResults)(name, scopeAttributes));
38
- model.addHook('afterCreate', 'sadot-afterCreate', (0, hooks_1.enrichResults)(name, scopeAttributes));
34
+ model.addHook('beforeCreate', 'sadot-beforeCreate', (0, hooks_1.beforeCreate)(scopeAttributes, modelOptions));
35
+ model.addHook('beforeUpdate', 'sadot-beforeUpdate', (0, hooks_1.beforeUpdate)(scopeAttributes, modelOptions));
36
+ model.addHook('afterFind', 'sadot-afterFind', (0, hooks_1.enrichResults)(name, scopeAttributes, 'afterFind', null, modelOptions));
37
+ model.addHook('afterUpdate', 'sadot-afterUpdate', (0, hooks_1.enrichResults)(name, scopeAttributes, null, null, modelOptions));
38
+ model.addHook('afterCreate', 'sadot-afterCreate', (0, hooks_1.enrichResults)(name, scopeAttributes, null, null, modelOptions));
39
39
  }
40
40
  catch (e) {
41
41
  logger_1.default.error(`Could not add custom fields hook to model ${name}. `, e);
@@ -0,0 +1,3 @@
1
+ import { ModelOptions } from '../types';
2
+ declare const getScopeAttributes: (instance: any, scopeAttributes: string[], scopeAttributeReplacer?: ModelOptions['scopeAttributeReplacer']) => Promise<any[]>;
3
+ export default getScopeAttributes;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const getIdentifiers = (instance, scopeAttributes) => {
4
+ if (Array.isArray(instance)) {
5
+ return instance.map((ins) => scopeAttributes.map((attr) => ins[attr])).flat();
6
+ }
7
+ return scopeAttributes.map((attribute) => instance[attribute]);
8
+ };
9
+ const getScopeAttributes = async (instance, scopeAttributes, scopeAttributeReplacer) => {
10
+ let identifiers = getIdentifiers(instance, scopeAttributes);
11
+ if (scopeAttributeReplacer) {
12
+ identifiers = await scopeAttributeReplacer(identifiers);
13
+ }
14
+ return identifiers;
15
+ };
16
+ exports.default = getScopeAttributes;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/sadot",
3
- "version": "0.5.4-beta.2",
3
+ "version": "0.5.4-beta.21",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -9,7 +9,24 @@
9
9
  "linter": "./node_modules/.bin/eslint .",
10
10
  "test": "jest --forceExit --runInBand",
11
11
  "coverage": "jest --coverage --forceExit --runInBand && rm -rf ./coverage",
12
- "dev": "nodemon"
12
+ "build-to-local-repo": "npm run build && cp -r dist/* ../$REPO/node_modules/$npm_package_name/dist",
13
+ "dev": "nodemon",
14
+ "watch": "npm-watch build-to-local-repo"
15
+ },
16
+ "watch": {
17
+ "build-to-local-repo": {
18
+ "extensions": [
19
+ "js",
20
+ "jsx",
21
+ "ts",
22
+ "tsx",
23
+ "css"
24
+ ],
25
+ "patterns": [
26
+ "src"
27
+ ],
28
+ "quiet": false
29
+ }
13
30
  },
14
31
  "dependencies": {
15
32
  "@autofleet/common-types": "^1.7.29",
@@ -18,6 +35,7 @@
18
35
  "@autofleet/logger": "^2.0.5",
19
36
  "express": "^4.18.2",
20
37
  "joi": "^17.7.0",
38
+ "npm-watch": "^0.11.0",
21
39
  "pg": "^8.10.0",
22
40
  "reflect-metadata": "^0.1.13",
23
41
  "sequelize": "^6.31.1",
@@ -41,4 +59,4 @@
41
59
  },
42
60
  "author": "Autofleet",
43
61
  "license": "ISC"
44
- }
62
+ }
@@ -65,10 +65,8 @@ router.get('/', async (req, res) => {
65
65
  if (entityIds?.length > 0) {
66
66
  where.entityId = entityIds;
67
67
  }
68
- const customFieldDefinitions = await DefinitionRepo.findAll(
69
- { ...where },
70
- { withDisabled: true },
71
- );
68
+ const customFieldDefinitions = await DefinitionRepo.findAll(where,
69
+ { withDisabled: true });
72
70
  return res.json(customFieldDefinitions);
73
71
  } catch (err) {
74
72
  logger.error('Failed to fetch custom field definitions', err);
@@ -1,7 +1,8 @@
1
- import logger from '../utils/logger';
2
1
  import * as ValueRepo from '../repository/value';
3
2
  import * as DefinitionRepo from '../repository/definition';
4
3
  import { MissingRequiredCustomFieldError } from '../errors';
4
+ import { ModelOptions } from '../types';
5
+ import getScopeAttributes from '../utils/scopeAttributes';
5
6
 
6
7
  /**
7
8
  * A hook to create the custom fields when updating a model (more then one instance).
@@ -15,14 +16,15 @@ export const beforeBulkCreate = (options): void => {
15
16
  * A hook to create the custom fields when updating a model instance.
16
17
  * TODO - cleanup if update fail
17
18
  */
18
- export const beforeCreate = (scopeAttributes: string[]) => async (
19
+ export const beforeCreate = (scopeAttributes: string[], modelOptions: ModelOptions = {}) => async (
19
20
  instance,
20
21
  options,
21
22
  ): Promise<void> => {
22
- logger.debug('sadot - before create hook');
23
23
  const { fields } = options;
24
24
  const modelType = instance.constructor.name;
25
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
25
+ const { scopeAttributeReplacer } = modelOptions;
26
+
27
+ const identifiers = await getScopeAttributes(instance, scopeAttributes, scopeAttributeReplacer);
26
28
  // get all model's required definitions
27
29
  const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType,
28
30
  instance.id,
@@ -41,8 +43,11 @@ export const beforeCreate = (scopeAttributes: string[]) => async (
41
43
  instance.id,
42
44
  identifiers,
43
45
  customFields,
44
- { transaction: options.transaction },
46
+ {
47
+ transaction: options.transaction,
48
+ },
45
49
  );
50
+
46
51
  // eslint-disable-next-line no-param-reassign
47
52
  fields.splice(customFieldsIdx, 1);
48
53
  } else if (requiredFieldsNames?.length > 0) {
@@ -4,6 +4,9 @@ import * as DefinitionRepo from '../repository/definition';
4
4
  import CustomFieldValue from '../models/CustomFieldValue';
5
5
  import CustomFieldDefinition from '../models/CustomFieldDefinition';
6
6
  import { SerializedCustomFields } from '../types/definition';
7
+ import logger from '../utils/logger';
8
+ import { ModelOptions } from '../types';
9
+ import getScopeAttributes from '../utils/scopeAttributes';
7
10
 
8
11
  type SupportedHookTypes = 'afterFind' | 'afterCreate' | 'afterUpdate';
9
12
 
@@ -29,11 +32,14 @@ const serializeCustomFields = (
29
32
  const enrichResults = (
30
33
  modelType: string,
31
34
  scopeAttributes: string[],
35
+ getScope,
32
36
  hookType?: SupportedHookTypes,
37
+ modelOptions: ModelOptions = {},
33
38
  ) => async (
34
39
  instancesOrInstance: any | any[],
35
40
  options,
36
41
  ): Promise<void> => {
42
+ const { scopeAttributeReplacer } = modelOptions;
37
43
  if (
38
44
  options.originalAttributes?.length > 0
39
45
  && !options.originalAttributes?.includes?.('customFields')
@@ -48,19 +54,21 @@ const enrichResults = (
48
54
 
49
55
  instances = instances.filter(Boolean);
50
56
 
51
- const identifiers = instances.map((instance) =>
52
- scopeAttributes
53
- .map((attr) => instance[attr])).flat();
57
+ const identifiers = await getScopeAttributes(instances, scopeAttributes, scopeAttributeReplacer);
58
+ logger.info('enrichResults - sadot - indentifiers: ', identifiers);
54
59
 
55
60
  const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
61
+
56
62
  const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
57
63
  ...map,
58
64
  [identifier]: [],
65
+
59
66
  }), {});
67
+
60
68
  const customFieldDefinitions = await DefinitionRepo.findByEntityIds(
61
69
  modelType,
62
70
  uniqueIdentifiers,
63
- { transaction: options.transaction },
71
+ { transaction: options.transaction, getScope },
64
72
  );
65
73
 
66
74
  const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
@@ -69,7 +77,7 @@ const enrichResults = (
69
77
  }), {});
70
78
 
71
79
  customFieldDefinitions.forEach((cfd) => {
72
- identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
80
+ identifierCustomFieldDefinitionsMapping[cfd.entityId]?.push(cfd);
73
81
  });
74
82
 
75
83
  // Get the values per instates ids:
@@ -104,6 +112,7 @@ const enrichResults = (
104
112
 
105
113
  scopeAttributes.forEach((attribute) => {
106
114
  const identifier = instance[attribute];
115
+
107
116
  const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];
108
117
  if (entityCustomFieldDefinitions?.length > 0) {
109
118
  entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
package/src/hooks/find.ts CHANGED
@@ -16,6 +16,7 @@ const doScopeAttributesMissing = (
16
16
  // eslint-disable-next-line import/prefer-default-export
17
17
  export const beforeFind = (scopeAttributes: string[]) => (options): void => {
18
18
  const { attributes: queryAttributes } = options;
19
+
19
20
  if (queryAttributes?.includes?.('customFields')) {
20
21
  const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes);
21
22
  logger.debug('sadot - before find hook');
@@ -1,5 +1,7 @@
1
1
  import logger from '../utils/logger';
2
2
  import * as ValueRepo from '../repository/value';
3
+ import { ModelOptions } from '../types';
4
+ import getScopeAttributes from '../utils/scopeAttributes';
3
5
 
4
6
  /**
5
7
  * A hook to update the custom fields when updating a model (more then one instance).
@@ -14,14 +16,15 @@ export const beforeBulkUpdate = (options): void => {
14
16
  * A hook to update the custom fields when updating a model instance.
15
17
  * TODO - cleanup if update fail
16
18
  */
17
- export const beforeUpdate = (scopeAttributes: string[]) => async (
19
+ export const beforeUpdate = (scopeAttributes: string[], modelOptions: ModelOptions = {}) => async (
18
20
  instance,
19
21
  options,
20
22
  ): Promise<void> => {
21
23
  logger.debug('sadot - before update hook');
22
24
  const { fields } = options;
25
+ const { scopeAttributeReplacer } = modelOptions;
23
26
  const modelType = instance.constructor.name;
24
- const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
27
+ const identifiers = await getScopeAttributes(instance, scopeAttributes, scopeAttributeReplacer);
25
28
 
26
29
  const customFieldsIdx = fields.indexOf('customFields');
27
30
  if (customFieldsIdx > -1) {
@@ -32,6 +35,7 @@ export const beforeUpdate = (scopeAttributes: string[]) => async (
32
35
  identifiers,
33
36
  customFields,
34
37
  { transaction: options.transaction },
38
+
35
39
  );
36
40
  // eslint-disable-next-line no-param-reassign
37
41
  fields.splice(customFieldsIdx, 1);
@@ -5,10 +5,12 @@ import logger from '../utils/logger';
5
5
  import CustomFieldDefinition from './CustomFieldDefinition';
6
6
  import CustomFieldValue from './CustomFieldValue';
7
7
  import TestModel from './tests/TestModel';
8
+ import ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';
9
+ import ContextModel from './tests/contextAwareModels/ContextModel';
8
10
  import AssociatedTestModel from './tests/AssociatedTestModel';
9
11
 
10
12
  const productionModels = [CustomFieldDefinition, CustomFieldValue];
11
- const testModels = [TestModel, AssociatedTestModel];
13
+ const testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextModel];
12
14
 
13
15
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
14
16
  const SCHEMA_VERSION = 1;
@@ -88,6 +90,8 @@ const initTestModels = async (sequelize: Sequelize): Promise<void> => {
88
90
  logger.info('custom-fields: test models added');
89
91
  await TestModel.sync({ alter: true });
90
92
  await AssociatedTestModel.sync({ alter: true });
93
+ await ContextModel.sync({ alter: true });
94
+ await ContextAwareTestModel.sync({ alter: true });
91
95
  logger.info('custom-fields: test models synced');
92
96
  };
93
97
 
@@ -96,6 +100,8 @@ export {
96
100
  CustomFieldDefinition,
97
101
  TestModel,
98
102
  AssociatedTestModel,
103
+ ContextAwareTestModel,
104
+ ContextModel,
99
105
  initTables,
100
106
  initTestModels,
101
107
  };
@@ -0,0 +1,45 @@
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+ import {
3
+ Table,
4
+ Column,
5
+ Model,
6
+ PrimaryKey,
7
+ DataType,
8
+ HasMany,
9
+ BelongsTo,
10
+ ForeignKey,
11
+ } from 'sequelize-typescript';
12
+ import AssociatedTestModel from '../AssociatedTestModel';
13
+ import ContextModel from './ContextModel';
14
+
15
+ @Table({ createdAt: false, updatedAt: false })
16
+ class ContextAwareTestModel extends Model {
17
+ @PrimaryKey
18
+ @Column({
19
+ type: DataType.UUID,
20
+ defaultValue: DataType.UUIDV4,
21
+ allowNull: false,
22
+ })
23
+ id!: string;
24
+
25
+ @ForeignKey(() => ContextModel)
26
+ @Column({
27
+ type: DataType.UUID,
28
+ })
29
+ contextId: string;
30
+
31
+ @Column({
32
+ type: DataType.BOOLEAN,
33
+ })
34
+ coolAttribute?: boolean;
35
+
36
+ @Column({
37
+ type: DataType.VIRTUAL,
38
+ })
39
+ customFields?: any;
40
+
41
+ @BelongsTo(() => ContextModel)
42
+ context: ContextModel;
43
+ }
44
+
45
+ export default ContextAwareTestModel;
@@ -0,0 +1,38 @@
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+ import {
3
+ Table,
4
+ Column,
5
+ Model,
6
+ PrimaryKey,
7
+ DataType,
8
+ } from 'sequelize-typescript';
9
+
10
+ // eslint-disable-next-line no-shadow
11
+ enum EEntityTypes {
12
+ BUSINESS_MODEL = 'businessModel',
13
+ CONTEXT = 'context',
14
+ DEMAND_SOURCE = 'demandSource',
15
+ FLEET = 'fleet',
16
+ }
17
+
18
+ @Table({ createdAt: false, updatedAt: false })
19
+ class ContextModel extends Model {
20
+ @PrimaryKey
21
+ @Column({
22
+ defaultValue: DataType.UUIDV4,
23
+ type: DataType.UUID,
24
+ })
25
+ id: string;
26
+
27
+ @Column({
28
+ type: DataType.UUID,
29
+ })
30
+ entityId: string;
31
+
32
+ @Column({
33
+ type: DataType.ENUM(...Object.values(EEntityTypes)),
34
+ })
35
+ entityType: EEntityTypes;
36
+ }
37
+
38
+ export default ContextModel;
@@ -1,21 +1,26 @@
1
- import { Op, WhereOptions } from 'sequelize';
1
+ import {
2
+ Op, WhereOptions,
3
+ } from 'sequelize';
2
4
  import { CustomFieldDefinition } from '../models';
3
5
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
6
+ import logger from '../utils/logger';
4
7
 
5
8
  export const create = (data: CreateCustomFieldDefinition): Promise<CustomFieldDefinition> =>
6
9
  CustomFieldDefinition.create(data);
7
10
 
8
11
  export const findAll = (
9
- where: any,
12
+ where: WhereOptions,
10
13
  options: any = { withDisabled: false },
11
14
  ): Promise<CustomFieldDefinition[]> => {
12
15
  const queryModel = options.withDisabled
13
16
  ? CustomFieldDefinition.unscoped()
14
17
  : CustomFieldDefinition;
18
+
19
+ logger.info('sadot - whereQuery', { options });
15
20
  return queryModel.scope('userScope').findAll({
16
21
  where,
17
- transaction: options.transaction,
18
22
  raw: true,
23
+ logging: true,
19
24
  });
20
25
  };
21
26
 
@@ -35,14 +40,6 @@ export const findById = (
35
40
  return CustomFieldDefinition.scope('userScope').findByPk(id);
36
41
  };
37
42
 
38
- export const findByEntityId = async (
39
- entityId: string,
40
- options: any = {},
41
- ): Promise<CustomFieldDefinition[]> => CustomFieldDefinition.findAll({
42
- where: { entityId },
43
- transaction: options.transaction,
44
- });
45
-
46
43
  export const findByEntityIds = async (
47
44
  modelType: string,
48
45
  entityIds: string[],
@@ -53,6 +50,7 @@ export const findByEntityIds = async (
53
50
  entityId: entityIds,
54
51
  },
55
52
  transaction: options.transaction,
53
+ include: options.include,
56
54
  raw: true,
57
55
  });
58
56
 
@@ -103,9 +101,13 @@ export const getRequiredFields = async (
103
101
  ): Promise<string[]> => {
104
102
  const entityIds = Array.isArray(entityId) ? entityId : [entityId];
105
103
  const requiredFields = await CustomFieldDefinition.findAll({
106
- where: { required: true, modelType, entityId: { [Op.in]: entityIds } },
104
+ where: {
105
+ required: true,
106
+ modelType,
107
+ entityId: { [Op.in]: entityIds },
108
+ },
107
109
  logging: true,
108
110
  });
109
- const requiredFieldsNames = requiredFields.map((definition) => definition.name);
111
+ const requiredFieldsNames = requiredFields.map((definition:any) => definition.name);
110
112
  return [...new Set(requiredFieldsNames)];
111
113
  };
@@ -52,13 +52,19 @@ export const updateValues = async (
52
52
  valuesToUpdate: ValuesToUpdate,
53
53
  options: any = {},
54
54
  ): Promise<CustomFieldValue[]> => {
55
- logger.info(`custom-fields: updating values for ${modelType} ${modelId}`, { valuesToUpdate });
56
-
57
55
  const names = Object.keys(valuesToUpdate);
58
- const fieldDefinitions = await DefinitionRepo.findAll(
59
- { modelType, name: names, entityId: identifiers },
56
+ logger.info(`custom-fields: updating values for ${modelType} ${modelId}`, {
57
+ names, options, valuesToUpdate, entityId: identifiers,
58
+ });
59
+
60
+ const fieldDefinitions = (await DefinitionRepo.findAll(
61
+ {
62
+ modelType,
63
+ name: names,
64
+ entityId: identifiers,
65
+ },
60
66
  { withDisabled: true, transaction: options.transaction },
61
- ) || [];
67
+ )) || [];
62
68
 
63
69
  const disabledDefinitions = fieldDefinitions.filter((def) => def.disabled);
64
70
  if (fieldDefinitions.length !== names.length) {
@@ -4,6 +4,7 @@ export default {
4
4
  password: process.env.DB_PASSWORD || null,
5
5
  database: process.env.DB_NAME || 'sadot_package_test',
6
6
  host: process.env.DB_HOST || '127.0.0.1',
7
+ port: process.env.DB_PORT || 5432,
7
8
  dialect: process.env.DB_TYPE || 'postgres',
8
9
  define: {
9
10
  underscored: true,
@@ -1,10 +1,14 @@
1
- import { CustomFieldDefinition, TestModel } from '../../models';
1
+ import {
2
+ ContextAwareTestModel, ContextModel, CustomFieldDefinition, TestModel,
3
+ } from '../../models';
2
4
 
3
5
  // eslint-disable-next-line import/prefer-default-export
4
6
  export const cleanup = async (): Promise<void> => {
5
7
  if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
6
8
  await CustomFieldDefinition.unscoped().destroy({ where: {} });
7
9
  await TestModel.destroy({ where: {} });
10
+ await ContextAwareTestModel.destroy({ where: {} });
11
+ await ContextModel.destroy({ where: {} });
8
12
  }
9
13
  };
10
14
 
@@ -1,6 +1,13 @@
1
1
  import { v4 as uuidv4 } from 'uuid';
2
2
  import { CreateCustomFieldDefinition, CustomFieldDefinitionDTO } from '../../types/definition';
3
3
 
4
+ export const contextAwareFieldDefinition = {
5
+ name: 'cool field',
6
+ modelType: 'ContextAwareTestModel',
7
+ fieldType: 'number',
8
+ entityType: 'fleetId',
9
+ };
10
+
4
11
  export const coolFieldDefinition: CreateCustomFieldDefinition = {
5
12
  name: 'cool field',
6
13
  modelType: 'TestModel',
@@ -1,6 +1,6 @@
1
1
  import { TestModel, AssociatedTestModel } from '../../models';
2
2
 
3
- export const createTestModel = (payload = {}) => TestModel.create(payload);
3
+ export const createTestModel = (payload = {}, model:any = TestModel) => model.create(payload);
4
4
 
5
5
  export const createTestModels = (fleetId, total: number) => {
6
6
  const models: Promise<TestModel>[] = [];
@@ -1,15 +1,19 @@
1
1
  export type ModelFetcher = (name: string) => any;
2
2
 
3
3
  export type ModelOptions = {
4
+ scopeAttributeReplacer?: (attributes?: string[]) => Promise<any>;
5
+ }
6
+ export type Models = {
4
7
  name: string;
5
8
  scopeAttributes: string[];
9
+ modelOptions?: ModelOptions;
6
10
  creationWebhookHandler?: (instance: any) => any;
7
11
  updateWebhookHandler?: (instance: any) => any;
8
12
  deletionWebhookHandler?: (instance: any) => any;
9
13
  }
10
14
 
11
- export type CustomFieldOptions= {
12
- models: ModelOptions[];
15
+ export type CustomFieldOptions = {
16
+ models: Models[];
13
17
  databaseConfig: any;
14
18
  getUser: () => any;
15
19
  };
package/src/utils/init.ts CHANGED
@@ -14,12 +14,14 @@ import {
14
14
  } from '../hooks';
15
15
  import { customFieldsFilterScope } from '../scopes';
16
16
  import logger from './logger';
17
- import type { ModelFetcher, ModelOptions } from '../types';
17
+ import type { ModelFetcher, Models } from '../types';
18
18
 
19
19
  const { CUSTOM_FIELDS_FILTER_SCOPE } = customFields;
20
20
 
21
- export const addHooks = (models: ModelOptions[], getModel: ModelFetcher): void => {
22
- models.forEach(async ({ name, scopeAttributes }) => {
21
+ export const addHooks = (models: Models[], getModel: ModelFetcher): void => {
22
+ models.forEach(async ({
23
+ name, scopeAttributes, modelOptions,
24
+ }) => {
23
25
  try {
24
26
  const model = getModel(name);
25
27
  if (!model) {
@@ -38,18 +40,18 @@ export const addHooks = (models: ModelOptions[], getModel: ModelFetcher): void =
38
40
  model.addHook('beforeFind', 'sadot-beforeFind', beforeFind(scopeAttributes));
39
41
  model.addHook('beforeBulkCreate', 'sadot-beforeBulkCreate', beforeBulkCreate);
40
42
  model.addHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate', beforeBulkUpdate);
41
- model.addHook('beforeCreate', 'sadot-beforeCreate', beforeCreate(scopeAttributes));
42
- model.addHook('beforeUpdate', 'sadot-beforeUpdate', beforeUpdate(scopeAttributes));
43
- model.addHook('afterFind', 'sadot-afterFind', enrichResults(name, scopeAttributes, 'afterFind'));
44
- model.addHook('afterUpdate', 'sadot-afterUpdate', enrichResults(name, scopeAttributes));
45
- model.addHook('afterCreate', 'sadot-afterCreate', enrichResults(name, scopeAttributes));
43
+ model.addHook('beforeCreate', 'sadot-beforeCreate', beforeCreate(scopeAttributes, modelOptions));
44
+ model.addHook('beforeUpdate', 'sadot-beforeUpdate', beforeUpdate(scopeAttributes, modelOptions));
45
+ model.addHook('afterFind', 'sadot-afterFind', enrichResults(name, scopeAttributes, 'afterFind', null, modelOptions));
46
+ model.addHook('afterUpdate', 'sadot-afterUpdate', enrichResults(name, scopeAttributes, null, null, modelOptions));
47
+ model.addHook('afterCreate', 'sadot-afterCreate', enrichResults(name, scopeAttributes, null, null, modelOptions));
46
48
  } catch (e) {
47
49
  logger.error(`Could not add custom fields hook to model ${name}. `, e);
48
50
  }
49
51
  });
50
52
  };
51
53
 
52
- export const removeHooks = (models: ModelOptions[], getModel: ModelFetcher): void => {
54
+ export const removeHooks = (models: Models[], getModel: ModelFetcher): void => {
53
55
  models.forEach(async ({ name }) => {
54
56
  try {
55
57
  const model = getModel(name);
@@ -81,7 +83,7 @@ const addAssociations = (model: ModelCtor, modelName: string): void => {
81
83
  CustomFieldValue.belongsTo(model, { foreignKey: 'modelId', as: modelName });
82
84
  };
83
85
 
84
- export const addScopes = (models: ModelOptions[], getModel: ModelFetcher): void => {
86
+ export const addScopes = (models: Models[], getModel: ModelFetcher): void => {
85
87
  models.forEach(async ({ name, scopeAttributes }) => {
86
88
  try {
87
89
  const model = getModel(name);
@@ -0,0 +1,18 @@
1
+ import { ModelOptions } from '../types';
2
+
3
+ const getIdentifiers = (instance: any, scopeAttributes: string[]) => {
4
+ if (Array.isArray(instance)) {
5
+ return instance.map((ins) =>
6
+ scopeAttributes.map((attr) => ins[attr])).flat();
7
+ }
8
+ return scopeAttributes.map((attribute) => instance[attribute]);
9
+ };
10
+ const getScopeAttributes = async (instance: any, scopeAttributes: string[], scopeAttributeReplacer?: ModelOptions['scopeAttributeReplacer']) => {
11
+ let identifiers = getIdentifiers(instance, scopeAttributes);
12
+ if (scopeAttributeReplacer) {
13
+ identifiers = await scopeAttributeReplacer(identifiers);
14
+ }
15
+ return identifiers;
16
+ };
17
+
18
+ export default getScopeAttributes;