@orion-js/migrations 4.3.3 → 4.3.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Orionjs Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs CHANGED
@@ -117,42 +117,13 @@ __runInitializers(_init, 1, MigrationsRepo);
117
117
 
118
118
  // src/loadMigrations/index.ts
119
119
  var import_dogs = require("@orion-js/dogs");
120
-
121
- // src/service/index.ts
122
- var import_services2 = require("@orion-js/services");
123
- var import_services3 = require("@orion-js/services");
124
- var serviceMetadata = /* @__PURE__ */ new WeakMap();
125
- function MigrationService(options) {
126
- return (target, context) => {
127
- (0, import_services3.Service)()(target, context);
128
- serviceMetadata.set(target, { _serviceType: "migrations", options });
129
- };
130
- }
131
- function getMigrationsFromServices(services) {
132
- return services.map((service) => {
133
- const instance = (0, import_services2.getInstance)(service);
134
- const options = serviceMetadata.get(instance.constructor);
135
- if (!options._serviceType || options._serviceType !== "migrations") {
136
- throw new Error(`Service ${service.name} is not a migration service`);
137
- }
138
- return {
139
- ...options.options,
140
- runMigration: async (context) => {
141
- const instance2 = (0, import_services2.getInstance)(service);
142
- return await instance2.runMigration(context);
143
- }
144
- };
145
- });
146
- }
147
-
148
- // src/loadMigrations/index.ts
149
120
  var import_services5 = require("@orion-js/services");
150
121
 
151
122
  // src/MigrationsService.ts
152
- var import_services4 = require("@orion-js/services");
123
+ var import_services2 = require("@orion-js/services");
153
124
  var import_logger = require("@orion-js/logger");
154
125
  var _migrationsRepo_dec, _MigrationsService_decorators, _init2;
155
- _MigrationsService_decorators = [(0, import_services4.Service)()], _migrationsRepo_dec = [(0, import_services4.Inject)(() => MigrationsRepo)];
126
+ _MigrationsService_decorators = [(0, import_services2.Service)()], _migrationsRepo_dec = [(0, import_services2.Inject)(() => MigrationsRepo)];
156
127
  var MigrationsService = class {
157
128
  constructor() {
158
129
  __publicField(this, "migrationsRepo", __runInitializers(_init2, 8, this)), __runInitializers(_init2, 11, this);
@@ -206,16 +177,38 @@ __decorateElement(_init2, 5, "migrationsRepo", _migrationsRepo_dec, MigrationsSe
206
177
  MigrationsService = __decorateElement(_init2, 0, "MigrationsService", _MigrationsService_decorators, MigrationsService);
207
178
  __runInitializers(_init2, 1, MigrationsService);
208
179
 
180
+ // src/service/index.ts
181
+ var import_services3 = require("@orion-js/services");
182
+ var import_services4 = require("@orion-js/services");
183
+ var serviceMetadata = /* @__PURE__ */ new WeakMap();
184
+ function MigrationService(options) {
185
+ return (target, context) => {
186
+ (0, import_services4.Service)()(target, context);
187
+ serviceMetadata.set(target, { _serviceType: "migrations", options });
188
+ };
189
+ }
190
+ function getMigrationsFromServices(services) {
191
+ return services.map((service) => {
192
+ const instance = (0, import_services3.getInstance)(service);
193
+ const options = serviceMetadata.get(instance.constructor);
194
+ if (!options._serviceType || options._serviceType !== "migrations") {
195
+ throw new Error(`Service ${service.name} is not a migration service`);
196
+ }
197
+ return {
198
+ ...options.options,
199
+ runMigration: async (context) => {
200
+ const instance2 = (0, import_services3.getInstance)(service);
201
+ return await instance2.runMigration(context);
202
+ }
203
+ };
204
+ });
205
+ }
206
+
209
207
  // src/loadMigrations/index.ts
210
- var import_logger2 = require("@orion-js/logger");
211
208
  function loadMigrations(migrationServices, options) {
212
209
  const migrations = getMigrationsFromServices(migrationServices);
213
210
  if (options == null ? void 0 : options.omitJob) return migrations;
214
211
  (0, import_dogs.startWorkers)({
215
- maxTries: 5,
216
- onMaxTriesReached: async (job) => {
217
- import_logger2.logger.error(`Max tries reached for job ${job.name}`, { job });
218
- },
219
212
  cooldownPeriod: 1e3,
220
213
  defaultLockTime: 1e3 * 60 * 20,
221
214
  // 20 min
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/service/index.ts","../src/MigrationsService.ts"],"sourcesContent":["export * from './Schema'\nexport * from './Repo'\nexport * from './loadMigrations'\nexport * from './service'\nexport * from './MigrationsService'\n","import {TypedId, typedId} from '@orion-js/mongodb'\nimport {InferSchemaType, schemaWithName} from '@orion-js/schema'\n\nexport type MigrationId = TypedId<'scnmg'>\n\nexport const MigrationSchema = schemaWithName('Migration', {\n _id: {\n type: typedId('scnmg'),\n },\n name: {\n type: String,\n },\n completedAt: {\n type: Date,\n },\n})\n\nexport type MigrationType = InferSchemaType<typeof MigrationSchema>\n","import {createCollection} from '@orion-js/mongodb'\nimport {MigrationSchema} from './Schema'\nimport {Service} from '@orion-js/services'\n\n@Service()\nexport class MigrationsRepo {\n public collection = createCollection({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n indexes: [],\n })\n\n async getCompletedMigrationNames() {\n const migrations = await this.collection.find().toArray()\n return migrations.map(m => m.name)\n }\n\n async saveCompletedMigration(name: string) {\n await this.collection.insertOne({\n name,\n completedAt: new Date(),\n })\n }\n}\n","import {defineJob, JobToRun, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\nimport {logger} from '@orion-js/logger'\n\nexport interface Options {\n lockTime?: number\n omitJob?: boolean\n}\n\nexport function loadMigrations(migrationServices: any[], options?: Options) {\n const migrations = getMigrationsFromServices(migrationServices)\n if (options?.omitJob) return migrations\n\n startWorkers({\n maxTries: 5,\n onMaxTriesReached: async (job: JobToRun) => {\n logger.error(`Max tries reached for job ${job.name}`, {job})\n },\n cooldownPeriod: 1000,\n defaultLockTime: 1000 * 60 * 20, // 20 min\n workersCount: 1,\n pollInterval: 10 * 1000,\n jobs: {\n orionjsRunMigrations: defineJob({\n type: 'recurrent',\n runEvery: 30 * 1000,\n async resolve(_params, context) {\n const instance = getInstance(MigrationsService)\n await instance.runMigrations(migrations, context)\n },\n }),\n },\n })\n\n return migrations\n}\n","import {ExecutionContext} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {Service} from '@orion-js/services'\n\nexport interface MigrationServiceOptions {\n name: string\n useMongoTransactions: false\n}\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string; options: MigrationServiceOptions}>()\n\nexport function MigrationService(options: MigrationServiceOptions) {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n serviceMetadata.set(target, {_serviceType: 'migrations', options: options})\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services.map(service => {\n const instance = getInstance(service)\n const options = serviceMetadata.get(instance.constructor)\n if (!options._serviceType || options._serviceType !== 'migrations') {\n throw new Error(`Service ${service.name} is not a migration service`)\n }\n\n return {\n ...options.options,\n runMigration: async (context: ExecutionContext) => {\n const instance = getInstance(service) as any\n return await instance.runMigration(context)\n },\n }\n })\n}\n","import {Inject, Service} from '@orion-js/services'\nimport type {MigrationsRepo as MigrationsRepoType} from './Repo'\nimport {MigrationsRepo} from './Repo'\nimport {logger} from '@orion-js/logger'\nimport {MigrationExecutable} from './service'\nimport {ExecutionContext} from '@orion-js/dogs'\n\n@Service()\nexport class MigrationsService {\n @Inject(() => MigrationsRepo)\n private migrationsRepo: MigrationsRepoType\n\n async getNextMigration(migrationsList: MigrationExecutable[]) {\n const completedNames = await this.migrationsRepo.getCompletedMigrationNames()\n\n for (const migrationExecutable of migrationsList) {\n if (completedNames.includes(migrationExecutable.name)) continue\n return migrationExecutable\n }\n }\n\n async runMigrations(migrationsList: MigrationExecutable[], context: ExecutionContext) {\n const next = await this.getNextMigration(migrationsList)\n if (!next) return\n\n logger.info('[orionjs/migrations] Running migration...', {name: next.name})\n\n if (next.useMongoTransactions) {\n await this.runAsTransaction(next.runMigration, context)\n } else {\n await this.runMigration(next.runMigration, context)\n }\n\n logger.info('[orionjs/migrations] Migration executed correctly', {name: next.name})\n\n await this.migrationsRepo.saveCompletedMigration(next.name)\n\n await this.runMigrations(migrationsList, context)\n }\n\n async runMigration(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration', {error})\n throw error\n }\n }\n\n async runAsTransaction(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n const {client} = this.migrationsRepo.collection.client\n const session = client.startSession()\n\n await session.withTransaction(async () => {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration, will abort transaction', {\n error,\n })\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAA+B;AAC/B,oBAA8C;AAIvC,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AAAA,EACF;AAAA,EAEA,MAAM,iBACJ,MACA,SACA;AACA,UAAM,EAAC,OAAM,IAAI,KAAK,eAAe,WAAW;AAChD,UAAM,UAAU,OAAO,aAAa;AAEpC,UAAM,QAAQ,gBAAgB,YAAY;AACxC,UAAI;AACF,cAAM,KAAK,OAAO;AAAA,MACpB,SAAS,OAAO;AACd,6BAAO,MAAM,wEAAwE;AAAA,UACnF;AAAA,QACF,CAAC;AACD,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAED,YAAQ,WAAW;AAAA,EACrB;AACF;AAhEOA,SAAA;AAEL,kBAAAA,QAAA,GAAQ,kBADR,qBADW;AAAA,oBAAN,kBAAAA,QAAA,wBADP,+BACa;AAAN,kBAAAA,QAAA,GAAM;;;AFJb,IAAAC,iBAAqB;AAOd,SAAS,eAAe,mBAA0B,SAAmB;AAC1E,QAAM,aAAa,0BAA0B,iBAAiB;AAC9D,MAAI,mCAAS,QAAS,QAAO;AAE7B,gCAAa;AAAA,IACX,UAAU;AAAA,IACV,mBAAmB,OAAO,QAAkB;AAC1C,4BAAO,MAAM,6BAA6B,IAAI,IAAI,IAAI,EAAC,IAAG,CAAC;AAAA,IAC7D;AAAA,IACA,gBAAgB;AAAA,IAChB,iBAAiB,MAAO,KAAK;AAAA;AAAA,IAC7B,cAAc;AAAA,IACd,cAAc,KAAK;AAAA,IACnB,MAAM;AAAA,MACJ,0BAAsB,uBAAU;AAAA,QAC9B,MAAM;AAAA,QACN,UAAU,KAAK;AAAA,QACf,MAAM,QAAQ,SAAS,SAAS;AAC9B,gBAAM,eAAW,8BAAY,iBAAiB;AAC9C,gBAAM,SAAS,cAAc,YAAY,OAAO;AAAA,QAClD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["import_mongodb","import_services","instance","import_services","import_services","_init","import_logger"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/MigrationsService.ts","../src/service/index.ts"],"sourcesContent":["export * from './Schema'\nexport * from './Repo'\nexport * from './loadMigrations'\nexport * from './service'\nexport * from './MigrationsService'\n","import {TypedId, typedId} from '@orion-js/mongodb'\nimport {InferSchemaType, schemaWithName} from '@orion-js/schema'\n\nexport type MigrationId = TypedId<'scnmg'>\n\nexport const MigrationSchema = schemaWithName('Migration', {\n _id: {\n type: typedId('scnmg'),\n },\n name: {\n type: String,\n },\n completedAt: {\n type: Date,\n },\n})\n\nexport type MigrationType = InferSchemaType<typeof MigrationSchema>\n","import {createCollection} from '@orion-js/mongodb'\nimport {MigrationSchema} from './Schema'\nimport {Service} from '@orion-js/services'\n\n@Service()\nexport class MigrationsRepo {\n public collection = createCollection({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n indexes: [],\n })\n\n async getCompletedMigrationNames() {\n const migrations = await this.collection.find().toArray()\n return migrations.map(m => m.name)\n }\n\n async saveCompletedMigration(name: string) {\n await this.collection.insertOne({\n name,\n completedAt: new Date(),\n })\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\nimport {getMigrationsFromServices} from '../service'\n\nexport interface Options {\n lockTime?: number\n omitJob?: boolean\n}\n\nexport function loadMigrations(migrationServices: any[], options?: Options) {\n const migrations = getMigrationsFromServices(migrationServices)\n if (options?.omitJob) return migrations\n\n startWorkers({\n cooldownPeriod: 1000,\n defaultLockTime: 1000 * 60 * 20, // 20 min\n workersCount: 1,\n pollInterval: 10 * 1000,\n jobs: {\n orionjsRunMigrations: defineJob({\n type: 'recurrent',\n runEvery: 30 * 1000,\n async resolve(_params, context) {\n const instance = getInstance(MigrationsService)\n await instance.runMigrations(migrations, context)\n },\n }),\n },\n })\n\n return migrations\n}\n","import {Inject, Service} from '@orion-js/services'\nimport type {MigrationsRepo as MigrationsRepoType} from './Repo'\nimport {MigrationsRepo} from './Repo'\nimport {logger} from '@orion-js/logger'\nimport {MigrationExecutable} from './service'\nimport {ExecutionContext} from '@orion-js/dogs'\n\n@Service()\nexport class MigrationsService {\n @Inject(() => MigrationsRepo)\n private migrationsRepo: MigrationsRepoType\n\n async getNextMigration(migrationsList: MigrationExecutable[]) {\n const completedNames = await this.migrationsRepo.getCompletedMigrationNames()\n\n for (const migrationExecutable of migrationsList) {\n if (completedNames.includes(migrationExecutable.name)) continue\n return migrationExecutable\n }\n }\n\n async runMigrations(migrationsList: MigrationExecutable[], context: ExecutionContext) {\n const next = await this.getNextMigration(migrationsList)\n if (!next) return\n\n logger.info('[orionjs/migrations] Running migration...', {name: next.name})\n\n if (next.useMongoTransactions) {\n await this.runAsTransaction(next.runMigration, context)\n } else {\n await this.runMigration(next.runMigration, context)\n }\n\n logger.info('[orionjs/migrations] Migration executed correctly', {name: next.name})\n\n await this.migrationsRepo.saveCompletedMigration(next.name)\n\n await this.runMigrations(migrationsList, context)\n }\n\n async runMigration(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration', {error})\n throw error\n }\n }\n\n async runAsTransaction(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n const {client} = this.migrationsRepo.collection.client\n const session = client.startSession()\n\n await session.withTransaction(async () => {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration, will abort transaction', {\n error,\n })\n throw error\n }\n })\n\n session.endSession()\n }\n}\n","import {ExecutionContext} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {Service} from '@orion-js/services'\n\nexport interface MigrationServiceOptions {\n name: string\n useMongoTransactions: false\n}\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string; options: MigrationServiceOptions}>()\n\nexport function MigrationService(options: MigrationServiceOptions) {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n serviceMetadata.set(target, {_serviceType: 'migrations', options: options})\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services.map(service => {\n const instance = getInstance(service)\n const options = serviceMetadata.get(instance.constructor)\n if (!options._serviceType || options._serviceType !== 'migrations') {\n throw new Error(`Service ${service.name} is not a migration service`)\n }\n\n return {\n ...options.options,\n runMigration: async (context: ExecutionContext) => {\n const instance = getInstance(service) as any\n return await instance.runMigration(context)\n },\n }\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAA+B;AAC/B,oBAA8C;AAIvC,IAAM,sBAAkB,8BAAe,aAAa;AAAA,EACzD,KAAK;AAAA,IACH,UAAM,wBAAQ,OAAO;AAAA,EACvB;AAAA,EACA,MAAM;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,EACR;AACF,CAAC;;;ACfD,IAAAA,kBAA+B;AAE/B,sBAAsB;AAFtB;AAIA,kCAAC,yBAAQ;AACF,IAAM,iBAAN,MAAqB;AAAA,EACnB,iBAAa,kCAAiB;AAAA,IACnC,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,SAAS,CAAC;AAAA,EACZ,CAAC;AAAA,EAED,MAAM,6BAA6B;AACjC,UAAM,aAAa,MAAM,KAAK,WAAW,KAAK,EAAE,QAAQ;AACxD,WAAO,WAAW,IAAI,OAAK,EAAE,IAAI;AAAA,EACnC;AAAA,EAEA,MAAM,uBAAuB,MAAc;AACzC,UAAM,KAAK,WAAW,UAAU;AAAA,MAC9B;AAAA,MACA,aAAa,oBAAI,KAAK;AAAA,IACxB,CAAC;AAAA,EACH;AACF;AAlBO;AAAM,iBAAN,8CADP,4BACa;AAAN,4BAAM;;;ACLb,kBA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uBAAU;AAAA,QAC9B,MAAM;AAAA,QACN,UAAU,KAAK;AAAA,QACf,MAAM,QAAQ,SAAS,SAAS;AAC9B,gBAAM,eAAW,8BAAY,iBAAiB;AAC9C,gBAAM,SAAS,cAAc,YAAY,OAAO;AAAA,QAClD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["import_mongodb","import_services","import_services","_init","import_services","instance"]}
package/dist/index.d.cts CHANGED
@@ -1,40 +1,14 @@
1
- import * as _orion_js_schema from '@orion-js/schema';
2
- import { InferSchemaType } from '@orion-js/schema';
3
- import * as _orion_js_mongodb from '@orion-js/mongodb';
4
1
  import { TypedId } from '@orion-js/mongodb';
2
+ import { InferSchemaType } from '@orion-js/schema';
5
3
  import { ExecutionContext } from '@orion-js/dogs';
6
4
 
7
5
  type MigrationId = TypedId<'scnmg'>;
8
- declare const MigrationSchema: {
9
- _id: {
10
- type: _orion_js_schema.FieldType<`scnmg-${string}`> & {
11
- generateId: () => `scnmg-${string}`;
12
- };
13
- };
14
- name: {
15
- type: StringConstructor;
16
- };
17
- completedAt: {
18
- type: DateConstructor;
19
- };
20
- };
6
+ declare const MigrationSchema: any;
21
7
  type MigrationType = InferSchemaType<typeof MigrationSchema>;
22
8
 
23
9
  declare class MigrationsRepo {
24
- collection: _orion_js_mongodb.Collection<_orion_js_mongodb.InferSchemaTypeWithId<{
25
- _id: {
26
- type: _orion_js_schema.FieldType<`scnmg-${string}`> & {
27
- generateId: () => `scnmg-${string}`;
28
- };
29
- };
30
- name: {
31
- type: StringConstructor;
32
- };
33
- completedAt: {
34
- type: DateConstructor;
35
- };
36
- }>>;
37
- getCompletedMigrationNames(): Promise<string[]>;
10
+ collection: any;
11
+ getCompletedMigrationNames(): Promise<any>;
38
12
  saveCompletedMigration(name: string): Promise<void>;
39
13
  }
40
14
 
package/dist/index.d.ts CHANGED
@@ -1,40 +1,14 @@
1
- import * as _orion_js_schema from '@orion-js/schema';
2
- import { InferSchemaType } from '@orion-js/schema';
3
- import * as _orion_js_mongodb from '@orion-js/mongodb';
4
1
  import { TypedId } from '@orion-js/mongodb';
2
+ import { InferSchemaType } from '@orion-js/schema';
5
3
  import { ExecutionContext } from '@orion-js/dogs';
6
4
 
7
5
  type MigrationId = TypedId<'scnmg'>;
8
- declare const MigrationSchema: {
9
- _id: {
10
- type: _orion_js_schema.FieldType<`scnmg-${string}`> & {
11
- generateId: () => `scnmg-${string}`;
12
- };
13
- };
14
- name: {
15
- type: StringConstructor;
16
- };
17
- completedAt: {
18
- type: DateConstructor;
19
- };
20
- };
6
+ declare const MigrationSchema: any;
21
7
  type MigrationType = InferSchemaType<typeof MigrationSchema>;
22
8
 
23
9
  declare class MigrationsRepo {
24
- collection: _orion_js_mongodb.Collection<_orion_js_mongodb.InferSchemaTypeWithId<{
25
- _id: {
26
- type: _orion_js_schema.FieldType<`scnmg-${string}`> & {
27
- generateId: () => `scnmg-${string}`;
28
- };
29
- };
30
- name: {
31
- type: StringConstructor;
32
- };
33
- completedAt: {
34
- type: DateConstructor;
35
- };
36
- }>>;
37
- getCompletedMigrationNames(): Promise<string[]>;
10
+ collection: any;
11
+ getCompletedMigrationNames(): Promise<any>;
38
12
  saveCompletedMigration(name: string): Promise<void>;
39
13
  }
40
14
 
package/dist/index.js CHANGED
@@ -90,42 +90,13 @@ __runInitializers(_init, 1, MigrationsRepo);
90
90
 
91
91
  // src/loadMigrations/index.ts
92
92
  import { defineJob, startWorkers } from "@orion-js/dogs";
93
-
94
- // src/service/index.ts
95
- import { getInstance } from "@orion-js/services";
96
- import { Service as Service2 } from "@orion-js/services";
97
- var serviceMetadata = /* @__PURE__ */ new WeakMap();
98
- function MigrationService(options) {
99
- return (target, context) => {
100
- Service2()(target, context);
101
- serviceMetadata.set(target, { _serviceType: "migrations", options });
102
- };
103
- }
104
- function getMigrationsFromServices(services) {
105
- return services.map((service) => {
106
- const instance = getInstance(service);
107
- const options = serviceMetadata.get(instance.constructor);
108
- if (!options._serviceType || options._serviceType !== "migrations") {
109
- throw new Error(`Service ${service.name} is not a migration service`);
110
- }
111
- return {
112
- ...options.options,
113
- runMigration: async (context) => {
114
- const instance2 = getInstance(service);
115
- return await instance2.runMigration(context);
116
- }
117
- };
118
- });
119
- }
120
-
121
- // src/loadMigrations/index.ts
122
93
  import { getInstance as getInstance2 } from "@orion-js/services";
123
94
 
124
95
  // src/MigrationsService.ts
125
- import { Inject, Service as Service3 } from "@orion-js/services";
96
+ import { Inject, Service as Service2 } from "@orion-js/services";
126
97
  import { logger } from "@orion-js/logger";
127
98
  var _migrationsRepo_dec, _MigrationsService_decorators, _init2;
128
- _MigrationsService_decorators = [Service3()], _migrationsRepo_dec = [Inject(() => MigrationsRepo)];
99
+ _MigrationsService_decorators = [Service2()], _migrationsRepo_dec = [Inject(() => MigrationsRepo)];
129
100
  var MigrationsService = class {
130
101
  constructor() {
131
102
  __publicField(this, "migrationsRepo", __runInitializers(_init2, 8, this)), __runInitializers(_init2, 11, this);
@@ -179,16 +150,38 @@ __decorateElement(_init2, 5, "migrationsRepo", _migrationsRepo_dec, MigrationsSe
179
150
  MigrationsService = __decorateElement(_init2, 0, "MigrationsService", _MigrationsService_decorators, MigrationsService);
180
151
  __runInitializers(_init2, 1, MigrationsService);
181
152
 
153
+ // src/service/index.ts
154
+ import { getInstance } from "@orion-js/services";
155
+ import { Service as Service3 } from "@orion-js/services";
156
+ var serviceMetadata = /* @__PURE__ */ new WeakMap();
157
+ function MigrationService(options) {
158
+ return (target, context) => {
159
+ Service3()(target, context);
160
+ serviceMetadata.set(target, { _serviceType: "migrations", options });
161
+ };
162
+ }
163
+ function getMigrationsFromServices(services) {
164
+ return services.map((service) => {
165
+ const instance = getInstance(service);
166
+ const options = serviceMetadata.get(instance.constructor);
167
+ if (!options._serviceType || options._serviceType !== "migrations") {
168
+ throw new Error(`Service ${service.name} is not a migration service`);
169
+ }
170
+ return {
171
+ ...options.options,
172
+ runMigration: async (context) => {
173
+ const instance2 = getInstance(service);
174
+ return await instance2.runMigration(context);
175
+ }
176
+ };
177
+ });
178
+ }
179
+
182
180
  // src/loadMigrations/index.ts
183
- import { logger as logger2 } from "@orion-js/logger";
184
181
  function loadMigrations(migrationServices, options) {
185
182
  const migrations = getMigrationsFromServices(migrationServices);
186
183
  if (options == null ? void 0 : options.omitJob) return migrations;
187
184
  startWorkers({
188
- maxTries: 5,
189
- onMaxTriesReached: async (job) => {
190
- logger2.error(`Max tries reached for job ${job.name}`, { job });
191
- },
192
185
  cooldownPeriod: 1e3,
193
186
  defaultLockTime: 1e3 * 60 * 20,
194
187
  // 20 min
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/service/index.ts","../src/MigrationsService.ts"],"sourcesContent":["import {TypedId, typedId} from '@orion-js/mongodb'\nimport {InferSchemaType, schemaWithName} from '@orion-js/schema'\n\nexport type MigrationId = TypedId<'scnmg'>\n\nexport const MigrationSchema = schemaWithName('Migration', {\n _id: {\n type: typedId('scnmg'),\n },\n name: {\n type: String,\n },\n completedAt: {\n type: Date,\n },\n})\n\nexport type MigrationType = InferSchemaType<typeof MigrationSchema>\n","import {createCollection} from '@orion-js/mongodb'\nimport {MigrationSchema} from './Schema'\nimport {Service} from '@orion-js/services'\n\n@Service()\nexport class MigrationsRepo {\n public collection = createCollection({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n indexes: [],\n })\n\n async getCompletedMigrationNames() {\n const migrations = await this.collection.find().toArray()\n return migrations.map(m => m.name)\n }\n\n async saveCompletedMigration(name: string) {\n await this.collection.insertOne({\n name,\n completedAt: new Date(),\n })\n }\n}\n","import {defineJob, JobToRun, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\nimport {logger} from '@orion-js/logger'\n\nexport interface Options {\n lockTime?: number\n omitJob?: boolean\n}\n\nexport function loadMigrations(migrationServices: any[], options?: Options) {\n const migrations = getMigrationsFromServices(migrationServices)\n if (options?.omitJob) return migrations\n\n startWorkers({\n maxTries: 5,\n onMaxTriesReached: async (job: JobToRun) => {\n logger.error(`Max tries reached for job ${job.name}`, {job})\n },\n cooldownPeriod: 1000,\n defaultLockTime: 1000 * 60 * 20, // 20 min\n workersCount: 1,\n pollInterval: 10 * 1000,\n jobs: {\n orionjsRunMigrations: defineJob({\n type: 'recurrent',\n runEvery: 30 * 1000,\n async resolve(_params, context) {\n const instance = getInstance(MigrationsService)\n await instance.runMigrations(migrations, context)\n },\n }),\n },\n })\n\n return migrations\n}\n","import {ExecutionContext} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {Service} from '@orion-js/services'\n\nexport interface MigrationServiceOptions {\n name: string\n useMongoTransactions: false\n}\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string; options: MigrationServiceOptions}>()\n\nexport function MigrationService(options: MigrationServiceOptions) {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n serviceMetadata.set(target, {_serviceType: 'migrations', options: options})\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services.map(service => {\n const instance = getInstance(service)\n const options = serviceMetadata.get(instance.constructor)\n if (!options._serviceType || options._serviceType !== 'migrations') {\n throw new Error(`Service ${service.name} is not a migration service`)\n }\n\n return {\n ...options.options,\n runMigration: async (context: ExecutionContext) => {\n const instance = getInstance(service) as any\n return await instance.runMigration(context)\n },\n }\n })\n}\n","import {Inject, Service} from '@orion-js/services'\nimport type {MigrationsRepo as MigrationsRepoType} from './Repo'\nimport {MigrationsRepo} from './Repo'\nimport {logger} from '@orion-js/logger'\nimport {MigrationExecutable} from './service'\nimport {ExecutionContext} from '@orion-js/dogs'\n\n@Service()\nexport class MigrationsService {\n @Inject(() => MigrationsRepo)\n private migrationsRepo: MigrationsRepoType\n\n async getNextMigration(migrationsList: MigrationExecutable[]) {\n const completedNames = await this.migrationsRepo.getCompletedMigrationNames()\n\n for (const migrationExecutable of migrationsList) {\n if (completedNames.includes(migrationExecutable.name)) continue\n return migrationExecutable\n }\n }\n\n async runMigrations(migrationsList: MigrationExecutable[], context: ExecutionContext) {\n const next = await this.getNextMigration(migrationsList)\n if (!next) return\n\n logger.info('[orionjs/migrations] Running migration...', {name: next.name})\n\n if (next.useMongoTransactions) {\n await this.runAsTransaction(next.runMigration, context)\n } else {\n await this.runMigration(next.runMigration, context)\n }\n\n logger.info('[orionjs/migrations] Migration executed correctly', {name: next.name})\n\n await this.migrationsRepo.saveCompletedMigration(next.name)\n\n await this.runMigrations(migrationsList, context)\n }\n\n async runMigration(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration', {error})\n throw error\n }\n }\n\n async runAsTransaction(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n const {client} = this.migrationsRepo.collection.client\n const session = client.startSession()\n\n await session.withTransaction(async () => {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration, will abort transaction', {\n error,\n })\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAiB,eAAc;AAC/B,SAAyB,sBAAqB;AAIvC,IAAM,kBAAkB,eAAe,aAAa;AAAA,EACzD,KAAK;AAAA,IACH,MAAM,QAAQ,OAAO;AAAA,EACvB;AAAA,EACA,MAAM;AAAA,IACJ,MAAM;AAAA,EACR;AAAA,EACA,aAAa;AAAA,IACX,MAAM;AAAA,EACR;AACF,CAAC;;;ACfD,SAAQ,wBAAuB;AAE/B,SAAQ,eAAc;AAFtB;AAIA,8BAAC,QAAQ;AACF,IAAM,iBAAN,MA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wE;AAAA,UACnF;AAAA,QACF,CAAC;AACD,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAED,YAAQ,WAAW;AAAA,EACrB;AACF;AAhEOA,SAAA;AAEL,kBAAAA,QAAA,GAAQ,kBADR,qBADW;AAAA,oBAAN,kBAAAA,QAAA,wBADP,+BACa;AAAN,kBAAAA,QAAA,GAAM;;;AFJb,SAAQ,UAAAE,eAAa;AAOd,SAAS,eAAe,mBAA0B,SAAmB;AAC1E,QAAM,aAAa,0BAA0B,iBAAiB;AAC9D,MAAI,mCAAS,QAAS,QAAO;AAE7B,eAAa;AAAA,IACX,UAAU;AAAA,IACV,mBAAmB,OAAO,QAAkB;AAC1C,MAAAA,QAAO,MAAM,6BAA6B,IAAI,IAAI,IAAI,EAAC,IAAG,CAAC;AAAA,IAC7D;AAAA,IACA,gBAAgB;AAAA,IAChB,iBAAiB,MAAO,KAAK;AAAA;AAAA,IAC7B,cAAc;AAAA,IACd,cAAc,KAAK;AAAA,IACnB,MAAM;AAAA,MACJ,sBAAsB,UAAU;AAAA,QAC9B,MAAM;AAAA,QACN,UAAU,KAAK;AAAA,QACf,MAAM,QAAQ,SAAS,SAAS;AAC9B,gBAAM,WAAWC,aAAY,iBAAiB;AAC9C,gBAAM,SAAS,cAAc,YAAY,OAAO;AAAA,QAClD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["Service","instance","getInstance","Service","_init","Service","logger","getInstance"]}
1
+ {"version":3,"sources":["../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/MigrationsService.ts","../src/service/index.ts"],"sourcesContent":["import {TypedId, typedId} from '@orion-js/mongodb'\nimport {InferSchemaType, schemaWithName} from '@orion-js/schema'\n\nexport type MigrationId = TypedId<'scnmg'>\n\nexport const MigrationSchema = schemaWithName('Migration', {\n _id: {\n type: typedId('scnmg'),\n },\n name: {\n type: String,\n },\n completedAt: {\n type: Date,\n },\n})\n\nexport type MigrationType = InferSchemaType<typeof MigrationSchema>\n","import {createCollection} from '@orion-js/mongodb'\nimport {MigrationSchema} from './Schema'\nimport {Service} from '@orion-js/services'\n\n@Service()\nexport class MigrationsRepo {\n public collection = createCollection({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n indexes: [],\n })\n\n async getCompletedMigrationNames() {\n const migrations = await this.collection.find().toArray()\n return migrations.map(m => m.name)\n }\n\n async saveCompletedMigration(name: string) {\n await this.collection.insertOne({\n name,\n completedAt: new Date(),\n })\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\nimport {getMigrationsFromServices} from '../service'\n\nexport interface Options {\n lockTime?: number\n omitJob?: boolean\n}\n\nexport function loadMigrations(migrationServices: any[], options?: Options) {\n const migrations = getMigrationsFromServices(migrationServices)\n if (options?.omitJob) return migrations\n\n startWorkers({\n cooldownPeriod: 1000,\n defaultLockTime: 1000 * 60 * 20, // 20 min\n workersCount: 1,\n pollInterval: 10 * 1000,\n jobs: {\n orionjsRunMigrations: defineJob({\n type: 'recurrent',\n runEvery: 30 * 1000,\n async resolve(_params, context) {\n const instance = getInstance(MigrationsService)\n await instance.runMigrations(migrations, context)\n },\n }),\n },\n })\n\n return migrations\n}\n","import {Inject, Service} from '@orion-js/services'\nimport type {MigrationsRepo as MigrationsRepoType} from './Repo'\nimport {MigrationsRepo} from './Repo'\nimport {logger} from '@orion-js/logger'\nimport {MigrationExecutable} from './service'\nimport {ExecutionContext} from '@orion-js/dogs'\n\n@Service()\nexport class MigrationsService {\n @Inject(() => MigrationsRepo)\n private migrationsRepo: MigrationsRepoType\n\n async getNextMigration(migrationsList: MigrationExecutable[]) {\n const completedNames = await this.migrationsRepo.getCompletedMigrationNames()\n\n for (const migrationExecutable of migrationsList) {\n if (completedNames.includes(migrationExecutable.name)) continue\n return migrationExecutable\n }\n }\n\n async runMigrations(migrationsList: MigrationExecutable[], context: ExecutionContext) {\n const next = await this.getNextMigration(migrationsList)\n if (!next) return\n\n logger.info('[orionjs/migrations] Running migration...', {name: next.name})\n\n if (next.useMongoTransactions) {\n await this.runAsTransaction(next.runMigration, context)\n } else {\n await this.runMigration(next.runMigration, context)\n }\n\n logger.info('[orionjs/migrations] Migration executed correctly', {name: next.name})\n\n await this.migrationsRepo.saveCompletedMigration(next.name)\n\n await this.runMigrations(migrationsList, context)\n }\n\n async runMigration(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration', {error})\n throw error\n }\n }\n\n async runAsTransaction(\n func: (context: ExecutionContext) => Promise<void>,\n context: ExecutionContext,\n ) {\n const {client} = this.migrationsRepo.collection.client\n const session = client.startSession()\n\n await session.withTransaction(async () => {\n try {\n await func(context)\n } catch (error) {\n logger.error('[orionjs/migrations] Error running migration, will abort transaction', {\n error,\n })\n throw error\n }\n })\n\n session.endSession()\n }\n}\n","import {ExecutionContext} from '@orion-js/dogs'\nimport {getInstance} from '@orion-js/services'\nimport {Service} from '@orion-js/services'\n\nexport interface MigrationServiceOptions {\n name: string\n useMongoTransactions: false\n}\n\n// Define metadata storage using WeakMaps\nconst serviceMetadata = new WeakMap<any, {_serviceType: string; options: MigrationServiceOptions}>()\n\nexport function MigrationService(options: MigrationServiceOptions) {\n return (target: any, context: ClassDecoratorContext<any>) => {\n Service()(target, context)\n serviceMetadata.set(target, {_serviceType: 'migrations', options: options})\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services.map(service => {\n const instance = getInstance(service)\n const options = serviceMetadata.get(instance.constructor)\n if (!options._serviceType || options._serviceType !== 'migrations') {\n throw new Error(`Service ${service.name} is not a migration service`)\n }\n\n return {\n ...options.options,\n runMigration: async (context: ExecutionContext) => {\n const instance = getInstance(service) as any\n return await instance.runMigration(context)\n },\n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AkB,oBAAI,QAAuE;AAE5F,SAAS,iBAAiB,SAAkC;AACjE,SAAO,CAAC,QAAa,YAAwC;AAC3D,IAAAA,SAAQ,EAAE,QAAQ,OAAO;AACzB,oBAAgB,IAAI,QAAQ,EAAC,cAAc,cAAc,QAAgB,CAAC;AAAA,EAC5E;AACF;AAMO,SAAS,0BAA0B,UAAwC;AAChF,SAAO,SAAS,IAAI,aAAW;AAC7B,UAAM,WAAW,YAAY,OAAO;AACpC,UAAM,UAAU,gBAAgB,IAAI,SAAS,WAAW;AACxD,QAAI,CAAC,QAAQ,gBAAgB,QAAQ,iBAAiB,cAAc;AAClE,YAAM,IAAI,MAAM,WAAW,QAAQ,IAAI,6BAA6B;AAAA,IACtE;AAEA,WAAO;AAAA,MACL,GAAG,QAAQ;AAAA,MACX,cAAc,OAAO,YAA8B;AACjD,cAAMC,YAAW,YAAY,OAAO;AACpC,eAAO,MAAMA,UAAS,aAAa,OAAO;AAAA,MAC5C;AAAA,IACF;AAAA,EACF,CAAC;AACH;;;AF7BO,SAAS,eAAe,mBAA0B,SAAmB;AAC1E,QAAM,aAAa,0BAA0B,iBAAiB;AAC9D,MAAI,mCAAS,QAAS,QAAO;AAE7B,eAAa;AAAA,IACX,gBAAgB;AAAA,IAChB,iBAAiB,MAAO,KAAK;AAAA;AAAA,IAC7B,cAAc;AAAA,IACd,cAAc,KAAK;AAAA,IACnB,MAAM;AAAA,MACJ,sBAAsB,UAAU;AAAA,QAC9B,MAAM;AAAA,QACN,UAAU,KAAK;AAAA,QACf,MAAM,QAAQ,SAAS,SAAS;AAC9B,gBAAM,WAAWC,aAAY,iBAAiB;AAC9C,gBAAM,SAAS,cAAc,YAAY,OAAO;AAAA,QAClD;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AAED,SAAO;AACT;","names":["getInstance","Service","_init","Service","Service","instance","getInstance"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orion-js/migrations",
3
- "version": "4.3.3",
3
+ "version": "4.3.5",
4
4
  "main": "./dist/index.cjs",
5
5
  "types": "./dist/index.d.ts",
6
6
  "files": [
@@ -8,15 +8,8 @@
8
8
  ],
9
9
  "author": "nicolaslopezj",
10
10
  "license": "MIT",
11
- "scripts": {
12
- "test": "bun test",
13
- "prepare": "bun run build",
14
- "clean": "rm -rf ./dist",
15
- "build": "tsup",
16
- "dev": "tsup --watch"
17
- },
18
11
  "peerDependencies": {
19
- "@orion-js/dogs": "4.3.4",
12
+ "@orion-js/dogs": "4.3.6",
20
13
  "@orion-js/logger": "4.3.1",
21
14
  "@orion-js/mongodb": "4.3.1"
22
15
  },
@@ -28,7 +21,7 @@
28
21
  },
29
22
  "devDependencies": {
30
23
  "@orion-js/mongodb": "4.3.1",
31
- "@orion-js/dogs": "4.3.4",
24
+ "@orion-js/dogs": "4.3.6",
32
25
  "@types/node": "^18.0.0",
33
26
  "mongodb-memory-server": "^10.1.4",
34
27
  "tsup": "^8.0.1",
@@ -44,5 +37,11 @@
44
37
  "types": "./dist/index.d.ts",
45
38
  "import": "./dist/index.js",
46
39
  "require": "./dist/index.cjs"
40
+ },
41
+ "scripts": {
42
+ "test": "bun test",
43
+ "clean": "rm -rf ./dist",
44
+ "build": "tsup",
45
+ "dev": "tsup --watch"
47
46
  }
48
- }
47
+ }