@autofleet/sadot 0.0.1-beta → 0.0.1-beta.1

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 (150) hide show
  1. package/dist/{src/api → api}/index.js +1 -0
  2. package/dist/api/index.js.map +1 -0
  3. package/dist/{src/api → api}/v1/definition/index.js +28 -25
  4. package/dist/api/v1/definition/index.js.map +1 -0
  5. package/dist/api/v1/definition/validations.js +36 -0
  6. package/dist/api/v1/definition/validations.js.map +1 -0
  7. package/dist/{src/api → api}/v1/errors.js +1 -0
  8. package/dist/api/v1/errors.js.map +1 -0
  9. package/dist/{src/api → api}/v1/index.js +2 -1
  10. package/dist/api/v1/index.js.map +1 -0
  11. package/dist/{src/events → events}/index.js +2 -21
  12. package/dist/events/index.js.map +1 -0
  13. package/dist/{src/hooks → hooks}/create.js +18 -15
  14. package/dist/hooks/create.js.map +1 -0
  15. package/dist/{src/hooks/enrich.js → hooks/find.js} +29 -52
  16. package/dist/hooks/find.js.map +1 -0
  17. package/dist/{src/hooks → hooks}/index.js +4 -5
  18. package/dist/hooks/index.js.map +1 -0
  19. package/dist/{src/hooks → hooks}/update.js +23 -8
  20. package/dist/hooks/update.js.map +1 -0
  21. package/dist/{src/hooks → hooks}/workaround.js +15 -5
  22. package/dist/hooks/workaround.js.map +1 -0
  23. package/dist/index.js +80 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/{src/models → models}/CustomFieldDefinition.js +17 -22
  26. package/dist/models/CustomFieldDefinition.js.map +1 -0
  27. package/dist/{src/models → models}/CustomFieldValue.js +39 -24
  28. package/dist/models/CustomFieldValue.js.map +1 -0
  29. package/dist/models/index.js +50 -0
  30. package/dist/models/index.js.map +1 -0
  31. package/dist/{src/models → models}/tests/AssociatedTestModel.js +1 -0
  32. package/dist/models/tests/AssociatedTestModel.js.map +1 -0
  33. package/dist/{src/models → models}/tests/TestModel.js +1 -0
  34. package/dist/models/tests/TestModel.js.map +1 -0
  35. package/dist/repository/definition.js +107 -0
  36. package/dist/repository/definition.js.map +1 -0
  37. package/dist/{src/repository → repository}/value.js +36 -27
  38. package/dist/repository/value.js.map +1 -0
  39. package/dist/{src/tests → tests}/api/test-api.js +22 -12
  40. package/dist/tests/api/test-api.js.map +1 -0
  41. package/dist/tests/helpers/index.js +28 -0
  42. package/dist/tests/helpers/index.js.map +1 -0
  43. package/dist/tests/mocks/index.js +60 -0
  44. package/dist/tests/mocks/index.js.map +1 -0
  45. package/dist/{src/tests → tests}/mocks/testModel.js +18 -10
  46. package/dist/tests/mocks/testModel.js.map +1 -0
  47. package/dist/tsconfig.tsbuildinfo +1 -0
  48. package/dist/{src/types → types}/definition/index.js +1 -0
  49. package/dist/types/definition/index.js.map +1 -0
  50. package/dist/{src/types → types}/index.js +1 -0
  51. package/dist/types/index.js.map +1 -0
  52. package/dist/{src/types → types}/value/index.js +1 -0
  53. package/dist/types/value/index.js.map +1 -0
  54. package/dist/{src/utils → utils}/db/index.js +1 -8
  55. package/dist/utils/db/index.js.map +1 -0
  56. package/dist/{src/utils → utils}/logger/index.js +2 -2
  57. package/dist/utils/logger/index.js.map +1 -0
  58. package/dist/{src/utils → utils}/validations/custom-fields.js +1 -0
  59. package/dist/utils/validations/custom-fields.js.map +1 -0
  60. package/dist/utils/validations/custom.js +59 -0
  61. package/dist/utils/validations/custom.js.map +1 -0
  62. package/dist/{src/utils → utils}/validations/index.js +1 -0
  63. package/dist/utils/validations/index.js.map +1 -0
  64. package/dist/utils/validations/type.js +32 -0
  65. package/dist/utils/validations/type.js.map +1 -0
  66. package/package.json +3 -6
  67. package/src/api/v1/definition/index.ts +13 -20
  68. package/src/api/v1/definition/validations.ts +27 -13
  69. package/src/api/v1/index.ts +1 -1
  70. package/src/events/index.ts +1 -23
  71. package/src/hooks/create.ts +6 -12
  72. package/src/hooks/find.ts +82 -23
  73. package/src/hooks/index.ts +2 -4
  74. package/src/hooks/update.ts +11 -5
  75. package/src/hooks/workaround.ts +2 -2
  76. package/src/index.ts +17 -60
  77. package/src/models/CustomFieldDefinition.ts +15 -23
  78. package/src/models/CustomFieldValue.ts +10 -10
  79. package/src/models/index.ts +16 -72
  80. package/src/models/tests/AssociatedTestModel.ts +1 -0
  81. package/src/models/tests/TestModel.ts +1 -0
  82. package/src/repository/definition.ts +41 -27
  83. package/src/repository/value.ts +11 -12
  84. package/src/tests/mocks/events.mock.ts +1 -1
  85. package/src/tests/mocks/{definition.mock.ts → index.ts} +6 -5
  86. package/src/tests/mocks/testModel.ts +7 -12
  87. package/src/types/index.ts +6 -4
  88. package/src/utils/db/index.ts +0 -7
  89. package/src/utils/logger/index.ts +1 -3
  90. package/src/utils/validations/custom.ts +44 -26
  91. package/src/utils/validations/type.ts +6 -23
  92. package/tsconfig.json +26 -9
  93. package/dist/jest.config.d.ts +0 -12
  94. package/dist/src/api/index.d.ts +0 -2
  95. package/dist/src/api/v1/definition/index.d.ts +0 -2
  96. package/dist/src/api/v1/definition/validations.d.ts +0 -2
  97. package/dist/src/api/v1/definition/validations.js +0 -36
  98. package/dist/src/api/v1/errors.d.ts +0 -2
  99. package/dist/src/api/v1/index.d.ts +0 -2
  100. package/dist/src/errors/index.d.ts +0 -16
  101. package/dist/src/errors/index.js +0 -45
  102. package/dist/src/events/index.d.ts +0 -4
  103. package/dist/src/hooks/create.d.ts +0 -9
  104. package/dist/src/hooks/enrich.d.ts +0 -5
  105. package/dist/src/hooks/find.d.ts +0 -1
  106. package/dist/src/hooks/find.js +0 -29
  107. package/dist/src/hooks/index.d.ts +0 -6
  108. package/dist/src/hooks/update.d.ts +0 -9
  109. package/dist/src/hooks/workaround.d.ts +0 -10
  110. package/dist/src/index.d.ts +0 -11
  111. package/dist/src/index.js +0 -105
  112. package/dist/src/models/CustomFieldDefinition.d.ts +0 -23
  113. package/dist/src/models/CustomFieldValue.d.ts +0 -15
  114. package/dist/src/models/index.d.ts +0 -8
  115. package/dist/src/models/index.js +0 -87
  116. package/dist/src/models/tests/AssociatedTestModel.d.ts +0 -12
  117. package/dist/src/models/tests/TestModel.d.ts +0 -11
  118. package/dist/src/repository/definition.d.ts +0 -17
  119. package/dist/src/repository/definition.js +0 -80
  120. package/dist/src/repository/value.d.ts +0 -24
  121. package/dist/src/tests/api/test-api.d.ts +0 -2
  122. package/dist/src/tests/helpers/database-config.d.ts +0 -15
  123. package/dist/src/tests/helpers/database-config.js +0 -16
  124. package/dist/src/tests/helpers/index.d.ts +0 -2
  125. package/dist/src/tests/helpers/index.js +0 -18
  126. package/dist/src/tests/mocks/definition.mock.d.ts +0 -37
  127. package/dist/src/tests/mocks/definition.mock.js +0 -64
  128. package/dist/src/tests/mocks/events.mock.d.ts +0 -3
  129. package/dist/src/tests/mocks/events.mock.js +0 -19
  130. package/dist/src/tests/mocks/testModel.d.ts +0 -12
  131. package/dist/src/types/definition/index.d.ts +0 -23
  132. package/dist/src/types/index.d.ts +0 -13
  133. package/dist/src/types/value/index.d.ts +0 -15
  134. package/dist/src/utils/constants/index.d.ts +0 -1
  135. package/dist/src/utils/constants/index.js +0 -5
  136. package/dist/src/utils/db/index.d.ts +0 -4
  137. package/dist/src/utils/logger/index.d.ts +0 -2
  138. package/dist/src/utils/validations/custom-fields.d.ts +0 -2
  139. package/dist/src/utils/validations/custom.d.ts +0 -15
  140. package/dist/src/utils/validations/custom.js +0 -42
  141. package/dist/src/utils/validations/index.d.ts +0 -2
  142. package/dist/src/utils/validations/type.d.ts +0 -18
  143. package/dist/src/utils/validations/type.js +0 -50
  144. package/dist/src/utils/validations/validators.d.ts +0 -12
  145. package/dist/src/utils/validations/validators.js +0 -33
  146. package/src/errors/index.ts +0 -42
  147. package/src/hooks/enrich.ts +0 -125
  148. package/src/tests/helpers/database-config.ts +0 -14
  149. package/src/utils/constants/index.ts +0 -2
  150. package/src/utils/validations/validators.ts +0 -34
package/tsconfig.json CHANGED
@@ -1,13 +1,30 @@
1
1
  {
2
2
  "compilerOptions": {
3
- "target": "es2020",
4
- "module": "commonjs",
5
- "declaration": true,
6
- "outDir": "./dist",
7
- "esModuleInterop": true,
8
- "experimentalDecorators": true,
9
- "emitDecoratorMetadata": true,
10
- "allowJs": true
3
+ "lib": [
4
+ "es2019"
5
+ ],
6
+ "incremental": true,
7
+ "module": "commonjs",
8
+ "esModuleInterop": true,
9
+ "target": "es6",
10
+ "moduleResolution": "node",
11
+ "sourceMap": true,
12
+ "outDir": "./dist",
13
+ "baseUrl": ".",
14
+ "experimentalDecorators": true,
15
+ "emitDecoratorMetadata": true,
16
+ "allowJs": true,
17
+ "paths": {
18
+ "*": [
19
+ "node_modules/*"
20
+ ]
21
+ }
11
22
  },
12
- "exclude": ["node_modules", "**/*.test.ts"]
23
+ "include": [
24
+ "src/**/*", "test"
25
+ ],
26
+ "exclude": [
27
+ "**/*.test.*",
28
+ "**/*.mock.*"
29
+ ]
13
30
  }
@@ -1,12 +0,0 @@
1
- export const testEnvironment: string;
2
- export const roots: string[];
3
- export const transform: {
4
- '^.+\\.tsx?$': string;
5
- };
6
- export const testRegex: string;
7
- export const moduleFileExtensions: string[];
8
- export namespace coverageThreshold {
9
- namespace global {
10
- const lines: number;
11
- }
12
- }
@@ -1,2 +0,0 @@
1
- declare const router: import("express-serve-static-core").Router;
2
- export default router;
@@ -1,2 +0,0 @@
1
- declare const router: import("express-serve-static-core").Router;
2
- export default router;
@@ -1,2 +0,0 @@
1
- export declare const validateCustomFieldDefinitionCreation: (payload: any) => any;
2
- export declare const validateCustomFieldDefinitionUpdate: (payload: any) => any;
@@ -1,36 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.validateCustomFieldDefinitionUpdate = exports.validateCustomFieldDefinitionCreation = void 0;
7
- const joi_1 = __importDefault(require("@hapi/joi"));
8
- const type_1 = require("../../../utils/validations/type");
9
- const ValidationSchema = joi_1.default.when('fieldType', {
10
- is: type_1.CustomFieldDefinitionType.SELECT,
11
- then: joi_1.default.array().items(joi_1.default.string()).min(1).unique(),
12
- otherwise: joi_1.default.any(),
13
- });
14
- const CustomFieldDefinitionCreationSchema = joi_1.default.object({
15
- name: joi_1.default.string().required(),
16
- displayName: joi_1.default.string().required(),
17
- validation: ValidationSchema,
18
- fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)).required(),
19
- entityId: joi_1.default.string().guid().required(),
20
- entityType: joi_1.default.string().required(),
21
- description: joi_1.default.string(),
22
- required: joi_1.default.boolean(),
23
- disabled: joi_1.default.boolean(),
24
- });
25
- const CustomFieldDefinitionUpdateSchema = joi_1.default.object({
26
- displayName: joi_1.default.string(),
27
- validation: ValidationSchema,
28
- fieldType: joi_1.default.string().valid(...Object.values(type_1.CustomFieldDefinitionType)),
29
- description: joi_1.default.string(),
30
- required: joi_1.default.boolean(),
31
- disabled: joi_1.default.boolean(),
32
- });
33
- const validateCustomFieldDefinitionCreation = (payload) => CustomFieldDefinitionCreationSchema.validateAsync(payload, { abortEarly: false });
34
- exports.validateCustomFieldDefinitionCreation = validateCustomFieldDefinitionCreation;
35
- const validateCustomFieldDefinitionUpdate = (payload) => CustomFieldDefinitionUpdateSchema.validateAsync(payload, { abortEarly: false });
36
- exports.validateCustomFieldDefinitionUpdate = validateCustomFieldDefinitionUpdate;
@@ -1,2 +0,0 @@
1
- declare const _default: (err: any, res: any, additionalData?: {}) => any;
2
- export default _default;
@@ -1,2 +0,0 @@
1
- declare const router: import("express-serve-static-core").Router;
2
- export default router;
@@ -1,16 +0,0 @@
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
- }
@@ -1,45 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MissingDefinitionError = exports.InvalidValueError = exports.UnsupportedCustomValidationError = exports.UnsupportedCustomFieldTypeError = exports.MissingRequiredCustomFieldError = void 0;
4
- /* eslint-disable max-classes-per-file */
5
- const errors_1 = require("@autofleet/errors");
6
- class MissingRequiredCustomFieldError extends errors_1.BadRequest {
7
- constructor(missingFields) {
8
- const err = new Error(`The following custom fields are required: ${missingFields.join(',')}`);
9
- super([err], null, missingFields);
10
- this.message = 'MISSING_REQUIRED_CUSTOM_FIELDS';
11
- }
12
- }
13
- exports.MissingRequiredCustomFieldError = MissingRequiredCustomFieldError;
14
- class UnsupportedCustomFieldTypeError extends errors_1.BadRequest {
15
- constructor(fieldType) {
16
- const err = new Error(`Type "${fieldType}" is not supported`);
17
- super([err], null, null);
18
- this.message = 'UNSUPPORTED_CUSTOM_FIELD_TYPE';
19
- }
20
- }
21
- exports.UnsupportedCustomFieldTypeError = UnsupportedCustomFieldTypeError;
22
- class UnsupportedCustomValidationError extends errors_1.BadRequest {
23
- constructor(fieldType) {
24
- const err = new Error(`Validation for "${fieldType}" is not supported`);
25
- super([err], null, null);
26
- this.message = 'UNSUPPORTED_CUSTOM_VALIDATION_TYPE';
27
- }
28
- }
29
- exports.UnsupportedCustomValidationError = UnsupportedCustomValidationError;
30
- class InvalidValueError extends errors_1.BadRequest {
31
- constructor(value, fieldType) {
32
- const err = new Error(`Invalid "${fieldType}" value ${JSON.stringify(value)}`);
33
- super([err], null, null);
34
- this.message = 'INVALID_VALUE';
35
- }
36
- }
37
- exports.InvalidValueError = InvalidValueError;
38
- class MissingDefinitionError extends errors_1.BadRequest {
39
- constructor(fieldNames) {
40
- const err = new Error(`Missing custom field definition for field ${fieldNames.join(',')}`);
41
- super([err], null, null);
42
- this.message = 'MISSING_DEFINITION';
43
- }
44
- }
45
- exports.MissingDefinitionError = MissingDefinitionError;
@@ -1,4 +0,0 @@
1
- import Events from '@autofleet/events';
2
- declare const events: Events;
3
- export declare const sendDimEvent: (instance: any) => void;
4
- export default events;
@@ -1,9 +0,0 @@
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>;
@@ -1,5 +0,0 @@
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;
@@ -1 +0,0 @@
1
- export declare const beforeFind: (scopeAttributes: string[]) => (options: any) => void;
@@ -1,29 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.beforeFind = void 0;
7
- /* eslint-disable no-param-reassign */
8
- const logger_1 = __importDefault(require("../utils/logger"));
9
- const doScopeAttributesMissing = (scopeAttributes, queryAttributes) => {
10
- const attributes = scopeAttributes
11
- .filter((attribute) => !queryAttributes.includes(attribute));
12
- if (!queryAttributes.includes?.('id')) {
13
- attributes.push('id');
14
- }
15
- return attributes;
16
- };
17
- // eslint-disable-next-line import/prefer-default-export
18
- const beforeFind = (scopeAttributes) => (options) => {
19
- const { attributes: queryAttributes } = options;
20
- if (queryAttributes?.includes('customFields')) {
21
- const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes);
22
- logger_1.default.debug('sadot - before find hook');
23
- if (missingScopeAttributes?.length > 0) {
24
- queryAttributes.push(...missingScopeAttributes);
25
- options.attributesToRemove = missingScopeAttributes;
26
- }
27
- }
28
- };
29
- exports.beforeFind = beforeFind;
@@ -1,6 +0,0 @@
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, };
@@ -1,9 +0,0 @@
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>;
@@ -1,10 +0,0 @@
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;
@@ -1,11 +0,0 @@
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/src/index.js DELETED
@@ -1,105 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- var __importDefault = (this && this.__importDefault) || function (mod) {
17
- return (mod && mod.__esModule) ? mod : { "default": mod };
18
- };
19
- Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.disableCustomFields = void 0;
21
- const sequelize_1 = require("sequelize");
22
- const models_1 = require("./models");
23
- const api_1 = __importDefault(require("./api"));
24
- const hooks_1 = require("./hooks");
25
- const db_1 = __importDefault(require("./utils/db"));
26
- const logger_1 = __importDefault(require("./utils/logger"));
27
- __exportStar(require("./utils/validations/custom-fields"), exports);
28
- const addHooks = (models, getModel) => {
29
- models.forEach(async ({ name, scopeAttributes }) => {
30
- try {
31
- const model = getModel(name);
32
- if (!model) {
33
- logger_1.default.warn('sadot - tried to addHooks to a model that does not exist yet', {
34
- name,
35
- scopeAttributes,
36
- });
37
- return;
38
- }
39
- model.rawAttributes.customFields = {
40
- type: sequelize_1.DataTypes.VIRTUAL,
41
- };
42
- model.refreshAttributes();
43
- // TODO: Uncomment after tests are passed
44
- // model.addHook('afterFind', workaround);
45
- model.addHook('beforeFind', 'sadot-beforeFind', (0, hooks_1.beforeFind)(scopeAttributes));
46
- model.addHook('beforeBulkCreate', 'sadot-beforeBulkCreate', hooks_1.beforeBulkCreate);
47
- model.addHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate', hooks_1.beforeBulkUpdate);
48
- model.addHook('beforeCreate', 'sadot-beforeCreate', (0, hooks_1.beforeCreate)(scopeAttributes));
49
- model.addHook('beforeUpdate', 'sadot-beforeUpdate', (0, hooks_1.beforeUpdate)(scopeAttributes));
50
- model.addHook('afterFind', 'sadot-afterFind', (0, hooks_1.enrichResults)(name, scopeAttributes));
51
- model.addHook('afterUpdate', 'sadot-afterUpdate', (0, hooks_1.enrichResults)(name, scopeAttributes));
52
- model.addHook('afterCreate', 'sadot-afterCreate', (0, hooks_1.enrichResults)(name, scopeAttributes));
53
- }
54
- catch (e) {
55
- logger_1.default.error(`Could not add custom fields hook to model ${name}. `, e);
56
- }
57
- });
58
- };
59
- /**
60
- * Adding custom fields enrichment to the models inside the MODELS_FILE_NAME json file
61
- * @see {@link 'custom-fields/config'} for configurations
62
- */
63
- const useCustomFields = async (app, getModel, options) => {
64
- const { models } = options;
65
- if (app) {
66
- app.use('/api', api_1.default);
67
- }
68
- const sequelize = (0, db_1.default)(options.databaseConfig);
69
- if (process.env.NODE_ENV === 'test') {
70
- await (0, models_1.initTestModels)(sequelize);
71
- }
72
- addHooks(models, getModel);
73
- await (0, models_1.initTables)(sequelize, options.getUser);
74
- logger_1.default.debug('sadot - custom fields finished initializing with models', models);
75
- return sequelize;
76
- };
77
- exports.default = useCustomFields;
78
- const removeHooks = (models, getModel) => {
79
- models.forEach(async ({ name }) => {
80
- try {
81
- const model = getModel(name);
82
- if (!model)
83
- return;
84
- if (model.rawAttributes.customFields) {
85
- delete model.rawAttributes.customFields;
86
- model.refreshAttributes();
87
- }
88
- // model.removeHook('afterFind', 'sadot-workaround');
89
- model.removeHook('beforeFind', 'sadot-beforeFind');
90
- model.removeHook('beforeBulkCreate', 'sadot-beforeBulkCreate');
91
- model.removeHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate');
92
- model.removeHook('beforeCreate', 'sadot-beforeCreate');
93
- model.removeHook('beforeUpdate', 'sadot-beforeUpdate');
94
- model.removeHook('afterFind', 'sadot-afterFind');
95
- model.removeHook('afterUpdate', 'sadot-afterUpdate');
96
- }
97
- catch (e) {
98
- logger_1.default.error(`Could not add custom fields hook to model ${name}. `, e);
99
- }
100
- });
101
- };
102
- const disableCustomFields = (models, getModel) => {
103
- removeHooks(models, getModel);
104
- };
105
- exports.disableCustomFields = disableCustomFields;
@@ -1,23 +0,0 @@
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;
@@ -1,15 +0,0 @@
1
- import { Model } from 'sequelize-typescript';
2
- import { CustomFieldDefinition } from '.';
3
- declare class CustomFieldValue extends Model {
4
- modelId: string;
5
- customFieldDefinitionId: string;
6
- value: any;
7
- createdAt?: Date;
8
- updatedAt?: Date;
9
- deletedAt?: Date;
10
- customFieldDefinition: CustomFieldDefinition;
11
- static validateValues(instances: CustomFieldValue[]): Promise<void>;
12
- static validateValue(instance: CustomFieldValue): Promise<void>;
13
- static afterSaveHandler(instance: CustomFieldValue, options: any): void;
14
- }
15
- export default CustomFieldValue;
@@ -1,8 +0,0 @@
1
- import type { Sequelize } from 'sequelize-typescript';
2
- import CustomFieldDefinition from './CustomFieldDefinition';
3
- import CustomFieldValue from './CustomFieldValue';
4
- import TestModel from './tests/TestModel';
5
- import AssociatedTestModel from './tests/AssociatedTestModel';
6
- declare const initTables: (sequelize: Sequelize, getUser: any) => Promise<void>;
7
- declare const initTestModels: (sequelize: Sequelize) => Promise<void>;
8
- export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, initTables, initTestModels, };
@@ -1,87 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.initTestModels = exports.initTables = exports.AssociatedTestModel = exports.TestModel = exports.CustomFieldDefinition = exports.CustomFieldValue = void 0;
7
- /* eslint-disable no-param-reassign */
8
- const sequelize_1 = require("sequelize");
9
- const logger_1 = __importDefault(require("../utils/logger"));
10
- const CustomFieldDefinition_1 = __importDefault(require("./CustomFieldDefinition"));
11
- exports.CustomFieldDefinition = CustomFieldDefinition_1.default;
12
- const CustomFieldValue_1 = __importDefault(require("./CustomFieldValue"));
13
- exports.CustomFieldValue = CustomFieldValue_1.default;
14
- const TestModel_1 = __importDefault(require("./tests/TestModel"));
15
- exports.TestModel = TestModel_1.default;
16
- const AssociatedTestModel_1 = __importDefault(require("./tests/AssociatedTestModel"));
17
- exports.AssociatedTestModel = AssociatedTestModel_1.default;
18
- const productionModels = [CustomFieldDefinition_1.default, CustomFieldValue_1.default];
19
- const testModels = [TestModel_1.default, AssociatedTestModel_1.default];
20
- const SADOT_MIGRATION_PREFIX = 'sadot-migration';
21
- const SCHEMA_VERSION = 1;
22
- const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
23
- const initTables = async (sequelize, getUser) => {
24
- logger_1.default.info('custom-fields: initialize custom-fields tables');
25
- // Detect models and import them to the orm
26
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
27
- if (!sequelize.addModels) {
28
- throw new Error('sequelize instance must have addModels function');
29
- }
30
- sequelize.addModels(productionModels);
31
- CustomFieldDefinition_1.default.addScope('userScope', () => {
32
- const user = getUser();
33
- if (user?.permissions) {
34
- return {
35
- where: {
36
- entityId: [
37
- ...Object.keys(user.permissions.fleets),
38
- ...Object.keys(user.permissions.businessModels),
39
- ...Object.keys(user.permissions.demandSources),
40
- ],
41
- },
42
- };
43
- }
44
- return {};
45
- });
46
- logger_1.default.info('custom-fields: models added');
47
- const SequelizeMeta = sequelize.define('SequelizeMeta', {
48
- name: {
49
- type: sequelize_1.DataTypes.STRING,
50
- allowNull: false,
51
- unique: true,
52
- primaryKey: true,
53
- autoIncrement: false,
54
- },
55
- }, {
56
- tableName: 'SequelizeMeta',
57
- timestamps: false,
58
- schema: 'public',
59
- });
60
- const migrations = await SequelizeMeta.findAll({ raw: true });
61
- const currentSadotSchemaVersion = migrations
62
- .reverse().find((m) => m.name.includes(SADOT_MIGRATION_PREFIX));
63
- if (!currentSadotSchemaVersion
64
- || currentSadotSchemaVersion.name !== CUSTOM_FIELDS_SCHEMA_VERSION) {
65
- await CustomFieldDefinition_1.default.sync({ alter: true });
66
- await CustomFieldValue_1.default.sync({ alter: true });
67
- await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });
68
- logger_1.default.info('custom-fields: models synced');
69
- }
70
- };
71
- exports.initTables = initTables;
72
- const initTestModels = async (sequelize) => {
73
- logger_1.default.info('custom-fields: initialize custom-fields test models');
74
- // Detect models and import them to the orm
75
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
76
- if (!sequelize.addModels) {
77
- throw new Error('sequelize instance must have addModels function');
78
- }
79
- sequelize.addModels(testModels);
80
- await sequelize.dropSchema('custom-fields', { logging: false });
81
- await sequelize.createSchema('custom-fields', { logging: false });
82
- logger_1.default.info('custom-fields: test models added');
83
- await TestModel_1.default.sync({ alter: true });
84
- await AssociatedTestModel_1.default.sync({ alter: true });
85
- logger_1.default.info('custom-fields: test models synced');
86
- };
87
- exports.initTestModels = initTestModels;
@@ -1,12 +0,0 @@
1
- import { Model } from 'sequelize-typescript';
2
- import TestModel from './TestModel';
3
- declare class AssociatedTestModel extends Model {
4
- id: string;
5
- testModelId: string;
6
- fleetId: string;
7
- businessModelId: string;
8
- demandSourceId: string;
9
- anotherAttribute?: boolean;
10
- testModel: TestModel;
11
- }
12
- export default AssociatedTestModel;
@@ -1,11 +0,0 @@
1
- import { Model } from 'sequelize-typescript';
2
- import AssociatedTestModel from './AssociatedTestModel';
3
- declare class TestModel extends Model {
4
- id: string;
5
- fleetId: string;
6
- businessModelId: string;
7
- demandSourceId: string;
8
- coolAttribute?: boolean;
9
- associatedModels: AssociatedTestModel[];
10
- }
11
- export default TestModel;
@@ -1,17 +0,0 @@
1
- import { CustomFieldDefinition } from '../models';
2
- import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
3
- export declare const create: (data: CreateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
4
- export declare const findAll: (where: any, options?: any) => Promise<CustomFieldDefinition[]>;
5
- export declare const findByIds: (ids: string[], options?: any) => Promise<CustomFieldDefinition[]>;
6
- export declare const findById: (id: string, options?: any) => Promise<CustomFieldDefinition | null>;
7
- export declare const findByEntityId: (entityId: string, options?: any) => Promise<CustomFieldDefinition[]>;
8
- export declare const findByEntityIds: (modelType: string, entityIds: string[], options?: any) => Promise<CustomFieldDefinition[]>;
9
- export declare const findByWhere: (where: any) => Promise<CustomFieldDefinition | null>;
10
- export declare const findDefinitionsByModels: (modelTypes: string[], options?: any) => Promise<CustomFieldDefinition[]>;
11
- export declare const update: (id: string, data: UpdateCustomFieldDefinition) => Promise<CustomFieldDefinition>;
12
- export declare const disable: (id: string) => Promise<any>;
13
- export declare const destroy: (id: string) => Promise<any>;
14
- /**
15
- * Return the names of the required fields for a given model
16
- */
17
- export declare const getRequiredFields: (modelType: string, modelId: string | string[], entityId: string | string[]) => Promise<string[]>;
@@ -1,80 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRequiredFields = exports.destroy = exports.disable = exports.update = exports.findDefinitionsByModels = exports.findByWhere = exports.findByEntityIds = exports.findByEntityId = exports.findById = exports.findByIds = exports.findAll = exports.create = void 0;
4
- const sequelize_1 = require("sequelize");
5
- const models_1 = require("../models");
6
- const create = (data) => models_1.CustomFieldDefinition.create(data);
7
- exports.create = create;
8
- const findAll = (where, options = { withDisabled: false }) => {
9
- const queryModel = options.withDisabled
10
- ? models_1.CustomFieldDefinition.unscoped()
11
- : models_1.CustomFieldDefinition;
12
- return queryModel.scope('userScope').findAll({
13
- where,
14
- transaction: options.transaction,
15
- raw: true,
16
- });
17
- };
18
- exports.findAll = findAll;
19
- const findByIds = (ids, options = { withDisabled: false }) => (0, exports.findAll)({ id: { [sequelize_1.Op.in]: ids } }, options);
20
- exports.findByIds = findByIds;
21
- const findById = (id, options = { withDisabled: false }) => {
22
- const { withDisabled } = options;
23
- if (withDisabled) {
24
- return models_1.CustomFieldDefinition.unscoped().scope('userScope').findByPk(id);
25
- }
26
- return models_1.CustomFieldDefinition.scope('userScope').findByPk(id);
27
- };
28
- exports.findById = findById;
29
- const findByEntityId = async (entityId, options = {}) => models_1.CustomFieldDefinition.findAll({
30
- where: { entityId },
31
- transaction: options.transaction,
32
- });
33
- exports.findByEntityId = findByEntityId;
34
- const findByEntityIds = async (modelType, entityIds, options = {}) => models_1.CustomFieldDefinition.findAll({
35
- where: {
36
- modelType,
37
- entityId: entityIds,
38
- },
39
- transaction: options.transaction,
40
- raw: true,
41
- });
42
- exports.findByEntityIds = findByEntityIds;
43
- const findByWhere = (where) => models_1.CustomFieldDefinition.scope('userScope').findOne({
44
- where,
45
- });
46
- exports.findByWhere = findByWhere;
47
- const findDefinitionsByModels = async (modelTypes, options) => {
48
- const query = { modelType: { [sequelize_1.Op.in]: modelTypes } };
49
- return models_1.CustomFieldDefinition.findAll({
50
- where: query,
51
- transaction: options?.transaction,
52
- });
53
- };
54
- exports.findDefinitionsByModels = findDefinitionsByModels;
55
- const update = async (id, data) => {
56
- const updatedDefinition = (await models_1.CustomFieldDefinition.scope('userScope').update(data, {
57
- where: { id },
58
- returning: true,
59
- individualHooks: true,
60
- }))[1][0];
61
- return updatedDefinition;
62
- };
63
- exports.update = update;
64
- const disable = (id) => models_1.CustomFieldDefinition.update({ disabled: true }, { where: { id } });
65
- exports.disable = disable;
66
- const destroy = (id) => models_1.CustomFieldDefinition.destroy({ where: { id } });
67
- exports.destroy = destroy;
68
- /**
69
- * Return the names of the required fields for a given model
70
- */
71
- const getRequiredFields = async (modelType, modelId, entityId) => {
72
- const entityIds = Array.isArray(entityId) ? entityId : [entityId];
73
- const requiredFields = await models_1.CustomFieldDefinition.findAll({
74
- where: { required: true, modelType, entityId: { [sequelize_1.Op.in]: entityIds } },
75
- logging: true,
76
- });
77
- const requiredFieldsNames = requiredFields.map((definition) => definition.name);
78
- return [...new Set(requiredFieldsNames)];
79
- };
80
- exports.getRequiredFields = getRequiredFields;