@astratra/store-mongo 1.0.2 → 1.2.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/LICENSE +1 -1
- package/README.md +37 -0
- package/package.json +4 -4
- package/src/index.d.ts +20 -0
- package/src/index.js +6 -5
- package/src/migrations.js +86 -0
package/LICENSE
CHANGED
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.
|
|
@@ -108,6 +134,17 @@ await usersStore.disconnect();
|
|
|
108
134
|
npm test --workspace @astratra/store-mongo
|
|
109
135
|
```
|
|
110
136
|
|
|
137
|
+
Sous Jest, Mongoose 9 (pilote MongoDB 7) ne se connecte pas tel quel : le
|
|
138
|
+
pilote charge `os` par un `import()` que Jest refuse, et le serveur répond
|
|
139
|
+
« Missing required sub-document 'driver' ». Donnez-lui `os` dans les options
|
|
140
|
+
de connexion de vos tests :
|
|
141
|
+
|
|
142
|
+
```js
|
|
143
|
+
mongoose.createConnection(uri, { runtimeAdapters: { os: require('os') } });
|
|
144
|
+
// ou, quand l'adapter ouvre la connexion lui-même :
|
|
145
|
+
createMongoUsersStore({ uri, connectionOptions: { runtimeAdapters: { os: require('os') } } });
|
|
146
|
+
```
|
|
147
|
+
|
|
111
148
|
Les tests utilisent `mongodb-memory-server`, donc aucune instance MongoDB
|
|
112
149
|
externe n'est requise. Au premier lancement, le binaire MongoDB peut être
|
|
113
150
|
téléchargé par `mongodb-memory-server`.
|
package/package.json
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/store-mongo",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "MongoDB/Mongoose persistence adapters for Astratra SaaS stores.",
|
|
5
5
|
"engines": {
|
|
6
|
-
"node": ">=
|
|
6
|
+
"node": ">=22"
|
|
7
7
|
},
|
|
8
8
|
"main": "src/index.js",
|
|
9
9
|
"types": "src/index.d.ts",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
},
|
|
41
41
|
"devDependencies": {
|
|
42
42
|
"jest": "30.4.2",
|
|
43
|
-
"mongodb-memory-server": "^
|
|
44
|
-
"mongoose": "^
|
|
43
|
+
"mongodb-memory-server": "^11.3.0",
|
|
44
|
+
"mongoose": "^9.12.1"
|
|
45
45
|
}
|
|
46
46
|
}
|
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
|
@@ -4,8 +4,8 @@ const DEFAULT_SETTINGS_COLLECTION = 'astratra_settings';
|
|
|
4
4
|
function loadMongoose() {
|
|
5
5
|
try {
|
|
6
6
|
return require('mongoose');
|
|
7
|
-
} catch (
|
|
8
|
-
throw new Error('@astratra/store-mongo requires mongoose. Install mongoose or pass it from an app that already depends on it.');
|
|
7
|
+
} catch (error) {
|
|
8
|
+
throw new Error('@astratra/store-mongo requires mongoose. Install mongoose or pass it from an app that already depends on it.', { cause: error });
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
11
|
|
|
@@ -179,7 +179,7 @@ function createMongoUsersStore(options = {}) {
|
|
|
179
179
|
|
|
180
180
|
try {
|
|
181
181
|
const user = await User.findByIdAndUpdate(id, { $set: data }, {
|
|
182
|
-
|
|
182
|
+
returnDocument: 'after',
|
|
183
183
|
runValidators: false
|
|
184
184
|
}).lean();
|
|
185
185
|
return stripMongoFields(user);
|
|
@@ -224,7 +224,7 @@ function createMongoSettingsStore(options = {}) {
|
|
|
224
224
|
const setting = await Setting.findOneAndUpdate(
|
|
225
225
|
{ key },
|
|
226
226
|
{ $set: { key, value } },
|
|
227
|
-
{ upsert: true,
|
|
227
|
+
{ upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }
|
|
228
228
|
).lean();
|
|
229
229
|
return setting.value;
|
|
230
230
|
},
|
|
@@ -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}`, { cause: error });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return { applied };
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
module.exports = {
|
|
85
|
+
createMongoMigrationRunner
|
|
86
|
+
};
|