@orion-js/migrations 4.0.0-next.2 → 4.0.0-next.3

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
@@ -2,7 +2,6 @@ var __defProp = Object.defineProperty;
2
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
5
  var __export = (target, all) => {
7
6
  for (var name in all)
8
7
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -16,6 +15,14 @@ var __copyProps = (to, from, except, desc) => {
16
15
  return to;
17
16
  };
18
17
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var __decorateClass = (decorators, target, key, kind) => {
19
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
20
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
21
+ if (decorator = decorators[i])
22
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
23
+ if (kind && result) __defProp(target, key, result);
24
+ return result;
25
+ };
19
26
 
20
27
  // src/index.ts
21
28
  var index_exports = {};
@@ -31,53 +38,28 @@ module.exports = __toCommonJS(index_exports);
31
38
 
32
39
  // src/Schema.ts
33
40
  var import_typed_model = require("@orion-js/typed-model");
34
- function _ts_decorate(decorators, target, key, desc) {
35
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
36
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
37
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
38
- return c > 3 && r && Object.defineProperty(target, key, r), r;
39
- }
40
- __name(_ts_decorate, "_ts_decorate");
41
- function _ts_metadata(k, v) {
42
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
- }
44
- __name(_ts_metadata, "_ts_metadata");
45
- var _MigrationSchema = class _MigrationSchema {
41
+ var MigrationSchema = class {
46
42
  _id;
47
43
  name;
48
44
  completedAt;
49
45
  };
50
- __name(_MigrationSchema, "MigrationSchema");
51
- var MigrationSchema = _MigrationSchema;
52
- _ts_decorate([
53
- (0, import_typed_model.Prop)({
54
- type: "string"
55
- }),
56
- _ts_metadata("design:type", typeof MigrationId === "undefined" ? Object : MigrationId)
57
- ], MigrationSchema.prototype, "_id", void 0);
58
- _ts_decorate([
59
- (0, import_typed_model.Prop)(),
60
- _ts_metadata("design:type", String)
61
- ], MigrationSchema.prototype, "name", void 0);
62
- _ts_decorate([
63
- (0, import_typed_model.Prop)(),
64
- _ts_metadata("design:type", typeof Date === "undefined" ? Object : Date)
65
- ], MigrationSchema.prototype, "completedAt", void 0);
66
- MigrationSchema = _ts_decorate([
46
+ __decorateClass([
47
+ (0, import_typed_model.Prop)({ type: "string" })
48
+ ], MigrationSchema.prototype, "_id", 2);
49
+ __decorateClass([
50
+ (0, import_typed_model.Prop)()
51
+ ], MigrationSchema.prototype, "name", 2);
52
+ __decorateClass([
53
+ (0, import_typed_model.Prop)()
54
+ ], MigrationSchema.prototype, "completedAt", 2);
55
+ MigrationSchema = __decorateClass([
67
56
  (0, import_typed_model.TypedSchema)()
68
57
  ], MigrationSchema);
69
58
 
70
59
  // src/Repo.ts
71
60
  var import_mongodb = require("@orion-js/mongodb");
72
61
  var import_services = require("@orion-js/services");
73
- function _ts_decorate2(decorators, target, key, desc) {
74
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
75
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
76
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
77
- return c > 3 && r && Object.defineProperty(target, key, r), r;
78
- }
79
- __name(_ts_decorate2, "_ts_decorate");
80
- var _MigrationsRepo = class _MigrationsRepo {
62
+ var MigrationsRepo = class {
81
63
  collection = (0, import_mongodb.createCollection)({
82
64
  name: "orionjs.migrations",
83
65
  schema: MigrationSchema,
@@ -89,15 +71,10 @@ var _MigrationsRepo = class _MigrationsRepo {
89
71
  return migrations.map((m) => m.name);
90
72
  }
91
73
  async saveCompletedMigration(name) {
92
- await this.collection.insertOne({
93
- name,
94
- completedAt: /* @__PURE__ */ new Date()
95
- });
74
+ await this.collection.insertOne({ name, completedAt: /* @__PURE__ */ new Date() });
96
75
  }
97
76
  };
98
- __name(_MigrationsRepo, "MigrationsRepo");
99
- var MigrationsRepo = _MigrationsRepo;
100
- MigrationsRepo = _ts_decorate2([
77
+ MigrationsRepo = __decorateClass([
101
78
  (0, import_services.Service)()
102
79
  ], MigrationsRepo);
103
80
 
@@ -115,20 +92,18 @@ function MigrationService(options) {
115
92
  target.prototype.serviceType = "migration";
116
93
  };
117
94
  }
118
- __name(MigrationService, "MigrationService");
119
95
  function getMigrationsFromServices(services) {
120
96
  return services.filter((service) => service.prototype.serviceType === "migration").map((service) => {
121
97
  const options = service.prototype.options;
122
98
  return {
123
99
  ...options,
124
- runMigration: /* @__PURE__ */ __name(async (context) => {
100
+ runMigration: async (context) => {
125
101
  const instance = (0, import_services2.getInstance)(service);
126
102
  return await instance.runMigration(context);
127
- }, "runMigration")
103
+ }
128
104
  };
129
105
  });
130
106
  }
131
- __name(getMigrationsFromServices, "getMigrationsFromServices");
132
107
 
133
108
  // src/loadMigrations/index.ts
134
109
  var import_services5 = require("@orion-js/services");
@@ -136,18 +111,7 @@ var import_services5 = require("@orion-js/services");
136
111
  // src/MigrationsService.ts
137
112
  var import_services4 = require("@orion-js/services");
138
113
  var import_logger = require("@orion-js/logger");
139
- function _ts_decorate3(decorators, target, key, desc) {
140
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
141
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
142
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
143
- return c > 3 && r && Object.defineProperty(target, key, r), r;
144
- }
145
- __name(_ts_decorate3, "_ts_decorate");
146
- function _ts_metadata2(k, v) {
147
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
148
- }
149
- __name(_ts_metadata2, "_ts_metadata");
150
- var _MigrationsService = class _MigrationsService {
114
+ var MigrationsService = class {
151
115
  migrationsRepo;
152
116
  async getNextMigration(migrationsList) {
153
117
  const completedNames = await this.migrationsRepo.getCompletedMigrationNames();
@@ -159,17 +123,13 @@ var _MigrationsService = class _MigrationsService {
159
123
  async runMigrations(migrationsList, context) {
160
124
  const next = await this.getNextMigration(migrationsList);
161
125
  if (!next) return;
162
- import_logger.logger.info("[orionjs/migrations] Running migration...", {
163
- name: next.name
164
- });
126
+ import_logger.logger.info("[orionjs/migrations] Running migration...", { name: next.name });
165
127
  if (next.useMongoTransactions) {
166
128
  await this.runAsTransaction(next.runMigration, context);
167
129
  } else {
168
130
  await this.runMigration(next.runMigration, context);
169
131
  }
170
- import_logger.logger.info("[orionjs/migrations] Migration executed correctly", {
171
- name: next.name
172
- });
132
+ import_logger.logger.info("[orionjs/migrations] Migration executed correctly", { name: next.name });
173
133
  await this.migrationsRepo.saveCompletedMigration(next.name);
174
134
  await this.runMigrations(migrationsList, context);
175
135
  }
@@ -195,13 +155,10 @@ var _MigrationsService = class _MigrationsService {
195
155
  session.endSession();
196
156
  }
197
157
  };
198
- __name(_MigrationsService, "MigrationsService");
199
- var MigrationsService = _MigrationsService;
200
- _ts_decorate3([
201
- (0, import_services4.Inject)(() => MigrationsRepo),
202
- _ts_metadata2("design:type", typeof MigrationsRepoType === "undefined" ? Object : MigrationsRepoType)
203
- ], MigrationsService.prototype, "migrationsRepo", void 0);
204
- MigrationsService = _ts_decorate3([
158
+ __decorateClass([
159
+ (0, import_services4.Inject)(() => MigrationsRepo)
160
+ ], MigrationsService.prototype, "migrationsRepo", 2);
161
+ MigrationsService = __decorateClass([
205
162
  (0, import_services4.Service)()
206
163
  ], MigrationsService);
207
164
 
@@ -212,6 +169,7 @@ function loadMigrations(migrationServices, options) {
212
169
  (0, import_dogs.startWorkers)({
213
170
  cooldownPeriod: 1e3,
214
171
  lockTime: 1e3 * 60 * 20,
172
+ // 20 min
215
173
  workersCount: 1,
216
174
  pollInterval: 10 * 1e3,
217
175
  jobs: {
@@ -227,7 +185,6 @@ function loadMigrations(migrationServices, options) {
227
185
  });
228
186
  return migrations;
229
187
  }
230
- __name(loadMigrations, "loadMigrations");
231
188
  // Annotate the CommonJS export names for ESM import in node:
232
189
  0 && (module.exports = {
233
190
  MigrationSchema,
@@ -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 {TypedSchema, Prop} from '@orion-js/typed-model'\n\nexport type MigrationId = `scnmg-${string}`\n\n@TypedSchema()\nexport class MigrationSchema {\n @Prop({type: 'string'})\n _id: MigrationId\n\n @Prop()\n name: string\n\n @Prop()\n completedAt: Date\n}\n","import {MongoCollection, Repository, Collection, 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<MigrationSchema>({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n idPrefix: 'scnmg-',\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({name, completedAt: new Date()})\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\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 lockTime: 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\nexport function MigrationService(options: MigrationServiceOptions): ClassDecorator {\n return function (target: any) {\n Service()(target)\n target.prototype.service = target\n target.prototype.options = options\n target.prototype.serviceType = 'migration'\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services\n .filter(service => service.prototype.serviceType === 'migration')\n .map(service => {\n const options = service.prototype.options\n return {\n ...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', error)\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;ACAA,yBAAgC;;;;;;;;;;;;AAKzB,IAAMA,mBAAN,MAAMA,iBAAAA;EAEXC;EAGAC;EAGAC;AACF;AATaH;AAAN,IAAMA,kBAAN;;;IACEI,MAAM;;;;;;;;;;;;;;;;;ACNf,qBAAwE;AAExE,sBAAwB;;;;;;;;AAGjB,IAAMC,kBAAN,MAAMA,gBAAAA;EACJC,iBAAaC,iCAAkC;IAClDC,MAAM;IACNC,QAAQC;IACRC,UAAU;IACVC,SAAS,CAAA;EACX,CAAA;EAEF,MAAMC,6BAA6B;AACjC,UAAMC,aAAa,MAAM,KAAKR,WAAWS,KAAI,EAAGC,QAAO;AACvD,WAAOF,WAAWG,IAAIC,CAAAA,MAAKA,EAAEV,IAAI;EACnC;EAEA,MAAMW,uBAAuBX,MAAc;AACzC,UAAM,KAAKF,WAAWc,UAAU;MAACZ;MAAMa,aAAa,oBAAIC,KAAAA;IAAM,CAAA;EAChE;AACF;AAhBajB;AAAN,IAAMA,iBAAN;;;;;;ACLP,kBAAsC;;;ACCtC,IAAAkB,mBAA0B;AAC1B,IAAAA,mBAAsB;AAOf,SAASC,iBAAiBC,SAAgC;AAC/D,SAAO,SAAUC,QAAW;AAC1BC,kCAAAA,EAAUD,MAAAA;AACVA,WAAOE,UAAUC,UAAUH;AAC3BA,WAAOE,UAAUH,UAAUA;AAC3BC,WAAO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OAAAA;IACb,SAASS,OAAO;AACdP,2BAAOO,MAAM,gDAAgDA,KAAAA;AAC7D,YAAMA;IACR;EACF;EAEA,MAAMJ,iBACJG,MACAR,SACA;AACA,UAAM,EAACU,OAAM,IAAI,KAAKnB,eAAeoB,WAAWD;AAChD,UAAME,UAAUF,OAAOG,aAAY;AAEnC,UAAMD,QAAQE,gBAAgB,YAAA;AAC5B,UAAI;AACF,cAAMN,KAAKR,OAAAA;MACb,SAASS,OAAO;AACdP,6BAAOO,MAAM,wEAAwEA,KAAAA;AACrF,cAAMA;MACR;IACF,CAAA;AAEAG,YAAQG,WAAU;EACpB;AACF;AA9DazB;AAAN,IAAMA,oBAAN;;qCACS0B,cAAAA;;;;;;;;AFCT,SAASC,eAAeC,mBAA0BC,SAAiB;AACxE,QAAMC,aAAaC,0BAA0BH,iBAAAA;AAC7C,MAAIC,mCAASG,QAAS,QAAOF;AAE7BG,gCAAa;IACXC,gBAAgB;IAChBC,UAAU,MAAO,KAAK;IACtBC,cAAc;IACdC,cAAc,KAAK;IACnBC,MAAM;MACJC,0BAAsBC,uBAAU;QAC9BC,MAAM;QACNC,UAAU,KAAK;QACf,MAAMC,QAAQC,QAAQC,SAAO;AAC3B,gBAAMC,eAAWC,8BAAYC,iBAAAA;AAC7B,gBAAMF,SAASG,cAAcnB,YAAYe,OAAAA;QAC3C;MACF,CAAA;IACF;EACF,CAAA;AAEA,SAAOf;AACT;AAtBgBH;","names":["MigrationSchema","_id","name","completedAt","type","MigrationsRepo","collection","createCollection","name","schema","MigrationSchema","idPrefix","indexes","getCompletedMigrationNames","migrations","find","toArray","map","m","saveCompletedMigration","insertOne","completedAt","Date","import_services","MigrationService","options","target","Service","prototype","service","serviceType","getMigrationsFromServices","services","filter","map","runMigration","context","instance","getInstance","import_services","import_services","MigrationsService","migrationsRepo","getNextMigration","migrationsList","completedNames","getCompletedMigrationNames","migrationExecutable","includes","name","runMigrations","context","next","logger","info","useMongoTransactions","runAsTransaction","runMigration","saveCompletedMigration","func","error","client","collection","session","startSession","withTransaction","endSession","MigrationsRepo","loadMigrations","migrationServices","options","migrations","getMigrationsFromServices","omitJob","startWorkers","cooldownPeriod","lockTime","workersCount","pollInterval","jobs","orionjsRunMigrations","defineJob","type","runEvery","resolve","params","context","instance","getInstance","MigrationsService","runMigrations"]}
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 {TypedSchema, Prop} from '@orion-js/typed-model'\n\nexport type MigrationId = `scnmg-${string}`\n\n@TypedSchema()\nexport class MigrationSchema {\n @Prop({type: 'string'})\n _id: MigrationId\n\n @Prop()\n name: string\n\n @Prop()\n completedAt: Date\n}\n","import {MongoCollection, Repository, Collection, 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<MigrationSchema>({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n idPrefix: 'scnmg-',\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({name, completedAt: new Date()})\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\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 lockTime: 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\nexport function MigrationService(options: MigrationServiceOptions): ClassDecorator {\n return function (target: any) {\n Service()(target)\n target.prototype.service = target\n target.prototype.options = options\n target.prototype.serviceType = 'migration'\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services\n .filter(service => service.prototype.serviceType === 'migration')\n .map(service => {\n const options = service.prototype.options\n return {\n ...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', error)\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAAgC;AAKzB,IAAM,kBAAN,MAAsB;AAAA,EAE3B;AAAA,EAGA;AAAA,EAGA;AACF;AAPE;AAAA,MADC,yBAAK,EAAC,MAAM,SAAQ,CAAC;AAAA,GADX,gBAEX;AAGA;AAAA,MADC,yBAAK;AAAA,GAJK,gBAKX;AAGA;AAAA,MADC,yBAAK;AAAA,GAPK,gBAQX;AARW,kBAAN;AAAA,MADN,gCAAY;AAAA,GACA;;;ACLb,qBAAwE;AAExE,sBAAwB;AAGjB,IAAM,iBAAN,MAAqB;AAAA,EACnB,iBAAa,iCAAkC;AAAA,IAClD,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,SAAS,CAAC;AAAA,EACZ,CAAC;AAAA,EAEH,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,EAAC,MAAM,aAAa,oBAAI,KAAK,EAAC,CAAC;AAAA,EACjE;AACF;AAhBa,iB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I,CAAC;AAElF,UAAM,KAAK,eAAe,uBAAuB,KAAK,IAAI;AAE1D,UAAM,KAAK,cAAc,gBAAgB,OAAO;AAAA,EAClD;AAAA,EAEA,MAAM,aACJ,MACA,SACA;AACA,QAAI;AACF,YAAM,KAAK,OAAO;AAAA,IACpB,SAAS,OAAO;AACd,2BAAO,MAAM,gDAAgD,KAAK;AAClE,YAAM;AAAA,IACR;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,KAAK;AAC1F,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAED,YAAQ,WAAW;AAAA,EACrB;AACF;AA5DU;AAAA,MADP,yBAAO,MAAM,cAAc;AAAA,GADjB,kBAEH;AAFG,oBAAN;AAAA,MADN,0BAAQ;AAAA,GACI;;;AFEN,SAAS,eAAe,mBAA0B,SAAmB;AAC1E,QAAM,aAAa,0BAA0B,iBAAiB;AAC9D,MAAI,mCAAS,QAAS,QAAO;AAE7B,gCAAa;AAAA,IACX,gBAAgB;AAAA,IAChB,UAAU,MAAO,KAAK;AAAA;AAAA,IACtB,cAAc;AAAA,IACd,cAAc,KAAK;AAAA,IACnB,MAAM;AAAA,MACJ,0BAAsB,uBAAU;AAAA,QAC9B,MAAM;AAAA,QACN,UAAU,KAAK;AAAA,QACf,MAAM,QAAQ,QAAQ,SAAS;AAC7B,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_services","import_services","import_services"]}
package/dist/index.js CHANGED
@@ -1,55 +1,38 @@
1
1
  var __defProp = Object.defineProperty;
2
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __decorateClass = (decorators, target, key, kind) => {
4
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
5
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
6
+ if (decorator = decorators[i])
7
+ result = (kind ? decorator(target, key, result) : decorator(result)) || result;
8
+ if (kind && result) __defProp(target, key, result);
9
+ return result;
10
+ };
3
11
 
4
12
  // src/Schema.ts
5
13
  import { TypedSchema, Prop } from "@orion-js/typed-model";
6
- function _ts_decorate(decorators, target, key, desc) {
7
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
8
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
9
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
10
- return c > 3 && r && Object.defineProperty(target, key, r), r;
11
- }
12
- __name(_ts_decorate, "_ts_decorate");
13
- function _ts_metadata(k, v) {
14
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
15
- }
16
- __name(_ts_metadata, "_ts_metadata");
17
- var _MigrationSchema = class _MigrationSchema {
14
+ var MigrationSchema = class {
18
15
  _id;
19
16
  name;
20
17
  completedAt;
21
18
  };
22
- __name(_MigrationSchema, "MigrationSchema");
23
- var MigrationSchema = _MigrationSchema;
24
- _ts_decorate([
25
- Prop({
26
- type: "string"
27
- }),
28
- _ts_metadata("design:type", typeof MigrationId === "undefined" ? Object : MigrationId)
29
- ], MigrationSchema.prototype, "_id", void 0);
30
- _ts_decorate([
31
- Prop(),
32
- _ts_metadata("design:type", String)
33
- ], MigrationSchema.prototype, "name", void 0);
34
- _ts_decorate([
35
- Prop(),
36
- _ts_metadata("design:type", typeof Date === "undefined" ? Object : Date)
37
- ], MigrationSchema.prototype, "completedAt", void 0);
38
- MigrationSchema = _ts_decorate([
19
+ __decorateClass([
20
+ Prop({ type: "string" })
21
+ ], MigrationSchema.prototype, "_id", 2);
22
+ __decorateClass([
23
+ Prop()
24
+ ], MigrationSchema.prototype, "name", 2);
25
+ __decorateClass([
26
+ Prop()
27
+ ], MigrationSchema.prototype, "completedAt", 2);
28
+ MigrationSchema = __decorateClass([
39
29
  TypedSchema()
40
30
  ], MigrationSchema);
41
31
 
42
32
  // src/Repo.ts
43
33
  import { createCollection } from "@orion-js/mongodb";
44
34
  import { Service } from "@orion-js/services";
45
- function _ts_decorate2(decorators, target, key, desc) {
46
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
47
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
48
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
49
- return c > 3 && r && Object.defineProperty(target, key, r), r;
50
- }
51
- __name(_ts_decorate2, "_ts_decorate");
52
- var _MigrationsRepo = class _MigrationsRepo {
35
+ var MigrationsRepo = class {
53
36
  collection = createCollection({
54
37
  name: "orionjs.migrations",
55
38
  schema: MigrationSchema,
@@ -61,15 +44,10 @@ var _MigrationsRepo = class _MigrationsRepo {
61
44
  return migrations.map((m) => m.name);
62
45
  }
63
46
  async saveCompletedMigration(name) {
64
- await this.collection.insertOne({
65
- name,
66
- completedAt: /* @__PURE__ */ new Date()
67
- });
47
+ await this.collection.insertOne({ name, completedAt: /* @__PURE__ */ new Date() });
68
48
  }
69
49
  };
70
- __name(_MigrationsRepo, "MigrationsRepo");
71
- var MigrationsRepo = _MigrationsRepo;
72
- MigrationsRepo = _ts_decorate2([
50
+ MigrationsRepo = __decorateClass([
73
51
  Service()
74
52
  ], MigrationsRepo);
75
53
 
@@ -87,20 +65,18 @@ function MigrationService(options) {
87
65
  target.prototype.serviceType = "migration";
88
66
  };
89
67
  }
90
- __name(MigrationService, "MigrationService");
91
68
  function getMigrationsFromServices(services) {
92
69
  return services.filter((service) => service.prototype.serviceType === "migration").map((service) => {
93
70
  const options = service.prototype.options;
94
71
  return {
95
72
  ...options,
96
- runMigration: /* @__PURE__ */ __name(async (context) => {
73
+ runMigration: async (context) => {
97
74
  const instance = getInstance(service);
98
75
  return await instance.runMigration(context);
99
- }, "runMigration")
76
+ }
100
77
  };
101
78
  });
102
79
  }
103
- __name(getMigrationsFromServices, "getMigrationsFromServices");
104
80
 
105
81
  // src/loadMigrations/index.ts
106
82
  import { getInstance as getInstance2 } from "@orion-js/services";
@@ -108,18 +84,7 @@ import { getInstance as getInstance2 } from "@orion-js/services";
108
84
  // src/MigrationsService.ts
109
85
  import { Inject, Service as Service3 } from "@orion-js/services";
110
86
  import { logger } from "@orion-js/logger";
111
- function _ts_decorate3(decorators, target, key, desc) {
112
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
113
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
114
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
115
- return c > 3 && r && Object.defineProperty(target, key, r), r;
116
- }
117
- __name(_ts_decorate3, "_ts_decorate");
118
- function _ts_metadata2(k, v) {
119
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
120
- }
121
- __name(_ts_metadata2, "_ts_metadata");
122
- var _MigrationsService = class _MigrationsService {
87
+ var MigrationsService = class {
123
88
  migrationsRepo;
124
89
  async getNextMigration(migrationsList) {
125
90
  const completedNames = await this.migrationsRepo.getCompletedMigrationNames();
@@ -131,17 +96,13 @@ var _MigrationsService = class _MigrationsService {
131
96
  async runMigrations(migrationsList, context) {
132
97
  const next = await this.getNextMigration(migrationsList);
133
98
  if (!next) return;
134
- logger.info("[orionjs/migrations] Running migration...", {
135
- name: next.name
136
- });
99
+ logger.info("[orionjs/migrations] Running migration...", { name: next.name });
137
100
  if (next.useMongoTransactions) {
138
101
  await this.runAsTransaction(next.runMigration, context);
139
102
  } else {
140
103
  await this.runMigration(next.runMigration, context);
141
104
  }
142
- logger.info("[orionjs/migrations] Migration executed correctly", {
143
- name: next.name
144
- });
105
+ logger.info("[orionjs/migrations] Migration executed correctly", { name: next.name });
145
106
  await this.migrationsRepo.saveCompletedMigration(next.name);
146
107
  await this.runMigrations(migrationsList, context);
147
108
  }
@@ -167,13 +128,10 @@ var _MigrationsService = class _MigrationsService {
167
128
  session.endSession();
168
129
  }
169
130
  };
170
- __name(_MigrationsService, "MigrationsService");
171
- var MigrationsService = _MigrationsService;
172
- _ts_decorate3([
173
- Inject(() => MigrationsRepo),
174
- _ts_metadata2("design:type", typeof MigrationsRepoType === "undefined" ? Object : MigrationsRepoType)
175
- ], MigrationsService.prototype, "migrationsRepo", void 0);
176
- MigrationsService = _ts_decorate3([
131
+ __decorateClass([
132
+ Inject(() => MigrationsRepo)
133
+ ], MigrationsService.prototype, "migrationsRepo", 2);
134
+ MigrationsService = __decorateClass([
177
135
  Service3()
178
136
  ], MigrationsService);
179
137
 
@@ -184,6 +142,7 @@ function loadMigrations(migrationServices, options) {
184
142
  startWorkers({
185
143
  cooldownPeriod: 1e3,
186
144
  lockTime: 1e3 * 60 * 20,
145
+ // 20 min
187
146
  workersCount: 1,
188
147
  pollInterval: 10 * 1e3,
189
148
  jobs: {
@@ -199,7 +158,6 @@ function loadMigrations(migrationServices, options) {
199
158
  });
200
159
  return migrations;
201
160
  }
202
- __name(loadMigrations, "loadMigrations");
203
161
  export {
204
162
  MigrationSchema,
205
163
  MigrationService,
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 {TypedSchema, Prop} from '@orion-js/typed-model'\n\nexport type MigrationId = `scnmg-${string}`\n\n@TypedSchema()\nexport class MigrationSchema {\n @Prop({type: 'string'})\n _id: MigrationId\n\n @Prop()\n name: string\n\n @Prop()\n completedAt: Date\n}\n","import {MongoCollection, Repository, Collection, 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<MigrationSchema>({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n idPrefix: 'scnmg-',\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({name, completedAt: new Date()})\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\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 lockTime: 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\nexport function MigrationService(options: MigrationServiceOptions): ClassDecorator {\n return function (target: any) {\n Service()(target)\n target.prototype.service = target\n target.prototype.options = options\n target.prototype.serviceType = 'migration'\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services\n .filter(service => service.prototype.serviceType === 'migration')\n .map(service => {\n const options = service.prototype.options\n return {\n ...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', error)\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;AAAA,SAAQA,aAAaC,YAAW;;;;;;;;;;;;AAKzB,IAAMC,mBAAN,MAAMA,iBAAAA;EAEXC;EAGAC;EAGAC;AACF;AATaH;AAAN,IAAMA,kBAAN;;;IACEI,MAAM;;;;;;;;;;;;;;;;;ACNf,SAAiDC,wBAAuB;AAExE,SAASC,eAAe;;;;;;;;AAGjB,IAAMC,kBAAN,MAAMA,gBAAAA;EACJC,aAAaC,iBAAkC;IAClDC,MAAM;IACNC,QAAQC;IACRC,UAAU;IACVC,SAAS,CAAA;EACX,CAAA;EAEF,MAAMC,6BAA6B;AACjC,UAAMC,aAAa,MAAM,KAAKR,WAAWS,KAAI,EAAGC,QAAO;AACvD,WAAOF,WAAWG,IAAIC,CAAAA,MAAKA,EAAEV,IAAI;EACnC;EAEA,MAAMW,uBAAuBX,MAAc;AACzC,UAAM,KAAKF,WAAWc,UAAU;MAACZ;MAAMa,aAAa,oBAAIC,KAAAA;IAAM,CAAA;EAChE;AACF;AAhBajB;AAAN,IAAMA,iBAAN;;;;;;ACLP,SAAQkB,WAAWC,oBAAmB;;;ACCtC,SAAQC,mBAAkB;AAC1B,SAAQC,WAAAA,gBAAc;AAOf,SAASC,iBAAiBC,SAAgC;AAC/D,SAAO,SAAUC,QAAW;AAC1BC,IAAAA,SAAAA,EAAUD,MAAAA;AACVA,WAAOE,UAAUC,UAAUH;AAC3BA,WAAOE,UAAUH,UAAUA;AAC3BC,WAAOE,UAAUE,cAAc;EACjC;AACF;AAPgBN;AAaT,SAASO,0BAA0BC,UAAe;AACvD,SAAOA,SACJC,OAAOJ,CAAAA,YAAWA,QAAQD,UAAUE,gBAAgB,WAAA,EACpDI,IAAIL,CAAAA,YAAAA;AACH,UAAMJ,UAAUI,QAAQD,UAAUH;AAClC,WAAO;MACL,GAAGA;MACHU,cAAc,8BAAOC,YAAAA;AACnB,cAAMC,WAAWC,Y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I;AACF,cAAMN,KAAKR,OAAAA;MACb,SAASS,OAAO;AACdP,eAAOO,MAAM,wEAAwEA,KAAAA;AACrF,cAAMA;MACR;IACF,CAAA;AAEAG,YAAQG,WAAU;EACpB;AACF;AA9DazB;AAAN,IAAMA,oBAAN;;eACS0B,cAAAA;;;;;;;;AFCT,SAASC,eAAeC,mBAA0BC,SAAiB;AACxE,QAAMC,aAAaC,0BAA0BH,iBAAAA;AAC7C,MAAIC,mCAASG,QAAS,QAAOF;AAE7BG,eAAa;IACXC,gBAAgB;IAChBC,UAAU,MAAO,KAAK;IACtBC,cAAc;IACdC,cAAc,KAAK;IACnBC,MAAM;MACJC,sBAAsBC,UAAU;QAC9BC,MAAM;QACNC,UAAU,KAAK;QACf,MAAMC,QAAQC,QAAQC,SAAO;AAC3B,gBAAMC,WAAWC,aAAYC,iBAAAA;AAC7B,gBAAMF,SAASG,cAAcnB,YAAYe,OAAAA;QAC3C;MACF,CAAA;IACF;EACF,CAAA;AAEA,SAAOf;AACT;AAtBgBH;","names":["TypedSchema","Prop","MigrationSchema","_id","name","completedAt","type","createCollection","Service","MigrationsRepo","collection","createCollection","name","schema","MigrationSchema","idPrefix","indexes","getCompletedMigrationNames","migrations","find","toArray","map","m","saveCompletedMigration","insertOne","completedAt","Date","defineJob","startWorkers","getInstance","Service","MigrationService","options","target","Service","prototype","service","serviceType","getMigrationsFromServices","services","filter","map","runMigration","context","instance","getInstance","getInstance","Inject","Service","logger","MigrationsService","migrationsRepo","getNextMigration","migrationsList","completedNames","getCompletedMigrationNames","migrationExecutable","includes","name","runMigrations","context","next","logger","info","useMongoTransactions","runAsTransaction","runMigration","saveCompletedMigration","func","error","client","collection","session","startSession","withTransaction","endSession","MigrationsRepo","loadMigrations","migrationServices","options","migrations","getMigrationsFromServices","omitJob","startWorkers","cooldownPeriod","lockTime","workersCount","pollInterval","jobs","orionjsRunMigrations","defineJob","type","runEvery","resolve","params","context","instance","getInstance","MigrationsService","runMigrations"]}
1
+ {"version":3,"sources":["../src/Schema.ts","../src/Repo.ts","../src/loadMigrations/index.ts","../src/service/index.ts","../src/MigrationsService.ts"],"sourcesContent":["import {TypedSchema, Prop} from '@orion-js/typed-model'\n\nexport type MigrationId = `scnmg-${string}`\n\n@TypedSchema()\nexport class MigrationSchema {\n @Prop({type: 'string'})\n _id: MigrationId\n\n @Prop()\n name: string\n\n @Prop()\n completedAt: Date\n}\n","import {MongoCollection, Repository, Collection, 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<MigrationSchema>({\n name: 'orionjs.migrations',\n schema: MigrationSchema,\n idPrefix: 'scnmg-',\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({name, completedAt: new Date()})\n }\n}\n","import {defineJob, startWorkers} from '@orion-js/dogs'\nimport {getMigrationsFromServices} from '../service'\nimport {getInstance} from '@orion-js/services'\nimport {MigrationsService} from '../MigrationsService'\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 lockTime: 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\nexport function MigrationService(options: MigrationServiceOptions): ClassDecorator {\n return function (target: any) {\n Service()(target)\n target.prototype.service = target\n target.prototype.options = options\n target.prototype.serviceType = 'migration'\n }\n}\n\nexport type MigrationExecutable = {\n runMigration(context: ExecutionContext): Promise<void>\n} & MigrationServiceOptions\n\nexport function getMigrationsFromServices(services: any[]): MigrationExecutable[] {\n return services\n .filter(service => service.prototype.serviceType === 'migration')\n .map(service => {\n const options = service.prototype.options\n return {\n ...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', error)\n throw error\n }\n })\n\n session.endSession()\n }\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAQ,aAAa,YAAW;AAKzB,IAAM,kBAAN,MAAsB;AAAA,EAE3B;AAAA,EAGA;AAAA,EAGA;AACF;AAPE;AAAA,EADC,KAAK,EAAC,MAAM,SAAQ,CAAC;AAAA,GADX,gBAEX;AAGA;AAAA,EADC,KAAK;AAAA,GAJK,gBAKX;AAGA;AAAA,EADC,KAAK;AAAA,GAPK,gBAQX;AARW,kBAAN;AAAA,EADN,YAAY;AAAA,GACA;;;ACLb,SAAiD,wBAAuB;AAExE,SAAS,eAAe;AAGjB,IAAM,iBAAN,MAAqB;AAAA,EACnB,aAAa,iBAAkC;AAAA,IAClD,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,UAAU;AAAA,IACV,SAAS,CAAC;AAAA,EACZ,CAAC;AAAA,EAEH,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,EAAC,MAAM,aAAa,oBAAI,KAAK,EAAC,CAAC;AAAA,EACjE;AACF;AAhBa,iBAAN;AAAA,EADN,QAAQ;AAAA,GACI;;;ACLb,SAAQ,WAAW,oBAAmB;;;ACCtC,SAAQ,mBAAkB;AAC1B,SAAQ,WAAAA,gBAAc;AAOf,SAAS,iBAAiB,SAAkD;AACjF,SAAO,SAAU,QAAa;AAC5B,IAAAA,SAAQ,EAAE,MAAM;AAChB,WAAO,UAAU,UAAU;AAC3B,WAAO,UAAU,UAAU;AAC3B,WAAO,UAAU,cAAc;AAAA,EACjC;AACF;AAMO,SAAS,0BAA0B,UAAwC;AAChF,SAAO,SACJ,OAAO,aAAW,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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,eAAO,MAAM,wEAAwE,KAAK;AAC1F,cAAM;AAAA,MACR;AAAA,IACF,CAAC;AAED,YAAQ,WAAW;AAAA,EACrB;AACF;AA5DU;AAAA,EADP,OAAO,MAAM,cAAc;AAAA,GADjB,kBAEH;AAFG,oBAAN;AAAA,EADNC,SAAQ;AAAA,GACI;;;AFEN,SAAS,eAAe,mBAA0B,SAAmB;AAC1E,QAAM,aAAa,0BAA0B,iBAAiB;AAC9D,MAAI,mCAAS,QAAS,QAAO;AAE7B,eAAa;AAAA,IACX,gBAAgB;AAAA,IAChB,UAAU,MAAO,KAAK;AAAA;AAAA,IACtB,cAAc;AAAA,IACd,cAAc,KAAK;AAAA,IACnB,MAAM;AAAA,MACJ,sBAAsB,UAAU;AAAA,QAC9B,MAAM;AAAA,QACN,UAAU,KAAK;AAAA,QACf,MAAM,QAAQ,QAAQ,SAAS;AAC7B,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","getInstance","Service","Service","getInstance"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orion-js/migrations",
3
- "version": "4.0.0-next.2",
3
+ "version": "4.0.0-next.3",
4
4
  "main": "./dist/index.cjs",
5
5
  "types": "./dist/index.d.ts",
6
6
  "files": [
@@ -9,12 +9,12 @@
9
9
  "author": "nicolaslopezj",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
- "@orion-js/dogs": "4.0.0-next.2",
13
- "@orion-js/mongodb": "4.0.0-next.2",
14
- "@orion-js/helpers": "4.0.0-next.2",
15
- "@orion-js/services": "4.0.0-next.2",
16
- "@orion-js/typed-model": "4.0.0-next.2",
17
- "@orion-js/logger": "4.0.0-next.2"
12
+ "@orion-js/dogs": "4.0.0-next.3",
13
+ "@orion-js/mongodb": "4.0.0-next.3",
14
+ "@orion-js/services": "4.0.0-next.3",
15
+ "@orion-js/logger": "4.0.0-next.3",
16
+ "@orion-js/typed-model": "4.0.0-next.3",
17
+ "@orion-js/helpers": "4.0.0-next.3"
18
18
  },
19
19
  "devDependencies": {
20
20
  "@types/lodash": "4.14.195",