@autofleet/sadot 0.3.1 → 0.3.3

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 (117) hide show
  1. package/dist/api/index.d.ts +2 -0
  2. package/dist/api/index.js +0 -1
  3. package/dist/api/v1/definition/index.d.ts +2 -0
  4. package/dist/api/v1/definition/index.js +19 -26
  5. package/dist/api/v1/definition/validations.d.ts +2 -0
  6. package/dist/api/v1/definition/validations.js +0 -1
  7. package/dist/api/v1/errors.d.ts +2 -0
  8. package/dist/api/v1/errors.js +0 -1
  9. package/dist/api/v1/index.d.ts +2 -0
  10. package/dist/api/v1/index.js +0 -1
  11. package/dist/errors/index.d.ts +16 -0
  12. package/dist/errors/index.js +0 -1
  13. package/dist/events/index.d.ts +4 -0
  14. package/dist/events/index.js +1 -2
  15. package/dist/hooks/create.d.ts +9 -0
  16. package/dist/hooks/create.js +6 -16
  17. package/dist/hooks/enrich.d.ts +5 -0
  18. package/dist/hooks/enrich.js +23 -27
  19. package/dist/hooks/find.d.ts +1 -0
  20. package/dist/hooks/find.js +3 -5
  21. package/dist/hooks/index.d.ts +6 -0
  22. package/dist/hooks/index.js +0 -1
  23. package/dist/hooks/update.d.ts +9 -0
  24. package/dist/hooks/update.js +3 -13
  25. package/dist/hooks/workaround.d.ts +10 -0
  26. package/dist/hooks/workaround.js +3 -13
  27. package/dist/index.d.ts +11 -0
  28. package/dist/index.js +8 -18
  29. package/dist/models/CustomFieldDefinition.d.ts +23 -0
  30. package/dist/models/CustomFieldDefinition.js +1 -2
  31. package/dist/models/CustomFieldValue.d.ts +15 -0
  32. package/dist/models/CustomFieldValue.js +20 -34
  33. package/dist/models/index.d.ts +8 -0
  34. package/dist/models/index.js +13 -23
  35. package/dist/models/tests/AssociatedTestModel.d.ts +12 -0
  36. package/dist/models/tests/AssociatedTestModel.js +0 -1
  37. package/dist/models/tests/TestModel.d.ts +11 -0
  38. package/dist/models/tests/TestModel.js +0 -1
  39. package/dist/repository/definition.d.ts +17 -0
  40. package/dist/repository/definition.js +19 -33
  41. package/dist/repository/value.d.ts +24 -0
  42. package/dist/repository/value.js +18 -28
  43. package/dist/tests/api/test-api.d.ts +2 -0
  44. package/dist/tests/api/test-api.js +12 -22
  45. package/dist/tests/helpers/database-config.d.ts +15 -0
  46. package/dist/tests/helpers/database-config.js +0 -1
  47. package/dist/tests/helpers/index.d.ts +2 -0
  48. package/dist/tests/helpers/index.js +4 -14
  49. package/dist/tests/mocks/definition.mock.d.ts +37 -0
  50. package/dist/tests/mocks/definition.mock.js +18 -13
  51. package/dist/tests/mocks/events.mock.d.ts +3 -0
  52. package/dist/tests/mocks/events.mock.js +0 -1
  53. package/dist/tests/mocks/testModel.d.ts +12 -0
  54. package/dist/tests/mocks/testModel.js +4 -14
  55. package/dist/types/definition/index.d.ts +23 -0
  56. package/dist/types/definition/index.js +0 -1
  57. package/dist/types/index.d.ts +13 -0
  58. package/dist/types/index.js +0 -1
  59. package/dist/types/value/index.d.ts +15 -0
  60. package/dist/types/value/index.js +0 -1
  61. package/dist/utils/constants/index.d.ts +1 -0
  62. package/dist/utils/constants/index.js +0 -1
  63. package/dist/utils/db/index.d.ts +4 -0
  64. package/dist/utils/db/index.js +0 -1
  65. package/dist/utils/logger/index.d.ts +2 -0
  66. package/dist/utils/logger/index.js +0 -1
  67. package/dist/utils/validations/custom-fields.d.ts +2 -0
  68. package/dist/utils/validations/custom-fields.js +0 -1
  69. package/dist/utils/validations/custom.d.ts +15 -0
  70. package/dist/utils/validations/custom.js +1 -2
  71. package/dist/utils/validations/index.d.ts +2 -0
  72. package/dist/utils/validations/index.js +0 -1
  73. package/dist/utils/validations/type.d.ts +18 -0
  74. package/dist/utils/validations/type.js +0 -1
  75. package/dist/utils/validations/validators.d.ts +12 -0
  76. package/dist/utils/validations/validators.js +0 -1
  77. package/package.json +1 -1
  78. package/tsconfig.json +9 -25
  79. package/dist/api/index.js.map +0 -1
  80. package/dist/api/v1/definition/index.js.map +0 -1
  81. package/dist/api/v1/definition/validations.js.map +0 -1
  82. package/dist/api/v1/errors.js.map +0 -1
  83. package/dist/api/v1/index.js.map +0 -1
  84. package/dist/errors/index.js.map +0 -1
  85. package/dist/events/index.js.map +0 -1
  86. package/dist/hooks/create.js.map +0 -1
  87. package/dist/hooks/enrich.js.map +0 -1
  88. package/dist/hooks/find.js.map +0 -1
  89. package/dist/hooks/index.js.map +0 -1
  90. package/dist/hooks/update.js.map +0 -1
  91. package/dist/hooks/workaround.js.map +0 -1
  92. package/dist/index.js.map +0 -1
  93. package/dist/models/CustomFieldDefinition.js.map +0 -1
  94. package/dist/models/CustomFieldValue.js.map +0 -1
  95. package/dist/models/index.js.map +0 -1
  96. package/dist/models/tests/AssociatedTestModel.js.map +0 -1
  97. package/dist/models/tests/TestModel.js.map +0 -1
  98. package/dist/repository/definition.js.map +0 -1
  99. package/dist/repository/value.js.map +0 -1
  100. package/dist/tests/api/test-api.js.map +0 -1
  101. package/dist/tests/helpers/database-config.js.map +0 -1
  102. package/dist/tests/helpers/index.js.map +0 -1
  103. package/dist/tests/mocks/definition.mock.js.map +0 -1
  104. package/dist/tests/mocks/events.mock.js.map +0 -1
  105. package/dist/tests/mocks/testModel.js.map +0 -1
  106. package/dist/tsconfig.tsbuildinfo +0 -1
  107. package/dist/types/definition/index.js.map +0 -1
  108. package/dist/types/index.js.map +0 -1
  109. package/dist/types/value/index.js.map +0 -1
  110. package/dist/utils/constants/index.js.map +0 -1
  111. package/dist/utils/db/index.js.map +0 -1
  112. package/dist/utils/logger/index.js.map +0 -1
  113. package/dist/utils/validations/custom-fields.js.map +0 -1
  114. package/dist/utils/validations/custom.js.map +0 -1
  115. package/dist/utils/validations/index.js.map +0 -1
  116. package/dist/utils/validations/type.js.map +0 -1
  117. package/dist/utils/validations/validators.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ declare const router: import("express-serve-static-core").Router;
2
+ export default router;
package/dist/api/index.js CHANGED
@@ -9,4 +9,3 @@ const v1_1 = __importDefault(require("./v1"));
9
9
  const router = (0, express_1.Router)({ mergeParams: true });
10
10
  router.use('/v1', v1_1.default);
11
11
  exports.default = router;
12
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ declare const router: import("express-serve-static-core").Router;
2
+ export default router;
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
27
  };
@@ -47,26 +38,29 @@ const toPascalCase = (str) => str.replace(/(^\w|-\w)/g, (subStr) => subStr.repla
47
38
  /**
48
39
  * Create
49
40
  */
50
- router.post('/', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
41
+ router.post('/', async (req, res) => {
51
42
  const { modelName } = req.params;
52
43
  const modelType = toPascalCase(modelName);
53
44
  try {
54
- const validatedPayload = yield (0, validations_1.validateCustomFieldDefinitionCreation)(req.body);
55
- const customFieldDefinition = yield DefinitionRepo.create(Object.assign(Object.assign({}, validatedPayload), { modelType }));
45
+ const validatedPayload = await (0, validations_1.validateCustomFieldDefinitionCreation)(req.body);
46
+ const customFieldDefinition = await DefinitionRepo.create({
47
+ ...validatedPayload,
48
+ modelType,
49
+ });
56
50
  return res.status(201).json(customFieldDefinition);
57
51
  }
58
52
  catch (err) {
59
53
  logger_1.default.error('Failed to create custom field definition', err);
60
54
  return (0, errors_2.default)(err, res, { message: `Error in create ${ENTITY} request` });
61
55
  }
62
- }));
56
+ });
63
57
  /**
64
58
  * Get by id
65
59
  */
66
- router.get('/:customFieldDefinitionId', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
60
+ router.get('/:customFieldDefinitionId', async (req, res) => {
67
61
  const { customFieldDefinitionId } = req.params;
68
62
  try {
69
- const customFieldDefinition = yield DefinitionRepo.findById(customFieldDefinitionId);
63
+ const customFieldDefinition = await DefinitionRepo.findById(customFieldDefinitionId);
70
64
  if (!customFieldDefinition) {
71
65
  throw new errors_1.ResourceNotFoundError();
72
66
  }
@@ -76,50 +70,49 @@ router.get('/:customFieldDefinitionId', (req, res) => __awaiter(void 0, void 0,
76
70
  logger_1.default.error('Failed to fetch custom field definition', err);
77
71
  return (0, errors_2.default)(err, res, { message: `Error in get ${ENTITY} request` });
78
72
  }
79
- }));
73
+ });
80
74
  /**
81
75
  * Get all
82
76
  */
83
- router.get('/', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
77
+ router.get('/', async (req, res) => {
84
78
  const { modelName } = req.params;
85
79
  const { entityIds } = req.query;
86
80
  const modelType = toPascalCase(modelName);
87
81
  try {
88
82
  const where = { modelType };
89
- if ((entityIds === null || entityIds === void 0 ? void 0 : entityIds.length) > 0) {
83
+ if (entityIds?.length > 0) {
90
84
  where.entityId = entityIds;
91
85
  }
92
- const customFieldDefinitions = yield DefinitionRepo.findAll(Object.assign({}, where), { withDisabled: true });
86
+ const customFieldDefinitions = await DefinitionRepo.findAll({ ...where }, { withDisabled: true });
93
87
  return res.json(customFieldDefinitions);
94
88
  }
95
89
  catch (err) {
96
90
  logger_1.default.error('Failed to fetch custom field definitions', err);
97
91
  return (0, errors_2.default)(err, res, { message: `Error in get all ${ENTITY} request` });
98
92
  }
99
- }));
93
+ });
100
94
  /**
101
95
  * Update
102
96
  */
103
- router.patch('/:customFieldDefinitionId', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
97
+ router.patch('/:customFieldDefinitionId', async (req, res) => {
104
98
  const { customFieldDefinitionId, modelName } = req.params;
105
99
  const modelType = toPascalCase(modelName);
106
100
  try {
107
101
  // eslint-disable-next-line max-len
108
- const validatedPayload = yield (0, validations_1.validateCustomFieldDefinitionUpdate)(req.body);
109
- const customFieldDefinition = yield DefinitionRepo.findByWhere({
102
+ const validatedPayload = await (0, validations_1.validateCustomFieldDefinitionUpdate)(req.body);
103
+ const customFieldDefinition = await DefinitionRepo.findByWhere({
110
104
  id: customFieldDefinitionId,
111
105
  modelType,
112
106
  });
113
107
  if (!customFieldDefinition) {
114
108
  throw new errors_1.ResourceNotFoundError();
115
109
  }
116
- const updatedCustomFieldDefinition = yield DefinitionRepo.update(customFieldDefinitionId, Object.assign(Object.assign({}, validatedPayload), { modelType }));
110
+ const updatedCustomFieldDefinition = await DefinitionRepo.update(customFieldDefinitionId, { ...validatedPayload, modelType });
117
111
  return res.status(200).json(updatedCustomFieldDefinition);
118
112
  }
119
113
  catch (err) {
120
114
  logger_1.default.error('Failed to patch custom field definition', err);
121
115
  return (0, errors_2.default)(err, res, { message: `Error in update ${ENTITY} request` });
122
116
  }
123
- }));
117
+ });
124
118
  exports.default = router;
125
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,2 @@
1
+ export declare const validateCustomFieldDefinitionCreation: (payload: any) => any;
2
+ export declare const validateCustomFieldDefinitionUpdate: (payload: any) => any;
@@ -34,4 +34,3 @@ const validateCustomFieldDefinitionCreation = (payload) => CustomFieldDefinition
34
34
  exports.validateCustomFieldDefinitionCreation = validateCustomFieldDefinitionCreation;
35
35
  const validateCustomFieldDefinitionUpdate = (payload) => CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });
36
36
  exports.validateCustomFieldDefinitionUpdate = validateCustomFieldDefinitionUpdate;
37
- //# sourceMappingURL=validations.js.map
@@ -0,0 +1,2 @@
1
+ declare const _default: (err: any, res: any, additionalData?: {}) => any;
2
+ export default _default;
@@ -13,4 +13,3 @@ exports.default = (err, res, additionalData = {}) => {
13
13
  }
14
14
  return (0, errors_1.handleError)(error, res, additionalData);
15
15
  };
16
- //# sourceMappingURL=errors.js.map
@@ -0,0 +1,2 @@
1
+ declare const router: import("express-serve-static-core").Router;
2
+ export default router;
@@ -8,4 +8,3 @@ const definition_1 = __importDefault(require("./definition"));
8
8
  const router = (0, express_1.Router)({ mergeParams: true });
9
9
  router.use('/custom-field-definitions/:modelName', definition_1.default);
10
10
  exports.default = router;
11
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,16 @@
1
+ import { BadRequest } from '@autofleet/errors';
2
+ export declare class MissingRequiredCustomFieldError extends BadRequest {
3
+ constructor(missingFields: string[]);
4
+ }
5
+ export declare class UnsupportedCustomFieldTypeError extends BadRequest {
6
+ constructor(fieldType: string);
7
+ }
8
+ export declare class UnsupportedCustomValidationError extends BadRequest {
9
+ constructor(fieldType: string);
10
+ }
11
+ export declare class InvalidValueError extends BadRequest {
12
+ constructor(value: any, fieldType: string);
13
+ }
14
+ export declare class MissingDefinitionError extends BadRequest {
15
+ constructor(fieldNames: string[]);
16
+ }
@@ -43,4 +43,3 @@ class MissingDefinitionError extends errors_1.BadRequest {
43
43
  }
44
44
  }
45
45
  exports.MissingDefinitionError = MissingDefinitionError;
46
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,4 @@
1
+ import Events from '@autofleet/events';
2
+ declare const events: Events;
3
+ export declare const sendDimEvent: (instance: any) => void;
4
+ export default events;
@@ -10,7 +10,7 @@ const events = new events_1.default({ logger: logger_1.default });
10
10
  const KEYS_TO_CONVERT = ['value'];
11
11
  const stringifyBools = (savedObject, keysToConvert) => {
12
12
  if (Object.keys(savedObject).some((key) => keysToConvert.includes(key))) {
13
- const objectToReturn = Object.assign({}, savedObject);
13
+ const objectToReturn = { ...savedObject };
14
14
  keysToConvert.forEach((key) => {
15
15
  if (typeof savedObject[key] === 'boolean') {
16
16
  objectToReturn[key] = savedObject[key].toString();
@@ -45,4 +45,3 @@ const sendDimEvent = (instance) => {
45
45
  };
46
46
  exports.sendDimEvent = sendDimEvent;
47
47
  exports.default = events;
48
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * A hook to create the custom fields when updating a model (more then one instance).
3
+ */
4
+ export declare const beforeBulkCreate: (options: any) => void;
5
+ /**
6
+ * A hook to create the custom fields when updating a model instance.
7
+ * TODO - cleanup if update fail
8
+ */
9
+ export declare const beforeCreate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
27
  };
@@ -53,28 +44,27 @@ exports.beforeBulkCreate = beforeBulkCreate;
53
44
  * A hook to create the custom fields when updating a model instance.
54
45
  * TODO - cleanup if update fail
55
46
  */
56
- const beforeCreate = (scopeAttributes) => (instance, options) => __awaiter(void 0, void 0, void 0, function* () {
47
+ const beforeCreate = (scopeAttributes) => async (instance, options) => {
57
48
  logger_1.default.debug('sadot - before create hook');
58
49
  const { fields } = options;
59
50
  const modelType = instance.constructor.name;
60
51
  const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
61
52
  // get all model's required definitions
62
- const requiredFieldsNames = yield DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers);
53
+ const requiredFieldsNames = await DefinitionRepo.getRequiredFields(modelType, instance.id, identifiers);
63
54
  const customFieldsIdx = fields.indexOf('customFields');
64
55
  const { customFields } = instance;
65
56
  if (customFieldsIdx > -1 && customFields) {
66
57
  const fieldsNames = Object.keys(customFields);
67
58
  const missingFields = requiredFieldsNames.filter((name) => !fieldsNames.includes(name));
68
- if ((missingFields === null || missingFields === void 0 ? void 0 : missingFields.length) > 0) {
59
+ if (missingFields?.length > 0) {
69
60
  throw new errors_1.MissingRequiredCustomFieldError(missingFields);
70
61
  }
71
- yield ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
62
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
72
63
  // eslint-disable-next-line no-param-reassign
73
64
  fields.splice(customFieldsIdx, 1);
74
65
  }
75
- else if ((requiredFieldsNames === null || requiredFieldsNames === void 0 ? void 0 : requiredFieldsNames.length) > 0) {
66
+ else if (requiredFieldsNames?.length > 0) {
76
67
  throw new errors_1.MissingRequiredCustomFieldError(requiredFieldsNames);
77
68
  }
78
- });
69
+ };
79
70
  exports.beforeCreate = beforeCreate;
80
- //# sourceMappingURL=create.js.map
@@ -0,0 +1,5 @@
1
+ /**
2
+ * A hook to attach the custom fields when fetching a model instances.
3
+ */
4
+ declare const enrichResults: (modelType: string, scopeAttributes: string[]) => (instancesOrInstance: any | any[], options: any) => Promise<void>;
5
+ export default enrichResults;
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  Object.defineProperty(exports, "__esModule", { value: true });
35
26
  /* eslint-disable no-param-reassign */
36
27
  const ValueRepo = __importStar(require("../repository/value"));
@@ -39,17 +30,19 @@ const DefinitionRepo = __importStar(require("../repository/definition"));
39
30
  * Serialize custom fields value into the format of {[name] -> [fieldData]}
40
31
  */
41
32
  const serializeCustomFields = (customFieldValues, customFieldDefinitionsHash) => {
42
- const customFields = customFieldValues.reduce((acc, cfv) => (Object.assign(Object.assign({}, acc), (customFieldDefinitionsHash[cfv.customFieldDefinitionId]
43
- && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }))), {});
33
+ const customFields = customFieldValues.reduce((acc, cfv) => ({
34
+ ...acc,
35
+ ...(customFieldDefinitionsHash[cfv.customFieldDefinitionId]
36
+ && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }),
37
+ }), {});
44
38
  return customFields;
45
39
  };
46
40
  /**
47
41
  * A hook to attach the custom fields when fetching a model instances.
48
42
  */
49
- const enrichResults = (modelType, scopeAttributes) => (instancesOrInstance, options) => __awaiter(void 0, void 0, void 0, function* () {
50
- var _a, _b, _c;
51
- if (((_a = options.originalAttributes) === null || _a === void 0 ? void 0 : _a.length) > 0
52
- && !((_c = (_b = options.originalAttributes) === null || _b === void 0 ? void 0 : _b.includes) === null || _c === void 0 ? void 0 : _c.call(_b, 'customFields'))) {
43
+ const enrichResults = (modelType, scopeAttributes) => async (instancesOrInstance, options) => {
44
+ if (options.originalAttributes?.length > 0
45
+ && !options.originalAttributes?.includes?.('customFields')) {
53
46
  return;
54
47
  }
55
48
  const primaryKey = 'id';
@@ -60,15 +53,21 @@ const enrichResults = (modelType, scopeAttributes) => (instancesOrInstance, opti
60
53
  const identifiers = instances.map((instance) => scopeAttributes
61
54
  .map((attr) => instance[attr])).flat();
62
55
  const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
63
- const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => (Object.assign(Object.assign({}, map), { [identifier]: [] })), {});
64
- const customFieldDefinitions = yield DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction });
65
- const definitionsMap = customFieldDefinitions.reduce((map, definition) => (Object.assign(Object.assign({}, map), { [definition.id]: definition })), {});
56
+ const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
57
+ ...map,
58
+ [identifier]: [],
59
+ }), {});
60
+ const customFieldDefinitions = await DefinitionRepo.findByEntityIds(modelType, uniqueIdentifiers, { transaction: options.transaction });
61
+ const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
62
+ ...map,
63
+ [definition.id]: definition,
64
+ }), {});
66
65
  customFieldDefinitions.forEach((cfd) => {
67
66
  identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
68
67
  });
69
68
  // Get the values per instates ids:
70
69
  const instancesIds = instances.map((i) => i[primaryKey]);
71
- const customFieldValues = yield ValueRepo.findValuesByModelIds(instancesIds, { transaction: options.transaction });
70
+ const customFieldValues = await ValueRepo.findValuesByModelIds(instancesIds, { transaction: options.transaction });
72
71
  // Group fields by modelId
73
72
  const valuesGroupByInstance = customFieldValues.reduce((acc, v) => {
74
73
  const { modelId } = v;
@@ -80,7 +79,6 @@ const enrichResults = (modelType, scopeAttributes) => (instancesOrInstance, opti
80
79
  }, {});
81
80
  // Attach custom fields to the instances
82
81
  instances.forEach((instance) => {
83
- var _a, _b;
84
82
  const customFields = {};
85
83
  const { id } = instance;
86
84
  const instanceValues = valuesGroupByInstance[id];
@@ -91,7 +89,7 @@ const enrichResults = (modelType, scopeAttributes) => (instancesOrInstance, opti
91
89
  scopeAttributes.forEach((attribute) => {
92
90
  const identifier = instance[attribute];
93
91
  const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];
94
- if ((entityCustomFieldDefinitions === null || entityCustomFieldDefinitions === void 0 ? void 0 : entityCustomFieldDefinitions.length) > 0) {
92
+ if (entityCustomFieldDefinitions?.length > 0) {
95
93
  entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
96
94
  if (customFields[customFieldDefinition.name] === undefined) {
97
95
  customFields[customFieldDefinition.name] = null;
@@ -100,13 +98,11 @@ const enrichResults = (modelType, scopeAttributes) => (instancesOrInstance, opti
100
98
  }
101
99
  });
102
100
  instance.customFields = customFields;
103
- (_b = (_a = options.attributesToRemove) === null || _a === void 0 ? void 0 : _a.forEach) === null || _b === void 0 ? void 0 : _b.call(_a, (attribute) => {
104
- var _a;
105
- (_a = instance.dataValues) === null || _a === void 0 ? true : delete _a[attribute];
101
+ options.attributesToRemove?.forEach?.((attribute) => {
102
+ delete instance.dataValues?.[attribute];
106
103
  // if raw:
107
- instance === null || instance === void 0 ? true : delete instance[attribute];
104
+ delete instance?.[attribute];
108
105
  });
109
106
  });
110
- });
107
+ };
111
108
  exports.default = enrichResults;
112
- //# sourceMappingURL=enrich.js.map
@@ -0,0 +1 @@
1
+ export declare const beforeFind: (scopeAttributes: string[]) => (options: any) => void;
@@ -7,10 +7,9 @@ exports.beforeFind = void 0;
7
7
  /* eslint-disable no-param-reassign */
8
8
  const logger_1 = __importDefault(require("../utils/logger"));
9
9
  const doScopeAttributesMissing = (scopeAttributes, queryAttributes) => {
10
- var _a;
11
10
  const attributes = scopeAttributes
12
11
  .filter((attribute) => !queryAttributes.includes(attribute));
13
- if (!((_a = queryAttributes.includes) === null || _a === void 0 ? void 0 : _a.call(queryAttributes, 'id'))) {
12
+ if (!queryAttributes.includes?.('id')) {
14
13
  attributes.push('id');
15
14
  }
16
15
  return attributes;
@@ -18,14 +17,13 @@ const doScopeAttributesMissing = (scopeAttributes, queryAttributes) => {
18
17
  // eslint-disable-next-line import/prefer-default-export
19
18
  const beforeFind = (scopeAttributes) => (options) => {
20
19
  const { attributes: queryAttributes } = options;
21
- if (queryAttributes === null || queryAttributes === void 0 ? void 0 : queryAttributes.includes('customFields')) {
20
+ if (queryAttributes?.includes('customFields')) {
22
21
  const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes);
23
22
  logger_1.default.debug('sadot - before find hook');
24
- if ((missingScopeAttributes === null || missingScopeAttributes === void 0 ? void 0 : missingScopeAttributes.length) > 0) {
23
+ if (missingScopeAttributes?.length > 0) {
25
24
  queryAttributes.push(...missingScopeAttributes);
26
25
  options.attributesToRemove = missingScopeAttributes;
27
26
  }
28
27
  }
29
28
  };
30
29
  exports.beforeFind = beforeFind;
31
- //# sourceMappingURL=find.js.map
@@ -0,0 +1,6 @@
1
+ import enrichResults from './enrich';
2
+ import { beforeFind } from './find';
3
+ import { beforeBulkUpdate, beforeUpdate } from './update';
4
+ import { beforeBulkCreate, beforeCreate } from './create';
5
+ import workaround from './workaround';
6
+ export { enrichResults, beforeFind, beforeBulkUpdate, beforeUpdate, beforeBulkCreate, beforeCreate, workaround, };
@@ -16,4 +16,3 @@ Object.defineProperty(exports, "beforeBulkCreate", { enumerable: true, get: func
16
16
  Object.defineProperty(exports, "beforeCreate", { enumerable: true, get: function () { return create_1.beforeCreate; } });
17
17
  const workaround_1 = __importDefault(require("./workaround"));
18
18
  exports.workaround = workaround_1.default;
19
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * A hook to update the custom fields when updating a model (more then one instance).
3
+ */
4
+ export declare const beforeBulkUpdate: (options: any) => void;
5
+ /**
6
+ * A hook to update the custom fields when updating a model instance.
7
+ * TODO - cleanup if update fail
8
+ */
9
+ export declare const beforeUpdate: (scopeAttributes: string[]) => (instance: any, options: any) => Promise<void>;
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
22
22
  __setModuleDefault(result, mod);
23
23
  return result;
24
24
  };
25
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
- return new (P || (P = Promise))(function (resolve, reject) {
28
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
- step((generator = generator.apply(thisArg, _arguments || [])).next());
32
- });
33
- };
34
25
  var __importDefault = (this && this.__importDefault) || function (mod) {
35
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
36
27
  };
@@ -51,7 +42,7 @@ exports.beforeBulkUpdate = beforeBulkUpdate;
51
42
  * A hook to update the custom fields when updating a model instance.
52
43
  * TODO - cleanup if update fail
53
44
  */
54
- const beforeUpdate = (scopeAttributes) => (instance, options) => __awaiter(void 0, void 0, void 0, function* () {
45
+ const beforeUpdate = (scopeAttributes) => async (instance, options) => {
55
46
  logger_1.default.debug('sadot - before update hook');
56
47
  const { fields } = options;
57
48
  const modelType = instance.constructor.name;
@@ -59,10 +50,9 @@ const beforeUpdate = (scopeAttributes) => (instance, options) => __awaiter(void
59
50
  const customFieldsIdx = fields.indexOf('customFields');
60
51
  if (customFieldsIdx > -1) {
61
52
  const { customFields } = instance;
62
- yield ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
53
+ await ValueRepo.updateValues(modelType, instance.id, identifiers, customFields, { transaction: options.transaction });
63
54
  // eslint-disable-next-line no-param-reassign
64
55
  fields.splice(customFieldsIdx, 1);
65
56
  }
66
- });
57
+ };
67
58
  exports.beforeUpdate = beforeUpdate;
68
- //# sourceMappingURL=update.js.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Workaround to a bug in sequelize.🐛
3
+ *
4
+ * **afterFind hook** isn't working on nested (included) models.
5
+ * The solution here is to add a global afterFind hook,
6
+ * which manually calls the afterFind hook of each model, recursively
7
+ * https://github.com/sequelize/sequelize/issues/4627
8
+ */
9
+ declare const handleChildrenAfterFindHook: (instances: any, options: any, level?: number) => any;
10
+ export default handleChildrenAfterFindHook;
@@ -7,17 +7,8 @@
7
7
  * which manually calls the afterFind hook of each model, recursively
8
8
  * https://github.com/sequelize/sequelize/issues/4627
9
9
  */
10
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
11
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
12
- return new (P || (P = Promise))(function (resolve, reject) {
13
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
14
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
15
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
16
- step((generator = generator.apply(thisArg, _arguments || [])).next());
17
- });
18
- };
19
10
  Object.defineProperty(exports, "__esModule", { value: true });
20
- const handleChildrenAfterFindHook = (instances, options, level = 0) => __awaiter(void 0, void 0, void 0, function* () {
11
+ const handleChildrenAfterFindHook = async (instances, options, level = 0) => {
21
12
  if (!instances)
22
13
  return Promise.resolve();
23
14
  if (Array.isArray(instances)) {
@@ -33,7 +24,7 @@ const handleChildrenAfterFindHook = (instances, options, level = 0) => __awaiter
33
24
  * Only run children "afterFind" hooks.
34
25
  */
35
26
  if (level >= 1) {
36
- yield constructor.runHooks('afterFind', instance, options);
27
+ await constructor.runHooks('afterFind', instance, options);
37
28
  }
38
29
  const { associations } = constructor;
39
30
  const associatedNames = Object.keys(instance).filter((attribute) => Object.keys(associations).includes(attribute));
@@ -42,6 +33,5 @@ const handleChildrenAfterFindHook = (instances, options, level = 0) => __awaiter
42
33
  return handleChildrenAfterFindHook(childInstances, options, level + 1);
43
34
  }
44
35
  return Promise.resolve();
45
- });
36
+ };
46
37
  exports.default = handleChildrenAfterFindHook;
47
- //# sourceMappingURL=workaround.js.map
@@ -0,0 +1,11 @@
1
+ import type { Application } from 'express';
2
+ import { Sequelize } from 'sequelize-typescript';
3
+ import { CustomFieldOptions, ModelFetcher } from './types';
4
+ export * from './utils/validations/custom-fields';
5
+ /**
6
+ * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
7
+ * @see {@link 'custom-fields/config'} for configurations
8
+ */
9
+ declare const useCustomFields: (app: Application | null, getModel: ModelFetcher, options: CustomFieldOptions) => Promise<Sequelize>;
10
+ export default useCustomFields;
11
+ export declare const disableCustomFields: (models: any, getModel: any) => void;
package/dist/index.js CHANGED
@@ -13,15 +13,6 @@ var __createBinding = (this && this.__createBinding) || (Object.create ? (functi
13
13
  var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
17
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
18
- return new (P || (P = Promise))(function (resolve, reject) {
19
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
20
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
21
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
22
- step((generator = generator.apply(thisArg, _arguments || [])).next());
23
- });
24
- };
25
16
  var __importDefault = (this && this.__importDefault) || function (mod) {
26
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
18
  };
@@ -35,7 +26,7 @@ const db_1 = __importDefault(require("./utils/db"));
35
26
  const logger_1 = __importDefault(require("./utils/logger"));
36
27
  __exportStar(require("./utils/validations/custom-fields"), exports);
37
28
  const addHooks = (models, getModel) => {
38
- models.forEach(({ name, scopeAttributes }) => __awaiter(void 0, void 0, void 0, function* () {
29
+ models.forEach(async ({ name, scopeAttributes }) => {
39
30
  try {
40
31
  const model = getModel(name);
41
32
  if (!model) {
@@ -63,29 +54,29 @@ const addHooks = (models, getModel) => {
63
54
  catch (e) {
64
55
  logger_1.default.error(`Could not add custom fields hook to model ${name}. `, e);
65
56
  }
66
- }));
57
+ });
67
58
  };
68
59
  /**
69
60
  * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
70
61
  * @see {@link 'custom-fields/config'} for configurations
71
62
  */
72
- const useCustomFields = (app, getModel, options) => __awaiter(void 0, void 0, void 0, function* () {
63
+ const useCustomFields = async (app, getModel, options) => {
73
64
  const { models } = options;
74
65
  if (app) {
75
66
  app.use('/api', api_1.default);
76
67
  }
77
68
  const sequelize = (0, db_1.default)(options.databaseConfig);
78
69
  if (process.env.NODE_ENV === 'test') {
79
- yield (0, models_1.initTestModels)(sequelize);
70
+ await (0, models_1.initTestModels)(sequelize);
80
71
  }
81
72
  addHooks(models, getModel);
82
- yield (0, models_1.initTables)(sequelize, options.getUser);
73
+ await (0, models_1.initTables)(sequelize, options.getUser);
83
74
  logger_1.default.debug('sadot - custom fields finished initializing with models', models);
84
75
  return sequelize;
85
- });
76
+ };
86
77
  exports.default = useCustomFields;
87
78
  const removeHooks = (models, getModel) => {
88
- models.forEach(({ name }) => __awaiter(void 0, void 0, void 0, function* () {
79
+ models.forEach(async ({ name }) => {
89
80
  try {
90
81
  const model = getModel(name);
91
82
  if (!model)
@@ -106,10 +97,9 @@ const removeHooks = (models, getModel) => {
106
97
  catch (e) {
107
98
  logger_1.default.error(`Could not add custom fields hook to model ${name}. `, e);
108
99
  }
109
- }));
100
+ });
110
101
  };
111
102
  const disableCustomFields = (models, getModel) => {
112
103
  removeHooks(models, getModel);
113
104
  };
114
105
  exports.disableCustomFields = disableCustomFields;
115
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,23 @@
1
+ import { Model } from 'sequelize-typescript';
2
+ import { CustomFieldDefinitionType } from '../utils/validations/type';
3
+ import { CustomFieldValue } from '.';
4
+ declare class CustomFieldDefinition extends Model {
5
+ id: string;
6
+ name: string;
7
+ displayName?: string;
8
+ fieldType: CustomFieldDefinitionType;
9
+ validation?: any;
10
+ entityId: string; /** Client association entity id */
11
+ entityType: string; /** Client association entity type (demand source / fleet / etc.) */
12
+ modelType: string; /** Model type. e.g. Vehicle / StopPoint / etc. */
13
+ description?: string;
14
+ required?: boolean;
15
+ disabled?: boolean;
16
+ createdAt?: Date;
17
+ updatedAt?: Date;
18
+ deletedAt?: Date;
19
+ values: CustomFieldValue[];
20
+ static displayNameDefaultValue(instance: CustomFieldDefinition): void;
21
+ static afterSaveHandler(instance: CustomFieldDefinition, options: any): void;
22
+ }
23
+ export default CustomFieldDefinition;