@autofleet/sadot 0.5.4-beta.0 → 0.5.4-beta.11

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.
package/.env ADDED
@@ -0,0 +1,3 @@
1
+ DB_USERNAME=emiltayeb
2
+ DB_PASSWORD=123456
3
+ NODE_ENV=test
@@ -41,6 +41,7 @@ const toPascalCase = (str) => str.replace(/(^\w|-\w)/g, (subStr) => subStr.repla
41
41
  router.post('/', async (req, res) => {
42
42
  const { modelName } = req.params;
43
43
  const modelType = toPascalCase(modelName);
44
+ logger_1.default.info('sadot Creating custom field definition', { modelName });
44
45
  try {
45
46
  const validatedPayload = await (0, validations_1.validateCustomFieldDefinitionCreation)(req.body);
46
47
  const customFieldDefinition = await DefinitionRepo.create({
@@ -83,7 +84,9 @@ router.get('/', async (req, res) => {
83
84
  if (entityIds?.length > 0) {
84
85
  where.entityId = entityIds;
85
86
  }
86
- const customFieldDefinitions = await DefinitionRepo.findAll({ ...where }, { withDisabled: true });
87
+ logger_1.default.info('sadot Fetching custom field definitions', { modelType, entityIds, where });
88
+ const customFieldDefinitions = await DefinitionRepo.findAll(where, { withDisabled: true });
89
+ logger_1.default.info('sadot Fetched custom field definitions customFieldDefinitions', { customFieldDefinitions });
87
90
  return res.json(customFieldDefinitions);
88
91
  }
89
92
  catch (err) {
package/dist/index.d.ts CHANGED
@@ -10,4 +10,3 @@ export * from './utils/constants';
10
10
  declare const useCustomFields: (app: Application | null, getModel: ModelFetcher, options: CustomFieldOptions) => Promise<Sequelize>;
11
11
  export default useCustomFields;
12
12
  export declare const disableCustomFields: (models: any, getModel: any) => void;
13
- export declare const getCustomFieldsSearchLiteral: (modelName: string, searchTerm: string) => string;
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.getCustomFieldsSearchLiteral = exports.disableCustomFields = void 0;
20
+ exports.disableCustomFields = void 0;
21
21
  const models_1 = require("./models");
22
22
  const api_1 = __importDefault(require("./api"));
23
23
  const db_1 = __importDefault(require("./utils/db"));
@@ -32,7 +32,7 @@ __exportStar(require("./utils/constants"), exports);
32
32
  const useCustomFields = async (app, getModel, options) => {
33
33
  const { models } = options;
34
34
  if (app) {
35
- app.use('/api', api_1.default);
35
+ app.use('/api', options.middleware, api_1.default);
36
36
  }
37
37
  const sequelize = (0, db_1.default)(options.databaseConfig);
38
38
  if (process.env.NODE_ENV === 'test') {
@@ -40,7 +40,7 @@ const useCustomFields = async (app, getModel, options) => {
40
40
  }
41
41
  // The order is important
42
42
  (0, init_1.addHooks)(models, getModel);
43
- await (0, models_1.initTables)(sequelize, options.getUser);
43
+ await (0, models_1.initTables)(sequelize, options.getUser, options.enrichUserPermissions);
44
44
  (0, init_1.addScopes)(models, getModel);
45
45
  logger_1.default.debug('sadot - custom fields finished initializing with models', models);
46
46
  return sequelize;
@@ -50,5 +50,3 @@ const disableCustomFields = (models, getModel) => {
50
50
  (0, init_1.removeHooks)(models, getModel);
51
51
  };
52
52
  exports.disableCustomFields = disableCustomFields;
53
- const getCustomFieldsSearchLiteral = (modelName, searchTerm) => `EXISTS (SELECT 1 FROM "custom_field_values" AS "cv" WHERE "cv"."deleted_at" IS NULL AND "cv"."model_id" = "${modelName}"."id" AND CAST("cv"."value" AS TEXT) ILIKE '%${searchTerm}%')`;
54
- exports.getCustomFieldsSearchLiteral = getCustomFieldsSearchLiteral;
@@ -3,6 +3,6 @@ import CustomFieldDefinition from './CustomFieldDefinition';
3
3
  import CustomFieldValue from './CustomFieldValue';
4
4
  import TestModel from './tests/TestModel';
5
5
  import AssociatedTestModel from './tests/AssociatedTestModel';
6
- declare const initTables: (sequelize: Sequelize, getUser: any) => Promise<void>;
6
+ declare const initTables: (sequelize: Sequelize, getUser: any, enrichUserPermissions: any) => Promise<void>;
7
7
  declare const initTestModels: (sequelize: Sequelize) => Promise<void>;
8
8
  export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, initTables, initTestModels, };
@@ -20,7 +20,7 @@ const testModels = [TestModel_1.default, AssociatedTestModel_1.default];
20
20
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
21
21
  const SCHEMA_VERSION = 1;
22
22
  const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
23
- const initTables = async (sequelize, getUser) => {
23
+ const initTables = async (sequelize, getUser, enrichUserPermissions) => {
24
24
  logger_1.default.info('custom-fields: initialize custom-fields tables');
25
25
  // Detect models and import them to the orm
26
26
  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -28,16 +28,20 @@ const initTables = async (sequelize, getUser) => {
28
28
  throw new Error('sequelize instance must have addModels function');
29
29
  }
30
30
  sequelize.addModels(productionModels);
31
- CustomFieldDefinition_1.default.addScope('userScope', () => {
31
+ CustomFieldDefinition_1.default.addScope('userScope', (entityIds) => {
32
32
  const user = getUser();
33
+ logger_1.default.info('custom fields scope added', { entityIds });
33
34
  if (user?.permissions) {
35
+ const entityId = [
36
+ ...Object.keys(user.permissions.fleets),
37
+ ...Object.keys(user.permissions.businessModels),
38
+ ...Object.keys(user.permissions.demandSources),
39
+ ...enrichUserPermissions(entityIds),
40
+ ];
41
+ logger_1.default.info('custom fields scope added updated entity:', { entityId });
34
42
  return {
35
43
  where: {
36
- entityId: [
37
- ...Object.keys(user.permissions.fleets),
38
- ...Object.keys(user.permissions.businessModels),
39
- ...Object.keys(user.permissions.demandSources),
40
- ],
44
+ entityId,
41
45
  },
42
46
  };
43
47
  }
@@ -9,10 +9,11 @@ const findAll = (where, options = { withDisabled: false }) => {
9
9
  const queryModel = options.withDisabled
10
10
  ? models_1.CustomFieldDefinition.unscoped()
11
11
  : models_1.CustomFieldDefinition;
12
- return queryModel.scope('userScope').findAll({
12
+ return queryModel.scope({ method: ['userScope', where] }).findAll({
13
13
  where,
14
14
  transaction: options.transaction,
15
15
  raw: true,
16
+ logging: console.log,
16
17
  });
17
18
  };
18
19
  exports.findAll = findAll;
@@ -1,3 +1,4 @@
1
+ import { RequestHandler } from 'express';
1
2
  export type ModelFetcher = (name: string) => any;
2
3
  export type ModelOptions = {
3
4
  name: string;
@@ -10,4 +11,6 @@ export type CustomFieldOptions = {
10
11
  models: ModelOptions[];
11
12
  databaseConfig: any;
12
13
  getUser: () => any;
14
+ enrichUserPermissions?: (entityIds: string[]) => any;
15
+ middleware?: RequestHandler;
13
16
  };
@@ -10,7 +10,6 @@ const models_1 = require("../models");
10
10
  const hooks_1 = require("../hooks");
11
11
  const scopes_1 = require("../scopes");
12
12
  const logger_1 = __importDefault(require("./logger"));
13
- const include_1 = require("../scopes/include");
14
13
  const { CUSTOM_FIELDS_FILTER_SCOPE } = common_types_1.customFields;
15
14
  const addHooks = (models, getModel) => {
16
15
  models.forEach(async ({ name, scopeAttributes }) => {
@@ -88,11 +87,11 @@ const addScopes = (models, getModel) => {
88
87
  });
89
88
  return;
90
89
  }
90
+ logger_1.default.info(`addScopes ${name}`, { name, scopeAttributes });
91
91
  // Necessary associations for the filtering scope
92
92
  addAssociations(model, name);
93
93
  // Add filter scope
94
94
  model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, (0, scopes_1.customFieldsFilterScope)(name));
95
- model.addScope('searchByCustomFields', (0, include_1.customFieldsSearchScope)(name));
96
95
  }
97
96
  catch (e) {
98
97
  logger_1.default.error(`Could not add custom fields scopes to model ${name}. `, e);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@autofleet/sadot",
3
- "version": "0.5.4-beta.0",
3
+ "version": "0.5.4-beta.11",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -9,7 +9,24 @@
9
9
  "linter": "./node_modules/.bin/eslint .",
10
10
  "test": "jest --forceExit --runInBand",
11
11
  "coverage": "jest --coverage --forceExit --runInBand && rm -rf ./coverage",
12
- "dev": "nodemon"
12
+ "build-to-local-repo": "npm run build && cp -r dist/* ../$REPO/node_modules/$npm_package_name/dist",
13
+ "dev": "nodemon",
14
+ "watch": "npm-watch build-to-local-repo"
15
+ },
16
+ "watch": {
17
+ "build-to-local-repo": {
18
+ "extensions": [
19
+ "js",
20
+ "jsx",
21
+ "ts",
22
+ "tsx",
23
+ "css"
24
+ ],
25
+ "patterns": [
26
+ "src"
27
+ ],
28
+ "quiet": false
29
+ }
13
30
  },
14
31
  "dependencies": {
15
32
  "@autofleet/common-types": "^1.7.29",
@@ -18,6 +35,7 @@
18
35
  "@autofleet/logger": "^2.0.5",
19
36
  "express": "^4.18.2",
20
37
  "joi": "^17.7.0",
38
+ "npm-watch": "^0.11.0",
21
39
  "pg": "^8.10.0",
22
40
  "reflect-metadata": "^0.1.13",
23
41
  "sequelize": "^6.31.1",
@@ -18,6 +18,7 @@ const toPascalCase = (str: string): string => str.replace(/(^\w|-\w)/g, (subStr)
18
18
  router.post('/', async (req: Request, res: Response) => {
19
19
  const { modelName } = req.params as any;
20
20
  const modelType = toPascalCase(modelName);
21
+ logger.info('sadot Creating custom field definition', { modelName });
21
22
  try {
22
23
  const validatedPayload: CreateCustomFieldDefinition = await
23
24
  validateCustomFieldDefinitionCreation(req.body);
@@ -58,17 +59,17 @@ router.get('/:customFieldDefinitionId', async (req, res) => {
58
59
  router.get('/', async (req, res) => {
59
60
  const { modelName } = req.params as any;
60
61
  const { entityIds } = req.query as any;
61
-
62
62
  const modelType = toPascalCase(modelName);
63
63
  try {
64
64
  const where: any = { modelType };
65
65
  if (entityIds?.length > 0) {
66
66
  where.entityId = entityIds;
67
67
  }
68
- const customFieldDefinitions = await DefinitionRepo.findAll(
69
- { ...where },
70
- { withDisabled: true },
71
- );
68
+
69
+ logger.info('sadot Fetching custom field definitions', { modelType, entityIds, where });
70
+ const customFieldDefinitions = await DefinitionRepo.findAll(where,
71
+ { withDisabled: true });
72
+ logger.info('sadot Fetched custom field definitions customFieldDefinitions', { customFieldDefinitions });
72
73
  return res.json(customFieldDefinitions);
73
74
  } catch (err) {
74
75
  logger.error('Failed to fetch custom field definitions', err);
package/src/index.ts CHANGED
@@ -24,7 +24,7 @@ const useCustomFields = async (
24
24
  ): Promise<Sequelize> => {
25
25
  const { models } = options;
26
26
  if (app) {
27
- app.use('/api', api);
27
+ app.use('/api', options.middleware, api);
28
28
  }
29
29
  const sequelize = initDB(options.databaseConfig);
30
30
  if (process.env.NODE_ENV === 'test') {
@@ -32,7 +32,7 @@ const useCustomFields = async (
32
32
  }
33
33
  // The order is important
34
34
  addHooks(models, getModel);
35
- await initTables(sequelize, options.getUser);
35
+ await initTables(sequelize, options.getUser, options.enrichUserPermissions);
36
36
  addScopes(models, getModel);
37
37
  logger.debug('sadot - custom fields finished initializing with models', models);
38
38
  return sequelize;
@@ -43,8 +43,3 @@ export default useCustomFields;
43
43
  export const disableCustomFields = (models, getModel): void => {
44
44
  removeHooks(models, getModel);
45
45
  };
46
-
47
- export const getCustomFieldsSearchLiteral = (
48
- modelName: string,
49
- searchTerm: string,
50
- ) : string => `EXISTS (SELECT 1 FROM "custom_field_values" AS "cv" WHERE "cv"."deleted_at" IS NULL AND "cv"."model_id" = "${modelName}"."id" AND CAST("cv"."value" AS TEXT) ILIKE '%${searchTerm}%')`;
@@ -14,7 +14,7 @@ const SADOT_MIGRATION_PREFIX = 'sadot-migration';
14
14
  const SCHEMA_VERSION = 1;
15
15
  const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
16
16
 
17
- const initTables = async (sequelize: Sequelize, getUser): Promise<void> => {
17
+ const initTables = async (sequelize: Sequelize, getUser, enrichUserPermissions): Promise<void> => {
18
18
  logger.info('custom-fields: initialize custom-fields tables');
19
19
  // Detect models and import them to the orm
20
20
  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -23,16 +23,20 @@ const initTables = async (sequelize: Sequelize, getUser): Promise<void> => {
23
23
  }
24
24
  sequelize.addModels(productionModels);
25
25
 
26
- CustomFieldDefinition.addScope('userScope', () => {
26
+ CustomFieldDefinition.addScope('userScope', (entityIds) => {
27
27
  const user = getUser();
28
+ logger.info('custom fields scope added', { entityIds });
28
29
  if (user?.permissions) {
30
+ const entityId = [
31
+ ...Object.keys(user.permissions.fleets),
32
+ ...Object.keys(user.permissions.businessModels),
33
+ ...Object.keys(user.permissions.demandSources),
34
+ ...enrichUserPermissions(entityIds),
35
+ ];
36
+ logger.info('custom fields scope added updated entity:', { entityId });
29
37
  return {
30
38
  where: {
31
- entityId: [
32
- ...Object.keys(user.permissions.fleets),
33
- ...Object.keys(user.permissions.businessModels),
34
- ...Object.keys(user.permissions.demandSources),
35
- ],
39
+ entityId,
36
40
  },
37
41
  };
38
42
  }
@@ -12,10 +12,11 @@ export const findAll = (
12
12
  const queryModel = options.withDisabled
13
13
  ? CustomFieldDefinition.unscoped()
14
14
  : CustomFieldDefinition;
15
- return queryModel.scope('userScope').findAll({
15
+ return queryModel.scope({ method: ['userScope', where] }).findAll({
16
16
  where,
17
17
  transaction: options.transaction,
18
18
  raw: true,
19
+ logging: console.log,
19
20
  });
20
21
  };
21
22
 
@@ -1,3 +1,5 @@
1
+ import { RequestHandler } from 'express';
2
+
1
3
  export type ModelFetcher = (name: string) => any;
2
4
 
3
5
  export type ModelOptions = {
@@ -8,8 +10,10 @@ export type ModelOptions = {
8
10
  deletionWebhookHandler?: (instance: any) => any;
9
11
  }
10
12
 
11
- export type CustomFieldOptions= {
13
+ export type CustomFieldOptions = {
12
14
  models: ModelOptions[];
13
15
  databaseConfig: any;
14
16
  getUser: () => any;
17
+ enrichUserPermissions?: (entityIds: string[]) => any;
18
+ middleware?: RequestHandler;
15
19
  };
package/src/utils/init.ts CHANGED
@@ -15,7 +15,6 @@ import {
15
15
  import { customFieldsFilterScope } from '../scopes';
16
16
  import logger from './logger';
17
17
  import type { ModelFetcher, ModelOptions } from '../types';
18
- import { customFieldsSearchScope } from '../scopes/include';
19
18
 
20
19
  const { CUSTOM_FIELDS_FILTER_SCOPE } = customFields;
21
20
 
@@ -93,11 +92,11 @@ export const addScopes = (models: ModelOptions[], getModel: ModelFetcher): void
93
92
  });
94
93
  return;
95
94
  }
95
+ logger.info(`addScopes ${name}`, { name, scopeAttributes });
96
96
  // Necessary associations for the filtering scope
97
97
  addAssociations(model, name);
98
98
  // Add filter scope
99
99
  model.addScope(CUSTOM_FIELDS_FILTER_SCOPE, customFieldsFilterScope(name));
100
- model.addScope('searchByCustomFields', customFieldsSearchScope(name));
101
100
  } catch (e) {
102
101
  logger.error(`Could not add custom fields scopes to model ${name}. `, e);
103
102
  }
@@ -1,9 +0,0 @@
1
- import { WhereOptions } from 'sequelize';
2
- export type CustomFieldSearchOptions = {
3
- where?: WhereOptions;
4
- };
5
- export declare const customFieldsSearchScope: (name: string) => ({ searchTerm, queryWithSearchTerm }: {
6
- searchTerm: any;
7
- queryWithSearchTerm: any;
8
- }) => CustomFieldSearchOptions;
9
- export declare const scopeName = "searchByCustomFields";
@@ -1,22 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.scopeName = exports.customFieldsSearchScope = void 0;
4
- const sequelize_typescript_1 = require("sequelize-typescript");
5
- const customFieldsSearchScope = (name) => ({ searchTerm, queryWithSearchTerm }) => {
6
- const subQuery = `${'EXISTS (SELECT 1 '
7
- + 'FROM "custom_field_values" AS "cv" '
8
- + 'WHERE '
9
- + '"cv"."deleted_at" IS NULL AND '
10
- + `"cv"."model_id" = "${name}"."id" AND `
11
- + `CAST("cv"."value" AS TEXT) ILIKE '%${searchTerm}%')`}`;
12
- return {
13
- where: {
14
- $or: [
15
- sequelize_typescript_1.Sequelize.literal(`(${subQuery})`),
16
- ...queryWithSearchTerm.$and[0].$or,
17
- ],
18
- },
19
- };
20
- };
21
- exports.customFieldsSearchScope = customFieldsSearchScope;
22
- exports.scopeName = 'searchByCustomFields';
@@ -1,30 +0,0 @@
1
- /* eslint-disable import/prefer-default-export */
2
- import { WhereOptions } from 'sequelize';
3
- import { Sequelize } from 'sequelize-typescript';
4
-
5
- export type CustomFieldSearchOptions = {
6
- where?: WhereOptions;
7
- }
8
-
9
- export const customFieldsSearchScope = (
10
- name: string,
11
- ) => ({ searchTerm, queryWithSearchTerm }) : CustomFieldSearchOptions => {
12
- const subQuery = `${
13
- 'EXISTS (SELECT 1 '
14
- + 'FROM "custom_field_values" AS "cv" '
15
- + 'WHERE '
16
- + '"cv"."deleted_at" IS NULL AND '
17
- + `"cv"."model_id" = "${name}"."id" AND `
18
- + `CAST("cv"."value" AS TEXT) ILIKE '%${searchTerm}%')`}`;
19
-
20
- return {
21
- where: {
22
- $or: [
23
- Sequelize.literal(`(${subQuery})`),
24
- ...queryWithSearchTerm.$and[0].$or,
25
- ],
26
- },
27
- };
28
- };
29
-
30
- export const scopeName = 'searchByCustomFields';