@astratra/store-mongo 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,6 +80,32 @@ const app = createSaasApp({
80
80
  Les méthodes retournent des objets JavaScript simples via Mongoose `.lean()`
81
81
  ou `.toObject()`, jamais des documents Mongoose vivants.
82
82
 
83
+ ## Migrations
84
+
85
+ Pas un DSL, pas de CLI, pas de diff de schéma — un runner minimal et
86
+ honnête : tu lui donnes du code brut dans l'ordre (création d'index,
87
+ backfill, reformage de documents), il applique une seule fois chaque
88
+ migration non encore vue, suivi par `id` dans une collection dédiée.
89
+
90
+ ```js
91
+ const { createMongoMigrationRunner } = require('@astratra/store-mongo');
92
+
93
+ const runner = createMongoMigrationRunner({ connection });
94
+
95
+ await runner.run([
96
+ { id: '2026-01-01-index-role', up: (conn) => conn.collection('app_users').createIndex({ role: 1 }) }
97
+ ]);
98
+ ```
99
+
100
+ Rejoue `run()` avec la même liste (plus les nouvelles migrations ajoutées
101
+ au fil du temps) à chaque déploiement. MongoDB n'a pas de transactions
102
+ inter-collections sur un déploiement standalone — contrairement au runner
103
+ Postgres, celui-ci n'enveloppe **pas** chaque migration dans une transaction.
104
+ Écris des migrations sûres à marquer comme appliquées même si une étape
105
+ intermédiaire de la même `up` échoue, ou utilise un replica set + session
106
+ si tu as besoin d'atomicité. Pas de `down()` : un rollback de schéma se fait
107
+ via une nouvelle migration qui défait l'ancienne.
108
+
83
109
  ## Cycle de vie de connexion
84
110
 
85
111
  Chemin recommandé : passer une `connection` déjà ouverte par l'application.
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "@astratra/store-mongo",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "MongoDB/Mongoose persistence adapters for Astratra SaaS stores.",
5
+ "engines": {
6
+ "node": ">=20"
7
+ },
5
8
  "main": "src/index.js",
6
9
  "types": "src/index.d.ts",
7
10
  "type": "commonjs",
package/src/index.d.ts CHANGED
@@ -59,3 +59,23 @@ export interface MongoSettingsStore<TSettings extends object = Record<string, un
59
59
 
60
60
  export function createMongoUsersStore<TUser extends MongoUserBase = MongoUser>(options: MongoUsersStoreOptions): MongoUsersStore<TUser>;
61
61
  export function createMongoSettingsStore<TSettings extends object = Record<string, unknown>>(options: MongoStoreOptions): MongoSettingsStore<TSettings>;
62
+
63
+ export interface MongoMigration {
64
+ id: string;
65
+ up(connection: MongoConnectionLike): Awaitable<unknown>;
66
+ }
67
+
68
+ export interface MongoMigrationRunnerOptions {
69
+ connection: MongoConnectionLike;
70
+ /** Defaults to "astratra_migrations". */
71
+ migrationsCollection?: string;
72
+ }
73
+
74
+ export interface MongoMigrationRunner {
75
+ /** IDs already recorded as applied, oldest first. */
76
+ appliedIds(): Promise<string[]>;
77
+ /** Runs whichever of the given migrations aren't applied yet, in order. Not transactional — see the package README. */
78
+ run(migrations: MongoMigration[]): Promise<{ applied: string[] }>;
79
+ }
80
+
81
+ export function createMongoMigrationRunner(options: MongoMigrationRunnerOptions): MongoMigrationRunner;
package/src/index.js CHANGED
@@ -245,5 +245,6 @@ function createMongoSettingsStore(options = {}) {
245
245
 
246
246
  module.exports = {
247
247
  createMongoSettingsStore,
248
- createMongoUsersStore
248
+ createMongoUsersStore,
249
+ ...require('./migrations')
249
250
  };
@@ -0,0 +1,86 @@
1
+ const DEFAULT_MIGRATIONS_COLLECTION = 'astratra_migrations';
2
+
3
+ function assertMigrationsShape(migrations) {
4
+ if (!Array.isArray(migrations)) {
5
+ throw new Error('createMongoMigrationRunner.run requires an array of migrations.');
6
+ }
7
+ const seen = new Set();
8
+ for (const migration of migrations) {
9
+ if (!migration || typeof migration.id !== 'string' || !migration.id) {
10
+ throw new Error('Every migration requires a non-empty string id.');
11
+ }
12
+ if (typeof migration.up !== 'function') {
13
+ throw new Error(`Migration "${migration.id}" requires an up(connection) function.`);
14
+ }
15
+ if (seen.has(migration.id)) {
16
+ throw new Error(`Duplicate migration id "${migration.id}".`);
17
+ }
18
+ seen.add(migration.id);
19
+ }
20
+ }
21
+
22
+ /**
23
+ * A minimal, honest migration runner — not a DSL, not a CLI, not schema
24
+ * diffing. It runs your plain code (index creation, backfills, document
25
+ * reshaping) in order, once each, tracked by id in a ledger collection.
26
+ * Given an array of { id, up(connection) }, applies whichever ids aren't in
27
+ * the ledger yet, in order, recording each as applied before moving to the
28
+ * next. Mongo has no cross-collection transactions on a standalone
29
+ * deployment, so unlike the Postgres runner this does NOT wrap each
30
+ * migration in a transaction — write migrations that are safe to record as
31
+ * applied even if a later step in the same "up" fails partway (or use a
32
+ * replica set + session if you need atomicity).
33
+ *
34
+ * const runner = createMongoMigrationRunner({ connection });
35
+ * await runner.run([
36
+ * { id: '2026-01-01-index-users-role', up: (conn) => conn.collection('astratra_users').createIndex({ role: 1 }) }
37
+ * ]);
38
+ */
39
+ function createMongoMigrationRunner(options = {}) {
40
+ const { connection } = options;
41
+ if (!connection) {
42
+ throw new Error('createMongoMigrationRunner requires options.connection.');
43
+ }
44
+ const collectionName = options.migrationsCollection || DEFAULT_MIGRATIONS_COLLECTION;
45
+
46
+ async function ready() {
47
+ if (connection.readyState === 0 && typeof connection.asPromise === 'function') {
48
+ await connection.asPromise();
49
+ }
50
+ return connection.collection(collectionName);
51
+ }
52
+
53
+ return {
54
+ async appliedIds() {
55
+ const ledger = await ready();
56
+ const docs = await ledger.find({}).sort({ appliedAt: 1 }).toArray();
57
+ return docs.map((doc) => doc.id);
58
+ },
59
+
60
+ async run(migrations) {
61
+ assertMigrationsShape(migrations);
62
+ const ledger = await ready();
63
+
64
+ const alreadyApplied = new Set(await this.appliedIds());
65
+ const applied = [];
66
+
67
+ for (const migration of migrations) {
68
+ if (alreadyApplied.has(migration.id)) continue;
69
+
70
+ try {
71
+ await migration.up(connection);
72
+ await ledger.insertOne({ id: migration.id, appliedAt: new Date() });
73
+ applied.push(migration.id);
74
+ } catch (error) {
75
+ throw new Error(`Migration "${migration.id}" failed: ${error.message}`);
76
+ }
77
+ }
78
+
79
+ return { applied };
80
+ }
81
+ };
82
+ }
83
+
84
+ module.exports = {
85
+ createMongoMigrationRunner
86
+ };