@autofleet/sadot 0.0.1-beta

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/jest.config.d.ts +12 -0
  2. package/dist/src/api/index.d.ts +2 -0
  3. package/dist/src/api/index.js +11 -0
  4. package/dist/src/api/v1/definition/index.d.ts +2 -0
  5. package/dist/src/api/v1/definition/index.js +118 -0
  6. package/dist/src/api/v1/definition/validations.d.ts +2 -0
  7. package/dist/src/api/v1/definition/validations.js +36 -0
  8. package/dist/src/api/v1/errors.d.ts +2 -0
  9. package/dist/src/api/v1/errors.js +15 -0
  10. package/dist/src/api/v1/index.d.ts +2 -0
  11. package/dist/src/api/v1/index.js +10 -0
  12. package/dist/src/errors/index.d.ts +16 -0
  13. package/dist/src/errors/index.js +45 -0
  14. package/dist/src/events/index.d.ts +4 -0
  15. package/dist/src/events/index.js +47 -0
  16. package/dist/src/hooks/create.d.ts +9 -0
  17. package/dist/src/hooks/create.js +70 -0
  18. package/dist/src/hooks/enrich.d.ts +5 -0
  19. package/dist/src/hooks/enrich.js +118 -0
  20. package/dist/src/hooks/find.d.ts +1 -0
  21. package/dist/src/hooks/find.js +29 -0
  22. package/dist/src/hooks/index.d.ts +6 -0
  23. package/dist/src/hooks/index.js +18 -0
  24. package/dist/src/hooks/update.d.ts +9 -0
  25. package/dist/src/hooks/update.js +58 -0
  26. package/dist/src/hooks/workaround.d.ts +10 -0
  27. package/dist/src/hooks/workaround.js +37 -0
  28. package/dist/src/index.d.ts +11 -0
  29. package/dist/src/index.js +105 -0
  30. package/dist/src/models/CustomFieldDefinition.d.ts +23 -0
  31. package/dist/src/models/CustomFieldDefinition.js +165 -0
  32. package/dist/src/models/CustomFieldValue.d.ts +15 -0
  33. package/dist/src/models/CustomFieldValue.js +148 -0
  34. package/dist/src/models/index.d.ts +8 -0
  35. package/dist/src/models/index.js +87 -0
  36. package/dist/src/models/tests/AssociatedTestModel.d.ts +12 -0
  37. package/dist/src/models/tests/AssociatedTestModel.js +71 -0
  38. package/dist/src/models/tests/TestModel.d.ts +11 -0
  39. package/dist/src/models/tests/TestModel.js +63 -0
  40. package/dist/src/repository/definition.d.ts +17 -0
  41. package/dist/src/repository/definition.js +80 -0
  42. package/dist/src/repository/value.d.ts +24 -0
  43. package/dist/src/repository/value.js +107 -0
  44. package/dist/src/tests/api/test-api.d.ts +2 -0
  45. package/dist/src/tests/api/test-api.js +56 -0
  46. package/dist/src/tests/helpers/database-config.d.ts +15 -0
  47. package/dist/src/tests/helpers/database-config.js +16 -0
  48. package/dist/src/tests/helpers/index.d.ts +2 -0
  49. package/dist/src/tests/helpers/index.js +18 -0
  50. package/dist/src/tests/mocks/definition.mock.d.ts +37 -0
  51. package/dist/src/tests/mocks/definition.mock.js +64 -0
  52. package/dist/src/tests/mocks/events.mock.d.ts +3 -0
  53. package/dist/src/tests/mocks/events.mock.js +19 -0
  54. package/dist/src/tests/mocks/testModel.d.ts +12 -0
  55. package/dist/src/tests/mocks/testModel.js +35 -0
  56. package/dist/src/types/definition/index.d.ts +23 -0
  57. package/dist/src/types/definition/index.js +2 -0
  58. package/dist/src/types/index.d.ts +13 -0
  59. package/dist/src/types/index.js +2 -0
  60. package/dist/src/types/value/index.d.ts +15 -0
  61. package/dist/src/types/value/index.js +2 -0
  62. package/dist/src/utils/constants/index.d.ts +1 -0
  63. package/dist/src/utils/constants/index.js +5 -0
  64. package/dist/src/utils/db/index.d.ts +4 -0
  65. package/dist/src/utils/db/index.js +24 -0
  66. package/dist/src/utils/logger/index.d.ts +2 -0
  67. package/dist/src/utils/logger/index.js +6 -0
  68. package/dist/src/utils/validations/custom-fields.d.ts +2 -0
  69. package/dist/src/utils/validations/custom-fields.js +10 -0
  70. package/dist/src/utils/validations/custom.d.ts +15 -0
  71. package/dist/src/utils/validations/custom.js +42 -0
  72. package/dist/src/utils/validations/index.d.ts +2 -0
  73. package/dist/src/utils/validations/index.js +20 -0
  74. package/dist/src/utils/validations/type.d.ts +18 -0
  75. package/dist/src/utils/validations/type.js +50 -0
  76. package/dist/src/utils/validations/validators.d.ts +12 -0
  77. package/dist/src/utils/validations/validators.js +33 -0
  78. package/package.json +44 -0
  79. package/src/api/index.ts +9 -0
  80. package/src/api/v1/definition/index.ts +110 -0
  81. package/src/api/v1/definition/validations.ts +35 -0
  82. package/src/api/v1/errors.ts +16 -0
  83. package/src/api/v1/index.ts +9 -0
  84. package/src/errors/index.ts +42 -0
  85. package/src/events/index.ts +50 -0
  86. package/src/hooks/create.ts +51 -0
  87. package/src/hooks/enrich.ts +125 -0
  88. package/src/hooks/find.ts +27 -0
  89. package/src/hooks/index.ts +15 -0
  90. package/src/hooks/update.ts +39 -0
  91. package/src/hooks/workaround.ts +47 -0
  92. package/src/index.ts +101 -0
  93. package/src/models/CustomFieldDefinition.ts +140 -0
  94. package/src/models/CustomFieldValue.ts +114 -0
  95. package/src/models/index.ts +101 -0
  96. package/src/models/tests/AssociatedTestModel.ts +57 -0
  97. package/src/models/tests/TestModel.ts +49 -0
  98. package/src/repository/definition.ts +111 -0
  99. package/src/repository/value.ts +99 -0
  100. package/src/tests/api/test-api.ts +38 -0
  101. package/src/tests/helpers/database-config.ts +14 -0
  102. package/src/tests/helpers/index.ts +15 -0
  103. package/src/tests/mocks/definition.mock.ts +69 -0
  104. package/src/tests/mocks/events.mock.ts +18 -0
  105. package/src/tests/mocks/testModel.ts +37 -0
  106. package/src/types/definition/index.ts +22 -0
  107. package/src/types/index.ts +15 -0
  108. package/src/types/value/index.ts +14 -0
  109. package/src/utils/constants/index.ts +2 -0
  110. package/src/utils/db/index.ts +21 -0
  111. package/src/utils/logger/index.ts +6 -0
  112. package/src/utils/validations/custom-fields.ts +9 -0
  113. package/src/utils/validations/custom.ts +39 -0
  114. package/src/utils/validations/index.ts +19 -0
  115. package/src/utils/validations/type.ts +45 -0
  116. package/src/utils/validations/validators.ts +34 -0
  117. package/tsconfig.json +13 -0
@@ -0,0 +1,14 @@
1
+ export default {
2
+ test: {
3
+ username: process.env.DB_USERNAME || '',
4
+ password: process.env.DB_PASSWORD || null,
5
+ database: process.env.DB_NAME || 'sadot_package_test',
6
+ host: process.env.DB_HOST || '127.0.0.1',
7
+ dialect: process.env.DB_TYPE || 'postgres',
8
+ define: {
9
+ underscored: true,
10
+ underscoredAll: true,
11
+ },
12
+ logging: false,
13
+ },
14
+ };
@@ -0,0 +1,15 @@
1
+ import { CustomFieldDefinition, TestModel } from '../../models';
2
+
3
+ // eslint-disable-next-line import/prefer-default-export
4
+ export const cleanup = async (): Promise<void> => {
5
+ if (process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development') {
6
+ await CustomFieldDefinition.unscoped().destroy({ where: {} });
7
+ await TestModel.destroy({ where: {} });
8
+ }
9
+ };
10
+
11
+ export const getModel = (name: string) => {
12
+ // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
13
+ const models = require('../../models');
14
+ return models[name];
15
+ };
@@ -0,0 +1,69 @@
1
+ import { v4 as uuidv4 } from 'uuid';
2
+ import { CreateCustomFieldDefinition, CustomFieldDefinitionDTO } from '../../types/definition';
3
+
4
+ export const coolFieldDefinition: CreateCustomFieldDefinition = {
5
+ name: 'cool field',
6
+ modelType: 'TestModel',
7
+ fieldType: 'number',
8
+ entityId: uuidv4(),
9
+ entityType: 'fleetId',
10
+ };
11
+
12
+ export const coolFieldDefinition2 = {
13
+ ...coolFieldDefinition,
14
+ name: 'cool field2',
15
+ };
16
+
17
+ export const coolFieldDefinition3 = {
18
+ ...coolFieldDefinition,
19
+ name: 'cool field3',
20
+ };
21
+
22
+ export const booleanField = (modelType: string): CreateCustomFieldDefinition => ({
23
+ name: 'shapeless',
24
+ modelType,
25
+ fieldType: 'boolean',
26
+ entityId: uuidv4(),
27
+ entityType: 'fleetId',
28
+ });
29
+
30
+ export const enumField = (modelType: string, options): CreateCustomFieldDefinition => ({
31
+ name: 'choices',
32
+ modelType,
33
+ fieldType: 'select',
34
+ validation: options,
35
+ entityId: uuidv4(),
36
+ entityType: 'fleetId',
37
+ });
38
+
39
+ export const rangeField = (modelType: string): CreateCustomFieldDefinition => ({
40
+ name: 'ranges',
41
+ modelType,
42
+ fieldType: 'number',
43
+ validation: {
44
+ between: [10, 12],
45
+ },
46
+ entityId: uuidv4(),
47
+ entityType: 'fleetId',
48
+ });
49
+
50
+ // eslint-disable-next-line max-len
51
+ export const createDefinition = (defaults: Partial<CustomFieldDefinitionDTO>): CreateCustomFieldDefinition => ({
52
+ name: defaults?.name || `def_${uuidv4()}`,
53
+ modelType: defaults?.modelType || 'TestModel',
54
+ fieldType: defaults?.fieldType || 'boolean',
55
+ entityId: defaults?.entityId || uuidv4(),
56
+ entityType: defaults?.entityType || 'fleetId',
57
+ });
58
+
59
+ export const createDefinitions = (
60
+ defaults: Partial<CustomFieldDefinitionDTO>,
61
+ length = 1,
62
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
63
+ ): CreateCustomFieldDefinition[] => (Array(length).fill({}).map((_) => ({
64
+ name: defaults?.name || `def_${uuidv4()}`,
65
+ modelType: defaults?.modelType || 'TestModel',
66
+ fieldType: defaults?.fieldType || 'boolean',
67
+ entityId: defaults?.entityId || uuidv4(),
68
+ entityType: defaults?.entityType || 'fleetId',
69
+ })));
@@ -0,0 +1,18 @@
1
+ /* eslint-disable no-param-reassign */
2
+
3
+ export const mockEvent = (events: any, eventName, numberOfEvents) => {
4
+ events.sendObject = jest.fn();
5
+ return [
6
+ events.sendObject,
7
+ (): void => {
8
+ const matchingEvents = events.sendObject.mock.calls.filter((call) => call[0] === eventName);
9
+ expect(matchingEvents.length).toEqual(numberOfEvents);
10
+ },
11
+ ];
12
+ };
13
+
14
+ export const mockDimCustomFieldDefinitionEvent = (events, numberOfEvents) =>
15
+ mockEvent(events, 'dim_custom_field_definition', numberOfEvents);
16
+
17
+ export const mockDimCustomFieldValueEvent = (events, numberOfEvents) =>
18
+ mockEvent(events, 'dim_custom_field_value', numberOfEvents);
@@ -0,0 +1,37 @@
1
+ import { TestModel, AssociatedTestModel } from '../../models';
2
+
3
+ export const createTestModel = (payload = {}) => TestModel.create(payload);
4
+
5
+ export const createTestModels = (fleetId, total: number) => {
6
+ const models = [];
7
+ for (let i = 0; i < total; i += 1) {
8
+ models.push(createTestModel({ fleetId }));
9
+ }
10
+ return Promise.all<TestModel>(models);
11
+ };
12
+
13
+ export const upsertTestModel = (payload) => TestModel.upsert(payload);
14
+
15
+ export const destroyTestModels = () => TestModel.destroy({ truncate: true });
16
+
17
+ export const getTestModel = (
18
+ id: string,
19
+ options = {},
20
+ ): Promise<TestModel> => TestModel.findByPk(id, options);
21
+
22
+ export const getSomeTestModels = (
23
+ options = { limit: 1 },
24
+ ): Promise<TestModel[]> => TestModel.findAll(options);
25
+
26
+ export const updateTestModel = (payload, query) => TestModel.update(payload, query);
27
+
28
+ // Associations
29
+ export const createTestModelWithAssociation = async () => {
30
+ const model = await TestModel.create({});
31
+ await AssociatedTestModel.create({ testModelId: model.id });
32
+ return model;
33
+ };
34
+
35
+ export const getTestModelWithAssociation = (limit = 1) => TestModel.findAll({
36
+ limit, include: [AssociatedTestModel],
37
+ });
@@ -0,0 +1,22 @@
1
+ export interface CustomFieldDefinitionDTO {
2
+ id: string;
3
+ name: string;
4
+ displayName?: string;
5
+ validation?: any;
6
+ fieldType: string;
7
+ entityId: string;
8
+ entityType: string;
9
+ modelType: string;
10
+ required?: boolean;
11
+ description?: string;
12
+ disabled?: boolean;
13
+ createdAt?: Date;
14
+ updatedAt?: Date;
15
+ deletedAt?: Date;
16
+ }
17
+ export type CreateCustomFieldDefinition = Omit<CustomFieldDefinitionDTO, 'id'>;
18
+ export type UpdateCustomFieldDefinition = Partial<CreateCustomFieldDefinition>;
19
+
20
+ export type SerializedCustomFields = {
21
+ [name: string]: CustomFieldDefinitionDTO & { value: any };
22
+ };
@@ -0,0 +1,15 @@
1
+ export type ModelFetcher = (name: string) => any;
2
+
3
+ export type ModelOptions = {
4
+ name: string;
5
+ scopeAttributes: string[];
6
+ creationWebhookHandler?: (instance: any) => any;
7
+ updateWebhookHandler?: (instance: any) => any;
8
+ deletionWebhookHandler?: (instance: any) => any;
9
+ }
10
+
11
+ export type CustomFieldOptions= {
12
+ models: ModelOptions[];
13
+ databaseConfig: any;
14
+ getUser: () => any;
15
+ };
@@ -0,0 +1,14 @@
1
+ export interface CustomFieldValueDTO {
2
+ id?: string;
3
+ modelId: string;
4
+ customFieldDefinitionId: string;
5
+ value: any;
6
+ createdAt?: Date;
7
+ updatedAt?: Date;
8
+ deletedAt?: Date;
9
+ }
10
+
11
+ export type ValuesToUpdate = {[name: string]: any };
12
+ export type CreateCustomFieldValue = Omit<CustomFieldValueDTO, 'id'>;
13
+ export type UpdateCustomFieldValue = ValuesToUpdate;
14
+ export type BulkUpdateCustomFieldValue = Partial<CustomFieldValueDTO>[];
@@ -0,0 +1,2 @@
1
+ // eslint-disable-next-line import/prefer-default-export
2
+ export const supportedEntities = ['businessModelId', 'fleetId', 'demandSourceId'];
@@ -0,0 +1,21 @@
1
+ import { Sequelize } from 'sequelize-typescript';
2
+ import { QueryTypes } from 'sequelize';
3
+
4
+ export default (databaseConfig: any): Sequelize => {
5
+ const ENV_DEV = 'test';
6
+ const env: string = process.env.NODE_ENV || ENV_DEV;
7
+ const config = databaseConfig[env];
8
+ let sequelize: Sequelize;
9
+ if (config.use_env_variable) {
10
+ sequelize = new Sequelize(process.env[config.use_env_variable], config);
11
+ } else {
12
+ sequelize = new Sequelize(config.database, config.username, config.password, config);
13
+ }
14
+ return sequelize;
15
+ };
16
+
17
+ export const createSequelizeMeta = (sequelize: Sequelize) => sequelize.query(`
18
+ CREATE TABLE IF NOT EXISTS "SequelizeMeta" (
19
+ name character varying(255) PRIMARY KEY
20
+ );
21
+ `, { type: QueryTypes.SELECT });
@@ -0,0 +1,6 @@
1
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
2
+ const Logger = require('@autofleet/logger');
3
+
4
+ const logger = Logger();
5
+
6
+ export default logger;
@@ -0,0 +1,9 @@
1
+ /* eslint-disable import/prefer-default-export */
2
+ import Joi from '@hapi/joi';
3
+
4
+ const CustomFieldsSchema = Joi.object().pattern(
5
+ Joi.string(),
6
+ Joi.any(),
7
+ );
8
+
9
+ export { CustomFieldsSchema };
@@ -0,0 +1,39 @@
1
+ /* eslint-disable no-shadow */
2
+ import logger from '../logger';
3
+ import { CustomFieldDefinitionType } from './type';
4
+ import validators from './validators';
5
+
6
+ export const mustHaveCustomValidation = {
7
+ [CustomFieldDefinitionType.SELECT]: true,
8
+ };
9
+
10
+ /**
11
+ * Validates the given validations object against the supported field types and their validators.
12
+ * @return true if the validation is valid, false otherwise.
13
+ */
14
+ export const validateValidation = (valueType, validation) => {
15
+ if (!validation) {
16
+ if (mustHaveCustomValidation[valueType]) {
17
+ logger.error(`No custom validation for custom field type ${valueType} found`);
18
+ return false;
19
+ }
20
+ return true;
21
+ }
22
+ return true;
23
+ };
24
+
25
+ /**
26
+ * Validates the given value against the custom validation rules for the specified field type.
27
+ * If no custom validation rules are provided, it falls back to the default validation.
28
+ * @returns true if the value is valid according to the validation rules, false otherwise.
29
+ */
30
+ const customValidation = (value, valueType, validation) => {
31
+ const validator = validators?.[valueType];
32
+ if (!validation || !validator) {
33
+ return validateValidation(valueType, validation);
34
+ }
35
+ // Always allow null values
36
+ return value === null || validator(value, validation);
37
+ };
38
+
39
+ export default customValidation;
@@ -0,0 +1,19 @@
1
+ import customValidation from './custom';
2
+ import validateValueType from './type';
3
+
4
+ const validateValue = (value, valueType, customValidations) => {
5
+ if (!validateValueType(value, valueType)) {
6
+ return false;
7
+ }
8
+ if (customValidations) {
9
+ return customValidation(value, valueType, customValidations);
10
+ }
11
+
12
+ // if (validations.required && !value) {
13
+ // return false;
14
+ // }
15
+
16
+ return true;
17
+ };
18
+
19
+ export default validateValue;
@@ -0,0 +1,45 @@
1
+ import Joi from '@hapi/joi';
2
+ /**
3
+ * Supported custom field types
4
+ */
5
+ // eslint-disable-next-line no-shadow
6
+ export enum CustomFieldDefinitionType {
7
+ NUMBER = 'number',
8
+ BOOLEAN = 'boolean',
9
+ DATE = 'date',
10
+ DATETIME = 'datetime',
11
+ TEXT = 'text',
12
+ IMAGE = 'image',
13
+ SELECT = 'select',
14
+ }
15
+ /**
16
+ * Validate that the given value is really of type "valueType"
17
+ * TODO: verify that required field not set to null
18
+ */
19
+ const validateValueType = (value: unknown, valueType: CustomFieldDefinitionType): boolean => {
20
+ if (value === null) {
21
+ // Null is always allowed
22
+ return true;
23
+ }
24
+
25
+ switch (valueType) {
26
+ case CustomFieldDefinitionType.TEXT:
27
+ return typeof value === 'string';
28
+ case CustomFieldDefinitionType.NUMBER:
29
+ return typeof value === 'number';
30
+ case CustomFieldDefinitionType.BOOLEAN:
31
+ return typeof value === 'boolean';
32
+ case CustomFieldDefinitionType.DATE:
33
+ case CustomFieldDefinitionType.DATETIME:
34
+ return !Joi.date().validate(value).error;
35
+ case CustomFieldDefinitionType.SELECT:
36
+ return true; // custom validation
37
+ case CustomFieldDefinitionType.IMAGE:
38
+ return !Joi.array().min(1).unique().items(Joi.string().uri())
39
+ .validate(value).error;
40
+ default:
41
+ return false;
42
+ }
43
+ };
44
+
45
+ export default validateValueType;
@@ -0,0 +1,34 @@
1
+ // eslint-disable-next-line no-shadow
2
+ export enum CustomValidations {
3
+ SELECT = 'select',
4
+ RANGE = 'between'
5
+ }
6
+
7
+ type Validator = (value, validation) => boolean;
8
+ /**
9
+ * Validate {@link CustomValidations.ENUM Enum}
10
+ */
11
+ const validateEnum: Validator = (value, enumValues) => (Array.isArray(enumValues)
12
+ && enumValues.length > 0
13
+ && enumValues.includes(value)
14
+ );
15
+ /**
16
+ * Validate {@link CustomValidations.RANGE Range}
17
+ */
18
+ const validateRange: Validator = (value, range) => {
19
+ const [min, max] = range;
20
+ if (min === undefined || max === undefined) {
21
+ return false;
22
+ }
23
+ return value >= range.min && value <= range.max;
24
+ };
25
+
26
+ /**
27
+ * Validators for custom fields
28
+ */
29
+ const validators: { [key: string]: Validator } = {
30
+ [CustomValidations.SELECT]: validateEnum,
31
+ [CustomValidations.RANGE]: validateRange,
32
+ };
33
+
34
+ export default validators;
package/tsconfig.json ADDED
@@ -0,0 +1,13 @@
1
+ {
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
11
+ },
12
+ "exclude": ["node_modules", "**/*.test.ts"]
13
+ }