@autofleet/sadot 0.8.3 → 0.8.5

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/dist/index.js CHANGED
@@ -35,7 +35,7 @@ const useCustomFields = async (app, getModel, options) => {
35
35
  if (app) {
36
36
  app.use('/api', api_1.default);
37
37
  }
38
- const sequelize = (0, db_1.default)(options.databaseConfig);
38
+ const sequelize = options.sequelize ?? (0, db_1.default)(options.databaseConfig);
39
39
  if (process.env.NODE_ENV === 'test') {
40
40
  await (0, models_1.initTestModels)(sequelize);
41
41
  }
@@ -6,6 +6,9 @@ import ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestMo
6
6
  import ContextTestModel from './tests/contextAwareModels/ContextTestModel';
7
7
  import AssociatedTestModel from './tests/AssociatedTestModel';
8
8
  import type { CustomFieldOptions } from '../types';
9
- declare const initTables: (sequelize: Sequelize, getUser: CustomFieldOptions['getUser']) => Promise<void>;
9
+ declare const initTables: (sequelize: Sequelize, getUser: CustomFieldOptions['getUser'], { schemaPrefix, schemaVersion }?: {
10
+ schemaPrefix: string;
11
+ schemaVersion: string;
12
+ }) => Promise<void>;
10
13
  declare const initTestModels: (sequelize: Sequelize) => Promise<void>;
11
14
  export { CustomFieldValue, CustomFieldDefinition, TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel, initTables, initTestModels, };
@@ -23,8 +23,8 @@ const productionModels = [CustomFieldDefinition_1.default, CustomFieldValue_1.de
23
23
  const testModels = [TestModel_1.default, AssociatedTestModel_1.default, ContextAwareTestModel_1.default, ContextTestModel_1.default];
24
24
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
25
25
  const SCHEMA_VERSION = 'fb0fa867-1241-4816-b08d-5ed9060c7ae5';
26
- const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
27
- const initTables = async (sequelize, getUser) => {
26
+ const initTables = async (sequelize, getUser, { schemaPrefix, schemaVersion } = { schemaPrefix: SADOT_MIGRATION_PREFIX, schemaVersion: SCHEMA_VERSION }) => {
27
+ const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}`;
28
28
  logger_1.default.info('custom-fields: initialize custom-fields tables');
29
29
  // Detect models and import them to the orm
30
30
  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -61,14 +61,22 @@ const initTables = async (sequelize, getUser) => {
61
61
  timestamps: false,
62
62
  schema: 'public',
63
63
  });
64
- const migrations = await SequelizeMeta.findAll({ raw: true });
65
- const currentSadotSchemaVersion = migrations.reverse().find((m) => m.name.includes(SADOT_MIGRATION_PREFIX));
66
- if (!currentSadotSchemaVersion
67
- || currentSadotSchemaVersion.name !== CUSTOM_FIELDS_SCHEMA_VERSION) {
64
+ const migrations = await SequelizeMeta.findAll({ where: { name: { [sequelize_1.Op.like]: `${schemaPrefix}%` } }, raw: true });
65
+ const currentSadotSchemaVersion = migrations.at(-1);
66
+ const expectedSchemaVersionIndex = migrations.findIndex((m) => m.name === CUSTOM_FIELDS_SCHEMA_VERSION);
67
+ if (!currentSadotSchemaVersion || currentSadotSchemaVersion.name !== CUSTOM_FIELDS_SCHEMA_VERSION) {
68
68
  await CustomFieldDefinition_1.default.sync({ alter: true });
69
69
  await CustomFieldValue_1.default.sync({ alter: true });
70
- await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });
70
+ if (expectedSchemaVersionIndex === -1) {
71
+ await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });
72
+ }
71
73
  logger_1.default.info('custom-fields: models synced');
74
+ if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {
75
+ // We have existing migrations, and we are calling `sync`.
76
+ // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.
77
+ const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);
78
+ await SequelizeMeta.destroy({ where: { name: { [sequelize_1.Op.in]: migrationsToDelete.map((m) => m.name) } } });
79
+ }
72
80
  }
73
81
  };
74
82
  exports.initTables = initTables;
@@ -0,0 +1,3 @@
1
+ import type { Application } from 'express';
2
+ import type { Models } from '../../types';
3
+ export declare function commonTestHooks(app?: Application | null, models?: Models[]): void;
@@ -0,0 +1,54 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.commonTestHooks = void 0;
30
+ const __1 = __importDefault(require("../.."));
31
+ const _1 = require(".");
32
+ const database_config_1 = __importDefault(require("./database-config"));
33
+ const db_1 = __importStar(require("../../utils/db"));
34
+ function commonTestHooks(app = null, models = [{ name: 'TestModel', scopeAttributes: ['fleetId'] }]) {
35
+ let sequelize;
36
+ beforeAll(async () => {
37
+ sequelize = (0, db_1.default)(database_config_1.default);
38
+ await (0, db_1.createSequelizeMeta)(sequelize);
39
+ await (0, __1.default)(app, _1.getModel, {
40
+ models,
41
+ databaseConfig: database_config_1.default,
42
+ getUser: () => undefined,
43
+ sequelize,
44
+ });
45
+ });
46
+ afterEach(async () => {
47
+ jest.clearAllMocks();
48
+ await (0, _1.cleanup)();
49
+ });
50
+ afterAll(async () => {
51
+ await sequelize.close();
52
+ });
53
+ }
54
+ exports.commonTestHooks = commonTestHooks;
@@ -1,5 +1,5 @@
1
1
  import type { IncludeOptions } from 'sequelize';
2
- import type { ModelCtor } from 'sequelize-typescript';
2
+ import type { ModelCtor, Sequelize } from 'sequelize-typescript';
3
3
  import type { getUser as GetUserType } from '@autofleet/zehut';
4
4
  export type ModelFetcher = (name: string) => any;
5
5
  export type ModelOptions = {
@@ -29,4 +29,5 @@ export type CustomFieldOptions = {
29
29
  models: Models[];
30
30
  databaseConfig: any;
31
31
  getUser: typeof GetUserType;
32
+ sequelize?: Sequelize;
32
33
  };
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@autofleet/sadot",
3
- "version": "0.8.3",
3
+ "version": "0.8.5",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
7
7
  "start": "ts-node src/index.ts",
8
8
  "build": "rm -rf dist && tsc",
9
9
  "linter": "eslint .",
10
- "test": "jest --forceExit --runInBand",
11
- "coverage": "jest --coverage --forceExit --runInBand && rm -rf ./coverage",
10
+ "test": "jest --runInBand",
11
+ "coverage": "jest --coverage --runInBand && rm -rf ./coverage",
12
12
  "build-to-local-repo": "node --run build && cp -r dist/* ../$REPO/node_modules/$npm_package_name/dist",
13
13
  "dev": "nodemon",
14
14
  "watch": "npm-watch build-to-local-repo",
package/src/index.ts CHANGED
@@ -30,7 +30,7 @@ const useCustomFields = async (
30
30
  if (app) {
31
31
  app.use('/api', api);
32
32
  }
33
- const sequelize = initDB(options.databaseConfig);
33
+ const sequelize = options.sequelize ?? initDB(options.databaseConfig);
34
34
  if (process.env.NODE_ENV === 'test') {
35
35
  await initTestModels(sequelize);
36
36
  }
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable no-param-reassign */
2
- import { DataTypes } from 'sequelize';
2
+ import { DataTypes, Op } from 'sequelize';
3
3
  import type { Sequelize } from 'sequelize-typescript';
4
4
  import logger from '../utils/logger';
5
5
  import CustomFieldDefinition from './CustomFieldDefinition';
@@ -15,9 +15,13 @@ const testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, Conte
15
15
 
16
16
  const SADOT_MIGRATION_PREFIX = 'sadot-migration';
17
17
  const SCHEMA_VERSION = 'fb0fa867-1241-4816-b08d-5ed9060c7ae5';
18
- const CUSTOM_FIELDS_SCHEMA_VERSION = `${SADOT_MIGRATION_PREFIX}_${SCHEMA_VERSION}`;
19
18
 
20
- const initTables = async (sequelize: Sequelize, getUser: CustomFieldOptions['getUser']): Promise<void> => {
19
+ const initTables = async (
20
+ sequelize: Sequelize,
21
+ getUser: CustomFieldOptions['getUser'],
22
+ { schemaPrefix, schemaVersion } = { schemaPrefix: SADOT_MIGRATION_PREFIX, schemaVersion: SCHEMA_VERSION },
23
+ ): Promise<void> => {
24
+ const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}`;
21
25
  logger.info('custom-fields: initialize custom-fields tables');
22
26
  // Detect models and import them to the orm
23
27
  // eslint-disable-next-line @typescript-eslint/explicit-function-return-type
@@ -61,17 +65,24 @@ const initTables = async (sequelize: Sequelize, getUser: CustomFieldOptions['get
61
65
  schema: 'public',
62
66
  },
63
67
  );
64
- const migrations = await SequelizeMeta.findAll({ raw: true });
65
- const currentSadotSchemaVersion = migrations.reverse().find((m: any) => m.name.includes(SADOT_MIGRATION_PREFIX));
66
68
 
67
- if (
68
- !currentSadotSchemaVersion
69
- || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION
70
- ) {
69
+ const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });
70
+ const currentSadotSchemaVersion = migrations.at(-1);
71
+ const expectedSchemaVersionIndex = migrations.findIndex((m) => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);
72
+
73
+ if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {
71
74
  await CustomFieldDefinition.sync({ alter: true });
72
75
  await CustomFieldValue.sync({ alter: true });
73
- await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });
76
+ if (expectedSchemaVersionIndex === -1) {
77
+ await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });
78
+ }
74
79
  logger.info('custom-fields: models synced');
80
+ if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {
81
+ // We have existing migrations, and we are calling `sync`.
82
+ // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.
83
+ const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);
84
+ await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map((m) => (m as any).name) } } });
85
+ }
75
86
  }
76
87
  };
77
88
 
@@ -0,0 +1,31 @@
1
+ import type { Application } from 'express';
2
+ import type { Sequelize } from 'sequelize-typescript';
3
+ import useCustomFields from '../..';
4
+ import { cleanup, getModel } from '.';
5
+ import databaseConfig from './database-config';
6
+ import initDB, { createSequelizeMeta } from '../../utils/db';
7
+ import type { Models } from '../../types';
8
+
9
+ export function commonTestHooks(app: Application | null = null, models: Models[] = [{ name: 'TestModel', scopeAttributes: ['fleetId'] }]) {
10
+ let sequelize: Sequelize;
11
+
12
+ beforeAll(async () => {
13
+ sequelize = initDB(databaseConfig);
14
+ await createSequelizeMeta(sequelize);
15
+ await useCustomFields(app, getModel, {
16
+ models,
17
+ databaseConfig,
18
+ getUser: () => undefined,
19
+ sequelize,
20
+ });
21
+ });
22
+
23
+ afterEach(async () => {
24
+ jest.clearAllMocks();
25
+ await cleanup();
26
+ });
27
+
28
+ afterAll(async () => {
29
+ await sequelize.close();
30
+ });
31
+ }
@@ -1,5 +1,5 @@
1
1
  import type { IncludeOptions } from 'sequelize';
2
- import type { ModelCtor } from 'sequelize-typescript';
2
+ import type { ModelCtor, Sequelize } from 'sequelize-typescript';
3
3
  import type { getUser as GetUserType } from '@autofleet/zehut';
4
4
 
5
5
  export type ModelFetcher = (name: string) => any;
@@ -33,4 +33,5 @@ export type CustomFieldOptions = {
33
33
  models: Models[];
34
34
  databaseConfig: any;
35
35
  getUser: typeof GetUserType;
36
+ sequelize?: Sequelize;
36
37
  };