@autofleet/sadot 0.0.2-beta → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) 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 +27 -23
  4. package/dist/api/v1/definition/index.js.map +1 -0
  5. package/dist/{src/api → api}/v1/definition/validations.js +5 -7
  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 +1 -0
  10. package/dist/api/v1/index.js.map +1 -0
  11. package/dist/{src/errors → errors}/index.js +1 -0
  12. package/dist/errors/index.js.map +1 -0
  13. package/dist/{src/events → events}/index.js +2 -21
  14. package/dist/events/index.js.map +1 -0
  15. package/dist/{src/hooks → hooks}/create.js +15 -10
  16. package/dist/hooks/create.js.map +1 -0
  17. package/dist/{src/hooks → hooks}/enrich.js +34 -42
  18. package/dist/hooks/enrich.js.map +1 -0
  19. package/dist/{src/hooks → hooks}/find.js +6 -9
  20. package/dist/hooks/find.js.map +1 -0
  21. package/dist/{src/hooks → hooks}/index.js +1 -0
  22. package/dist/hooks/index.js.map +1 -0
  23. package/dist/{src/hooks → hooks}/update.js +12 -7
  24. package/dist/hooks/update.js.map +1 -0
  25. package/dist/{src/hooks → hooks}/workaround.js +13 -3
  26. package/dist/hooks/workaround.js.map +1 -0
  27. package/dist/{src/index.js → index.js} +20 -21
  28. package/dist/index.js.map +1 -0
  29. package/dist/{src/models → models}/CustomFieldDefinition.js +3 -2
  30. package/dist/models/CustomFieldDefinition.js.map +1 -0
  31. package/dist/{src/models → models}/CustomFieldValue.js +34 -20
  32. package/dist/models/CustomFieldValue.js.map +1 -0
  33. package/dist/models/index.js +63 -0
  34. package/dist/models/index.js.map +1 -0
  35. package/dist/{src/models → models}/tests/AssociatedTestModel.js +1 -0
  36. package/dist/models/tests/AssociatedTestModel.js.map +1 -0
  37. package/dist/{src/models → models}/tests/TestModel.js +1 -0
  38. package/dist/models/tests/TestModel.js.map +1 -0
  39. package/dist/repository/definition.js +97 -0
  40. package/dist/repository/definition.js.map +1 -0
  41. package/dist/{src/repository → repository}/value.js +29 -20
  42. package/dist/repository/value.js.map +1 -0
  43. package/dist/{src/tests → tests}/api/test-api.js +22 -12
  44. package/dist/tests/api/test-api.js.map +1 -0
  45. package/dist/{src/tests → tests}/helpers/database-config.js +1 -0
  46. package/dist/tests/helpers/database-config.js.map +1 -0
  47. package/dist/tests/helpers/index.js +28 -0
  48. package/dist/tests/helpers/index.js.map +1 -0
  49. package/dist/{src/tests → tests}/mocks/definition.mock.js +13 -18
  50. package/dist/tests/mocks/definition.mock.js.map +1 -0
  51. package/dist/{src/tests → tests}/mocks/events.mock.js +1 -0
  52. package/dist/tests/mocks/events.mock.js.map +1 -0
  53. package/dist/{src/tests → tests}/mocks/testModel.js +14 -4
  54. package/dist/tests/mocks/testModel.js.map +1 -0
  55. package/dist/tsconfig.tsbuildinfo +1 -0
  56. package/dist/{src/types → types}/definition/index.js +1 -0
  57. package/dist/types/definition/index.js.map +1 -0
  58. package/dist/{src/types → types}/index.js +1 -0
  59. package/dist/types/index.js.map +1 -0
  60. package/dist/{src/types → types}/value/index.js +1 -0
  61. package/dist/types/value/index.js.map +1 -0
  62. package/dist/{src/utils → utils}/db/index.js +1 -8
  63. package/dist/utils/db/index.js.map +1 -0
  64. package/dist/{src/utils → utils}/logger/index.js +2 -2
  65. package/dist/utils/logger/index.js.map +1 -0
  66. package/dist/{src/utils → utils}/validations/custom-fields.js +1 -0
  67. package/dist/utils/validations/custom-fields.js.map +1 -0
  68. package/dist/{src/utils → utils}/validations/custom.js +2 -1
  69. package/dist/utils/validations/custom.js.map +1 -0
  70. package/dist/{src/utils → utils}/validations/index.js +1 -0
  71. package/dist/utils/validations/index.js.map +1 -0
  72. package/dist/{src/utils → utils}/validations/type.js +2 -2
  73. package/dist/utils/validations/type.js.map +1 -0
  74. package/dist/{src/utils → utils}/validations/validators.js +1 -0
  75. package/dist/utils/validations/validators.js.map +1 -0
  76. package/package.json +1 -3
  77. package/src/api/v1/definition/index.ts +3 -10
  78. package/src/api/v1/definition/validations.ts +4 -8
  79. package/src/events/index.ts +1 -23
  80. package/src/hooks/create.ts +0 -2
  81. package/src/hooks/enrich.ts +18 -41
  82. package/src/hooks/find.ts +0 -2
  83. package/src/hooks/update.ts +0 -2
  84. package/src/index.ts +6 -19
  85. package/src/models/CustomFieldDefinition.ts +1 -1
  86. package/src/models/index.ts +17 -59
  87. package/src/repository/definition.ts +25 -22
  88. package/src/repository/value.ts +1 -2
  89. package/src/types/index.ts +4 -4
  90. package/src/utils/db/index.ts +0 -7
  91. package/src/utils/logger/index.ts +1 -3
  92. package/src/utils/validations/type.ts +1 -2
  93. package/tsconfig.json +25 -9
  94. package/dist/jest.config.d.ts +0 -12
  95. package/dist/src/api/index.d.ts +0 -2
  96. package/dist/src/api/v1/definition/index.d.ts +0 -2
  97. package/dist/src/api/v1/definition/validations.d.ts +0 -2
  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/events/index.d.ts +0 -4
  102. package/dist/src/hooks/create.d.ts +0 -9
  103. package/dist/src/hooks/enrich.d.ts +0 -5
  104. package/dist/src/hooks/find.d.ts +0 -1
  105. package/dist/src/hooks/index.d.ts +0 -6
  106. package/dist/src/hooks/update.d.ts +0 -9
  107. package/dist/src/hooks/workaround.d.ts +0 -10
  108. package/dist/src/index.d.ts +0 -11
  109. package/dist/src/models/CustomFieldDefinition.d.ts +0 -23
  110. package/dist/src/models/CustomFieldValue.d.ts +0 -15
  111. package/dist/src/models/index.d.ts +0 -8
  112. package/dist/src/models/index.js +0 -87
  113. package/dist/src/models/tests/AssociatedTestModel.d.ts +0 -12
  114. package/dist/src/models/tests/TestModel.d.ts +0 -11
  115. package/dist/src/repository/definition.d.ts +0 -17
  116. package/dist/src/repository/definition.js +0 -80
  117. package/dist/src/repository/value.d.ts +0 -24
  118. package/dist/src/tests/api/test-api.d.ts +0 -2
  119. package/dist/src/tests/helpers/database-config.d.ts +0 -15
  120. package/dist/src/tests/helpers/index.d.ts +0 -2
  121. package/dist/src/tests/helpers/index.js +0 -18
  122. package/dist/src/tests/mocks/definition.mock.d.ts +0 -37
  123. package/dist/src/tests/mocks/events.mock.d.ts +0 -3
  124. package/dist/src/tests/mocks/testModel.d.ts +0 -12
  125. package/dist/src/types/definition/index.d.ts +0 -23
  126. package/dist/src/types/index.d.ts +0 -13
  127. package/dist/src/types/value/index.d.ts +0 -15
  128. package/dist/src/utils/constants/index.d.ts +0 -1
  129. package/dist/src/utils/constants/index.js +0 -5
  130. package/dist/src/utils/db/index.d.ts +0 -4
  131. package/dist/src/utils/logger/index.d.ts +0 -2
  132. package/dist/src/utils/validations/custom-fields.d.ts +0 -2
  133. package/dist/src/utils/validations/custom.d.ts +0 -15
  134. package/dist/src/utils/validations/index.d.ts +0 -2
  135. package/dist/src/utils/validations/type.d.ts +0 -18
  136. package/dist/src/utils/validations/validators.d.ts +0 -12
  137. package/src/utils/constants/index.ts +0 -2
@@ -2,30 +2,22 @@
2
2
  import * as ValueRepo from '../repository/value';
3
3
  import * as DefinitionRepo from '../repository/definition';
4
4
  import CustomFieldValue from '../models/CustomFieldValue';
5
- import CustomFieldDefinition from '../models/CustomFieldDefinition';
6
5
  import { SerializedCustomFields } from '../types/definition';
7
- import logger from '../utils/logger';
8
6
 
9
7
  /**
10
8
  * Serialize custom fields value into the format of {[name] -> [fieldData]}
11
9
  */
12
- const serializeCustomFields = (
13
- customFieldValues: CustomFieldValue[],
14
- customFieldDefinitionsHash: Record<string, CustomFieldDefinition>,
15
- ): SerializedCustomFields => {
10
+ const serializeCustomFields = (customFieldValues: CustomFieldValue[]): SerializedCustomFields => {
16
11
  const customFields = customFieldValues.reduce((acc, cfv) => ({
17
12
  ...acc,
18
- ...(
19
- customFieldDefinitionsHash[cfv.customFieldDefinitionId]
20
- && { [customFieldDefinitionsHash[cfv.customFieldDefinitionId].name]: cfv.value }
21
- ),
13
+ [cfv.customFieldDefinition.name]: cfv.value,
22
14
  }), {});
23
15
  return customFields;
24
16
  };
25
17
  /**
26
18
  * A hook to attach the custom fields when fetching a model instances.
27
19
  */
28
- const enrichResults = (modelType: string, scopeAttributes: string[]) => async (
20
+ const enrichResults = (scopeAttributes: string[]) => async (
29
21
  instancesOrInstance: any | any[],
30
22
  options,
31
23
  ): Promise<void> => {
@@ -41,31 +33,21 @@ const enrichResults = (modelType: string, scopeAttributes: string[]) => async (
41
33
  ? instancesOrInstance
42
34
  : [instancesOrInstance];
43
35
 
44
- instances = instances.filter(Boolean);
36
+ instances = instances.filter((instance) => !!instance);
45
37
 
46
38
  const identifiers = instances.map((instance) =>
47
39
  scopeAttributes
48
40
  .map((attr) => instance[attr])).flat();
49
41
 
50
- const uniqueIdentifiers = [...new Set(identifiers)].filter(Boolean);
51
- const identifierCustomFieldDefinitionsMapping = uniqueIdentifiers.reduce((map, identifier) => ({
52
- ...map,
53
- [identifier]: [],
54
- }), {});
55
- const customFieldDefinitions = await DefinitionRepo.findByEntityIds(
56
- modelType,
57
- uniqueIdentifiers,
58
- { transaction: options.transaction },
59
- );
60
-
61
- const definitionsMap = customFieldDefinitions.reduce((map, definition) => ({
62
- ...map,
63
- [definition.id]: definition,
64
- }), {});
65
-
66
- customFieldDefinitions.forEach((cfd) => {
67
- identifierCustomFieldDefinitionsMapping[cfd.entityId].push(cfd);
68
- });
42
+ const uniqueIdentifiers = [...new Set(identifiers)].filter((identifier) => !!identifier);
43
+ const identifierCustomFieldDefinitionsMapping = {};
44
+ await Promise.all(uniqueIdentifiers.map(async (identifier) => {
45
+ const customFieldDefinitions = await DefinitionRepo.findByEntityId(
46
+ identifier,
47
+ { transaction: options.transaction },
48
+ );
49
+ identifierCustomFieldDefinitionsMapping[identifier] = customFieldDefinitions;
50
+ }));
69
51
 
70
52
  // Get the values per instates ids:
71
53
  const instancesIds = instances.map((i) => i[primaryKey]);
@@ -93,27 +75,22 @@ const enrichResults = (modelType: string, scopeAttributes: string[]) => async (
93
75
  const { id } = instance;
94
76
  const instanceValues = valuesGroupByInstance[id];
95
77
  if (instanceValues) {
96
- const serializedCustomFields = serializeCustomFields(instanceValues, definitionsMap);
78
+ const serializedCustomFields = serializeCustomFields(instanceValues);
97
79
  Object.assign(customFields, serializedCustomFields);
98
80
  }
99
81
 
100
82
  scopeAttributes.forEach((attribute) => {
101
83
  const identifier = instance[attribute];
102
- const entityCustomFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];
103
- if (entityCustomFieldDefinitions?.length > 0) {
104
- entityCustomFieldDefinitions.forEach((customFieldDefinition) => {
84
+ const customFieldDefinitions = identifierCustomFieldDefinitionsMapping[identifier];
85
+ if (customFieldDefinitions?.length > 0) {
86
+ customFieldDefinitions.forEach((customFieldDefinition) => {
105
87
  if (customFields[customFieldDefinition.name] === undefined) {
106
88
  customFields[customFieldDefinition.name] = null;
107
89
  }
108
90
  });
109
91
  }
110
92
  });
111
- if (customFields && Object.keys(customFields).length > 0) {
112
- logger.info('sadot - enrichResults - customFields', customFields);
113
- instance.customFields = customFields;
114
- } else {
115
- logger.info('sadot - enrichResults - no customFields');
116
- }
93
+ instance.customFields = customFields;
117
94
  options.attributesToRemove?.forEach?.((attribute) => {
118
95
  delete instance.dataValues?.[attribute];
119
96
  // if raw:
package/src/hooks/find.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  /* eslint-disable no-param-reassign */
2
- import logger from '../utils/logger';
3
2
 
4
3
  const doScopeAttributesMissing = (
5
4
  scopeAttributes: string[],
@@ -18,7 +17,6 @@ export const beforeFind = (scopeAttributes: string[]) => (options): void => {
18
17
  const { attributes: queryAttributes } = options;
19
18
  if (queryAttributes?.includes('customFields')) {
20
19
  const missingScopeAttributes = doScopeAttributesMissing(scopeAttributes, queryAttributes);
21
- logger.debug('sadot - before find hook');
22
20
  if (missingScopeAttributes?.length > 0) {
23
21
  queryAttributes.push(...missingScopeAttributes);
24
22
  options.attributesToRemove = missingScopeAttributes;
@@ -1,4 +1,3 @@
1
- import logger from '../utils/logger';
2
1
  import * as ValueRepo from '../repository/value';
3
2
 
4
3
  /**
@@ -18,7 +17,6 @@ export const beforeUpdate = (scopeAttributes: string[]) => async (
18
17
  instance,
19
18
  options,
20
19
  ): Promise<void> => {
21
- logger.debug('sadot - before update hook');
22
20
  const { fields } = options;
23
21
  const modelType = instance.constructor.name;
24
22
  const identifiers = scopeAttributes.map((attribute) => instance[attribute]);
package/src/index.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import type { Application } from 'express';
2
2
  import { DataTypes } from 'sequelize';
3
- import { Sequelize } from 'sequelize-typescript';
4
- import { initTables, initTestModels } from './models';
3
+ import { initTables } from './models';
5
4
  import api from './api';
6
5
  import {
7
6
  beforeFind,
@@ -21,13 +20,7 @@ const addHooks = (models: ModelOptions[], getModel: ModelFetcher) => {
21
20
  models.forEach(async ({ name, scopeAttributes }) => {
22
21
  try {
23
22
  const model = getModel(name);
24
- if (!model) {
25
- logger.warn('sadot - tried to addHooks to a model that does not exist yet', {
26
- name,
27
- scopeAttributes,
28
- });
29
- return;
30
- }
23
+ if (!model) return;
31
24
  model.rawAttributes.customFields = {
32
25
  type: DataTypes.VIRTUAL,
33
26
  };
@@ -39,9 +32,8 @@ const addHooks = (models: ModelOptions[], getModel: ModelFetcher) => {
39
32
  model.addHook('beforeBulkUpdate', 'sadot-beforeBulkUpdate', beforeBulkUpdate);
40
33
  model.addHook('beforeCreate', 'sadot-beforeCreate', beforeCreate(scopeAttributes));
41
34
  model.addHook('beforeUpdate', 'sadot-beforeUpdate', beforeUpdate(scopeAttributes));
42
- model.addHook('afterFind', 'sadot-afterFind', enrichResults(name, scopeAttributes));
43
- model.addHook('afterUpdate', 'sadot-afterUpdate', enrichResults(name, scopeAttributes));
44
- model.addHook('afterCreate', 'sadot-afterCreate', enrichResults(name, scopeAttributes));
35
+ model.addHook('afterFind', 'sadot-afterFind', enrichResults(scopeAttributes));
36
+ model.addHook('afterUpdate', 'sadot-afterUpdate', enrichResults(scopeAttributes));
45
37
  } catch (e) {
46
38
  logger.error(`Could not add custom fields hook to model ${name}. `, e);
47
39
  }
@@ -56,19 +48,14 @@ const useCustomFields = async (
56
48
  app: Application | null,
57
49
  getModel: ModelFetcher,
58
50
  options: CustomFieldOptions,
59
- ): Promise<Sequelize> => {
51
+ ): Promise<void> => {
60
52
  const { models } = options;
61
53
  if (app) {
62
54
  app.use('/api', api);
63
55
  }
64
56
  const sequelize = initDB(options.databaseConfig);
65
- if (process.env.NODE_ENV === 'test') {
66
- await initTestModels(sequelize);
67
- }
68
- addHooks(models, getModel);
69
57
  await initTables(sequelize, options.getUser);
70
- logger.debug('sadot - custom fields finished initializing with models', models);
71
- return sequelize;
58
+ addHooks(models, getModel);
72
59
  };
73
60
 
74
61
  export default useCustomFields;
@@ -23,7 +23,7 @@ import { UnsupportedCustomFieldTypeError, UnsupportedCustomValidationError } fro
23
23
  indexes: [
24
24
  {
25
25
  name: 'unique_name_model_type',
26
- fields: ['model_type', 'entity_id', 'name'],
26
+ fields: ['name', 'model_type', 'entity_id'],
27
27
  unique: true,
28
28
  },
29
29
  ],
@@ -1,5 +1,4 @@
1
1
  /* eslint-disable no-param-reassign */
2
- import { DataTypes } from 'sequelize';
3
2
  import type { Sequelize } from 'sequelize-typescript';
4
3
  import logger from '../utils/logger';
5
4
  import CustomFieldDefinition from './CustomFieldDefinition';
@@ -8,11 +7,7 @@ import TestModel from './tests/TestModel';
8
7
  import AssociatedTestModel from './tests/AssociatedTestModel';
9
8
 
10
9
  const productionModels = [CustomFieldDefinition, CustomFieldValue];
11
- const testModels = [TestModel, AssociatedTestModel];
12
-
13
- const SADOT_MIGRATION_PREFIX = 'sadot-migration';
14
- const SCHEMA_VERSION = 1;
15
- const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
10
+ const testModels = [...productionModels, TestModel, AssociatedTestModel];
16
11
 
17
12
  const initTables = async (sequelize: Sequelize, getUser): Promise<void> => {
18
13
  logger.info('custom-fields: initialize custom-fields tables');
@@ -21,7 +16,22 @@ const initTables = async (sequelize: Sequelize, getUser): Promise<void> => {
21
16
  if (!sequelize.addModels) {
22
17
  throw new Error('sequelize instance must have addModels function');
23
18
  }
24
- sequelize.addModels(productionModels);
19
+
20
+ const models = process.env.NODE_ENV === 'test' ? testModels : productionModels;
21
+
22
+ sequelize.addModels(models);
23
+ await sequelize.dropSchema('custom-fields', { logging: false });
24
+ await sequelize.createSchema('custom-fields', { logging: false });
25
+
26
+ logger.info('custom-fields: models added');
27
+ await CustomFieldDefinition.sync({ alter: true });
28
+ await CustomFieldValue.sync({ alter: true });
29
+
30
+ if (process.env.NODE_ENV === 'test') {
31
+ await TestModel.sync({ alter: true });
32
+ await AssociatedTestModel.sync({ alter: true });
33
+ }
34
+ logger.info('custom-fields: models synced');
25
35
 
26
36
  CustomFieldDefinition.addScope('userScope', () => {
27
37
  const user = getUser();
@@ -38,57 +48,6 @@ const initTables = async (sequelize: Sequelize, getUser): Promise<void> => {
38
48
  }
39
49
  return {};
40
50
  });
41
-
42
- logger.info('custom-fields: models added');
43
-
44
- const SequelizeMeta = sequelize.define(
45
- 'SequelizeMeta',
46
- {
47
- name: {
48
- type: DataTypes.STRING,
49
- allowNull: false,
50
- unique: true,
51
- primaryKey: true,
52
- autoIncrement: false,
53
- },
54
- },
55
- {
56
- tableName: 'SequelizeMeta',
57
- timestamps: false,
58
- schema: 'public',
59
- },
60
- );
61
- const migrations = await SequelizeMeta.findAll({ raw: true });
62
- const currentSadotSchemaVersion = migrations
63
- .reverse().find((m: any) => m.name.includes(SADOT_MIGRATION_PREFIX));
64
-
65
- if (
66
- !currentSadotSchemaVersion
67
- || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION
68
- ) {
69
- await CustomFieldDefinition.sync({ alter: true });
70
- await CustomFieldValue.sync({ alter: true });
71
- await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });
72
- logger.info('custom-fields: models synced');
73
- }
74
- };
75
-
76
- const initTestModels = async (sequelize: Sequelize): Promise<void> => {
77
- logger.info('custom-fields: initialize custom-fields test models');
78
- // Detect models and import them to the orm
79
- // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
80
- if (!sequelize.addModels) {
81
- throw new Error('sequelize instance must have addModels function');
82
- }
83
-
84
- sequelize.addModels(testModels);
85
- await sequelize.dropSchema('custom-fields', { logging: false });
86
- await sequelize.createSchema('custom-fields', { logging: false });
87
-
88
- logger.info('custom-fields: test models added');
89
- await TestModel.sync({ alter: true });
90
- await AssociatedTestModel.sync({ alter: true });
91
- logger.info('custom-fields: test models synced');
92
51
  };
93
52
 
94
53
  export {
@@ -97,5 +56,4 @@ export {
97
56
  TestModel,
98
57
  AssociatedTestModel,
99
58
  initTables,
100
- initTestModels,
101
59
  };
@@ -1,5 +1,5 @@
1
1
  import { Op, WhereOptions } from 'sequelize';
2
- import { CustomFieldDefinition } from '../models';
2
+ import { CustomFieldDefinition, CustomFieldValue } from '../models';
3
3
  import type { CreateCustomFieldDefinition, UpdateCustomFieldDefinition } from '../types/definition';
4
4
 
5
5
  export const create = (data: CreateCustomFieldDefinition): Promise<CustomFieldDefinition> =>
@@ -9,14 +9,11 @@ export const findAll = (
9
9
  where: any,
10
10
  options: any = { withDisabled: false },
11
11
  ): Promise<CustomFieldDefinition[]> => {
12
- const queryModel = options.withDisabled
13
- ? CustomFieldDefinition.unscoped()
14
- : CustomFieldDefinition;
15
- return queryModel.scope('userScope').findAll({
16
- where,
17
- transaction: options.transaction,
18
- raw: true,
19
- });
12
+ if (options.withDisabled) {
13
+ return CustomFieldDefinition.unscoped().scope('userScope').findAll({ where });
14
+ }
15
+
16
+ return CustomFieldDefinition.scope('userScope').findAll({ where });
20
17
  };
21
18
 
22
19
  export const findByIds = (
@@ -43,22 +40,10 @@ export const findByEntityId = async (
43
40
  transaction: options.transaction,
44
41
  });
45
42
 
46
- export const findByEntityIds = async (
47
- modelType: string,
48
- entityIds: string[],
49
- options: any = {},
50
- ): Promise<CustomFieldDefinition[]> => CustomFieldDefinition.findAll({
51
- where: {
52
- modelType,
53
- entityId: entityIds,
54
- },
55
- transaction: options.transaction,
56
- raw: true,
57
- });
58
-
59
43
  export const findByWhere = (where): Promise<CustomFieldDefinition | null> =>
60
44
  CustomFieldDefinition.scope('userScope').findOne({
61
45
  where,
46
+ include: [CustomFieldValue],
62
47
  });
63
48
 
64
49
  export const findDefinitionsByModels = async (
@@ -68,6 +53,7 @@ export const findDefinitionsByModels = async (
68
53
  const query: WhereOptions<CreateCustomFieldDefinition> = { modelType: { [Op.in]: modelTypes } };
69
54
  return CustomFieldDefinition.findAll({
70
55
  where: query,
56
+ include: [CustomFieldValue],
71
57
  transaction: options?.transaction,
72
58
  });
73
59
  };
@@ -100,10 +86,27 @@ export const getRequiredFields = async (
100
86
  modelType: string,
101
87
  modelId: string | string[],
102
88
  entityId: string | string[],
89
+ onlyNull = false,
103
90
  ): Promise<string[]> => {
104
91
  const entityIds = Array.isArray(entityId) ? entityId : [entityId];
92
+ const modelIds = Array.isArray(modelId) ? modelId : [modelId];
93
+ // const valueQuery = Object.assign(
94
+ // {
95
+ // modelId: { [Op.in]: modelIds },
96
+ // },
97
+ // onlyNull ? { value: { [Op.eq]: null } } : null,
98
+ // );
99
+ const valueQuery = onlyNull ? {
100
+ modelId: { [Op.in]: modelIds },
101
+ value: { [Op.eq]: null },
102
+ } : {};
105
103
  const requiredFields = await CustomFieldDefinition.findAll({
106
104
  where: { required: true, modelType, entityId: { [Op.in]: entityIds } },
105
+ include: {
106
+ model: CustomFieldValue,
107
+ where: { ...valueQuery },
108
+ required: false,
109
+ },
107
110
  logging: true,
108
111
  });
109
112
  const requiredFieldsNames = requiredFields.map((definition) => definition.name);
@@ -34,9 +34,8 @@ export const findValuesByModelIds = async (modelIds: string[], options?): Promis
34
34
  const { transaction } = options;
35
35
  return CustomFieldValue.findAll({
36
36
  where: { modelId: modelIds },
37
+ include: [CustomFieldDefinition],
37
38
  transaction,
38
- raw: true,
39
- nest: true,
40
39
  });
41
40
  };
42
41
 
@@ -9,7 +9,7 @@ export type ModelOptions = {
9
9
  }
10
10
 
11
11
  export type CustomFieldOptions= {
12
- models: ModelOptions[];
13
- databaseConfig: any;
14
- getUser: () => any;
15
- };
12
+ models: ModelOptions[];
13
+ databaseConfig: any;
14
+ getUser: () => any;
15
+ };
@@ -1,5 +1,4 @@
1
1
  import { Sequelize } from 'sequelize-typescript';
2
- import { QueryTypes } from 'sequelize';
3
2
 
4
3
  export default (databaseConfig: any): Sequelize => {
5
4
  const ENV_DEV = 'test';
@@ -13,9 +12,3 @@ export default (databaseConfig: any): Sequelize => {
13
12
  }
14
13
  return sequelize;
15
14
  };
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 });
@@ -1,6 +1,4 @@
1
1
  // eslint-disable-next-line @typescript-eslint/no-var-requires
2
2
  const Logger = require('@autofleet/logger');
3
3
 
4
- const logger = Logger();
5
-
6
- export default logger;
4
+ export default Logger();
@@ -35,8 +35,7 @@ const validateValueType = (value: unknown, valueType: CustomFieldDefinitionType)
35
35
  case CustomFieldDefinitionType.SELECT:
36
36
  return true; // custom validation
37
37
  case CustomFieldDefinitionType.IMAGE:
38
- return !Joi.array().min(1).unique().items(Joi.string().uri())
39
- .validate(value).error;
38
+ return !Joi.string().uri().validate(value).error;
40
39
  default:
41
40
  return false;
42
41
  }
package/tsconfig.json CHANGED
@@ -1,13 +1,29 @@
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
+ ]
13
29
  }
@@ -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,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,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,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;
@@ -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;