@astratra/store-mongo 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Astratra
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/README.md ADDED
@@ -0,0 +1,113 @@
1
+ # @astratra/store-mongo
2
+
3
+ Adapters MongoDB/Mongoose reels pour les stores `usersStore` et
4
+ `settingsStore` attendus par `@astratra/saas-kit`.
5
+
6
+ Le package ne change pas `saas-kit` : il fournit juste une implémentation
7
+ persistante du même contrat que les stores mémoire de développement.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ npm install @astratra/store-mongo mongoose
13
+ ```
14
+
15
+ `mongoose` est une dependance peer optionnelle du package. En pratique, une
16
+ application qui utilise déjà MongoDB garde sa propre dépendance et sa propre
17
+ connexion.
18
+
19
+ ## Utilisateurs
20
+
21
+ ```js
22
+ const mongoose = require('mongoose');
23
+ const { createMongoUsersStore } = require('@astratra/store-mongo');
24
+
25
+ await mongoose.connect(process.env.MONGODB_URI);
26
+
27
+ const usersStore = createMongoUsersStore({
28
+ connection: mongoose.connection,
29
+ collection: 'app_users'
30
+ });
31
+ ```
32
+
33
+ Le schema est volontairement permissif : `email` et `role` sont connus, mais
34
+ `strict: false` laisse passer les champs métier de l'application consommatrice
35
+ comme `name`, `avatar`, `tenantId` ou `clinicId`.
36
+
37
+ Par défaut, `email` a un index unique. Pour désactiver cette contrainte :
38
+
39
+ ```js
40
+ const usersStore = createMongoUsersStore({
41
+ connection: mongoose.connection,
42
+ uniqueEmail: false
43
+ });
44
+ ```
45
+
46
+ ## Parametres
47
+
48
+ ```js
49
+ const { createMongoSettingsStore } = require('@astratra/store-mongo');
50
+
51
+ const settingsStore = createMongoSettingsStore({
52
+ connection: mongoose.connection,
53
+ collection: 'app_settings'
54
+ });
55
+
56
+ await settingsStore.set('timezone', 'Europe/Paris');
57
+ const allSettings = await settingsStore.getAll();
58
+ ```
59
+
60
+ `settingsStore` stocke chaque réglage sous forme `{ key, value }`, avec
61
+ `value` en `Schema.Types.Mixed`.
62
+
63
+ ## Avec `@astratra/saas-kit`
64
+
65
+ ```js
66
+ const { createSaasApp } = require('@astratra/saas-kit');
67
+ const {
68
+ createMongoSettingsStore,
69
+ createMongoUsersStore
70
+ } = require('@astratra/store-mongo');
71
+
72
+ const app = createSaasApp({
73
+ usersStore: createMongoUsersStore({ connection: mongoose.connection }),
74
+ settingsStore: createMongoSettingsStore({ connection: mongoose.connection }),
75
+ notify,
76
+ verifyPassword
77
+ });
78
+ ```
79
+
80
+ Les méthodes retournent des objets JavaScript simples via Mongoose `.lean()`
81
+ ou `.toObject()`, jamais des documents Mongoose vivants.
82
+
83
+ ## Cycle de vie de connexion
84
+
85
+ Chemin recommandé : passer une `connection` déjà ouverte par l'application.
86
+ Dans ce mode, l'adapter ne ferme pas MongoDB.
87
+
88
+ ```js
89
+ const usersStore = createMongoUsersStore({ connection: mongoose.connection });
90
+ await usersStore.disconnect(); // no-op pour une connexion injectée
91
+ ```
92
+
93
+ Pour un script ou un petit service autonome, l'adapter peut ouvrir sa propre
94
+ connexion avec `uri`. Dans ce cas, `disconnect()` ferme cette connexion.
95
+
96
+ ```js
97
+ const usersStore = createMongoUsersStore({
98
+ uri: process.env.MONGODB_URI
99
+ });
100
+
101
+ // ...
102
+ await usersStore.disconnect();
103
+ ```
104
+
105
+ ## Tests
106
+
107
+ ```bash
108
+ npm test --workspace @astratra/store-mongo
109
+ ```
110
+
111
+ Les tests utilisent `mongodb-memory-server`, donc aucune instance MongoDB
112
+ externe n'est requise. Au premier lancement, le binaire MongoDB peut être
113
+ téléchargé par `mongodb-memory-server`.
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@astratra/store-mongo",
3
+ "version": "0.1.0",
4
+ "description": "MongoDB/Mongoose persistence adapters for Astratra SaaS stores.",
5
+ "main": "src/index.js",
6
+ "types": "src/index.d.ts",
7
+ "type": "commonjs",
8
+ "files": [
9
+ "src"
10
+ ],
11
+ "scripts": {
12
+ "test": "jest"
13
+ },
14
+ "jest": {
15
+ "testMatch": [
16
+ "**/__tests__/**/*.test.js"
17
+ ],
18
+ "testTimeout": 60000
19
+ },
20
+ "keywords": [
21
+ "astratra",
22
+ "mongodb",
23
+ "mongoose",
24
+ "saas"
25
+ ],
26
+ "license": "MIT",
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "peerDependencies": {
31
+ "mongoose": ">=8"
32
+ },
33
+ "peerDependenciesMeta": {
34
+ "mongoose": {
35
+ "optional": true
36
+ }
37
+ },
38
+ "devDependencies": {
39
+ "jest": "30.4.2",
40
+ "mongodb-memory-server": "^10.2.0",
41
+ "mongoose": "^8.17.0"
42
+ }
43
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,59 @@
1
+ export type Awaitable<T> = T | Promise<T>;
2
+
3
+ export interface MongoConnectionLike {
4
+ models: Record<string, unknown>;
5
+ model(name: string, schema: unknown, collection?: string): unknown;
6
+ close(): Awaitable<void>;
7
+ asPromise?(): Promise<unknown>;
8
+ }
9
+
10
+ export interface MongoStoreOptions {
11
+ connection?: MongoConnectionLike;
12
+ uri?: string;
13
+ connectionOptions?: Record<string, unknown>;
14
+ collection?: string;
15
+ }
16
+
17
+ export interface MongoUsersStoreOptions extends MongoStoreOptions {
18
+ uniqueEmail?: boolean;
19
+ }
20
+
21
+ export interface MongoUser {
22
+ id: string;
23
+ email?: string;
24
+ role?: string;
25
+ [key: string]: unknown;
26
+ }
27
+
28
+ export interface MongoUserBase {
29
+ id: string;
30
+ email?: string;
31
+ role?: string;
32
+ }
33
+
34
+ export interface UsersListOptions {
35
+ role?: string;
36
+ limit?: number;
37
+ offset?: number;
38
+ }
39
+
40
+ export interface MongoUsersStore<TUser extends MongoUserBase = MongoUser> {
41
+ findByEmail(email: string): Promise<TUser | null>;
42
+ findById(id: string): Promise<TUser | null>;
43
+ create(userData: Partial<TUser> & Record<string, unknown>): Promise<TUser>;
44
+ list(options?: UsersListOptions): Promise<TUser[]>;
45
+ update(id: string, patch: Partial<TUser> & Record<string, unknown>): Promise<TUser | null>;
46
+ disconnect(): Promise<void>;
47
+ }
48
+
49
+ export interface MongoSettingsStore<TSettings extends object = Record<string, unknown>> {
50
+ get<TKey extends keyof TSettings & string>(key: TKey): Promise<TSettings[TKey] | null>;
51
+ get(key: string): Promise<unknown | null>;
52
+ set<TKey extends keyof TSettings & string>(key: TKey, value: TSettings[TKey]): Promise<void>;
53
+ set(key: string, value: unknown): Promise<void>;
54
+ getAll(): Promise<Partial<TSettings>>;
55
+ disconnect(): Promise<void>;
56
+ }
57
+
58
+ export function createMongoUsersStore<TUser extends MongoUserBase = MongoUser>(options: MongoUsersStoreOptions): MongoUsersStore<TUser>;
59
+ export function createMongoSettingsStore<TSettings extends object = Record<string, unknown>>(options: MongoStoreOptions): MongoSettingsStore<TSettings>;
package/src/index.js ADDED
@@ -0,0 +1,222 @@
1
+ const DEFAULT_USERS_COLLECTION = 'astratra_users';
2
+ const DEFAULT_SETTINGS_COLLECTION = 'astratra_settings';
3
+
4
+ function loadMongoose() {
5
+ try {
6
+ return require('mongoose');
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.');
9
+ }
10
+ }
11
+
12
+ function modelName(prefix, collection) {
13
+ const safeCollection = String(collection).replace(/[^a-zA-Z0-9_]/g, '_');
14
+ return `Astratra${prefix}_${safeCollection}`;
15
+ }
16
+
17
+ function createConnectionContext(options = {}) {
18
+ const mongoose = loadMongoose();
19
+ if (options.connection) {
20
+ return {
21
+ mongoose,
22
+ connection: options.connection,
23
+ managed: false,
24
+ ready: Promise.resolve()
25
+ };
26
+ }
27
+
28
+ if (!options.uri) {
29
+ throw new Error('createMongo store requires options.connection or options.uri.');
30
+ }
31
+
32
+ const connection = mongoose.createConnection(options.uri, options.connectionOptions || {});
33
+ return {
34
+ mongoose,
35
+ connection,
36
+ managed: true,
37
+ ready: typeof connection.asPromise === 'function' ? connection.asPromise() : Promise.resolve(connection)
38
+ };
39
+ }
40
+
41
+ function getModel(connection, name, schema, collection) {
42
+ if (connection.models[name]) {
43
+ return connection.models[name];
44
+ }
45
+ return connection.model(name, schema, collection);
46
+ }
47
+
48
+ function stripMongoFields(doc) {
49
+ if (!doc) return null;
50
+ const plain = { ...doc };
51
+ if (plain.id === undefined && plain._id !== undefined) {
52
+ plain.id = String(plain._id);
53
+ }
54
+ delete plain._id;
55
+ delete plain.__v;
56
+ return plain;
57
+ }
58
+
59
+ function isDuplicateKeyError(error) {
60
+ return error && (error.code === 11000 || error.code === 11001);
61
+ }
62
+
63
+ function nullForCastError(error) {
64
+ if (error && (error.name === 'CastError' || error.name === 'BSONError')) {
65
+ return null;
66
+ }
67
+ throw error;
68
+ }
69
+
70
+ function safeNumber(value, fallback) {
71
+ const number = Number(value);
72
+ return Number.isFinite(number) ? Math.max(number, 0) : fallback;
73
+ }
74
+
75
+ function initModel(Model) {
76
+ if (!Model.astratraInitPromise) {
77
+ Model.astratraInitPromise = Model.init();
78
+ }
79
+ return Model.astratraInitPromise;
80
+ }
81
+
82
+ function createMongoUsersStore(options = {}) {
83
+ const collection = options.collection || DEFAULT_USERS_COLLECTION;
84
+ const uniqueEmail = options.uniqueEmail !== false;
85
+ const context = createConnectionContext(options);
86
+ const schema = new context.mongoose.Schema({
87
+ email: { type: String, index: uniqueEmail ? { unique: true } : true },
88
+ role: String
89
+ }, {
90
+ strict: false
91
+ });
92
+ const User = getModel(context.connection, modelName('User', collection), schema, collection);
93
+
94
+ async function ready() {
95
+ await context.ready;
96
+ if (uniqueEmail) {
97
+ await initModel(User);
98
+ }
99
+ }
100
+
101
+ return {
102
+ async findByEmail(email) {
103
+ await ready();
104
+ const user = await User.findOne({ email }).lean();
105
+ return stripMongoFields(user);
106
+ },
107
+
108
+ async findById(id) {
109
+ await ready();
110
+ try {
111
+ const user = await User.findById(id).lean();
112
+ return stripMongoFields(user);
113
+ } catch (error) {
114
+ return nullForCastError(error);
115
+ }
116
+ },
117
+
118
+ async create(userData) {
119
+ await ready();
120
+ const data = { ...(userData || {}) };
121
+ if (data.id !== undefined && data._id === undefined && context.mongoose.isValidObjectId(data.id)) {
122
+ data._id = data.id;
123
+ delete data.id;
124
+ }
125
+
126
+ try {
127
+ const user = await User.create(data);
128
+ return stripMongoFields(user.toObject());
129
+ } catch (error) {
130
+ if (uniqueEmail && isDuplicateKeyError(error)) {
131
+ throw error;
132
+ }
133
+ throw error;
134
+ }
135
+ },
136
+
137
+ async list({ role, limit = 50, offset = 0 } = {}) {
138
+ await ready();
139
+ const query = role ? { role } : {};
140
+ const users = await User.find(query)
141
+ .sort({ _id: 1 })
142
+ .skip(safeNumber(offset, 0))
143
+ .limit(safeNumber(limit, 50))
144
+ .lean();
145
+ return users.map(stripMongoFields);
146
+ },
147
+
148
+ async update(id, patch) {
149
+ await ready();
150
+ const data = { ...(patch || {}) };
151
+ delete data.id;
152
+ delete data._id;
153
+
154
+ try {
155
+ const user = await User.findByIdAndUpdate(id, { $set: data }, {
156
+ new: true,
157
+ runValidators: false
158
+ }).lean();
159
+ return stripMongoFields(user);
160
+ } catch (error) {
161
+ return nullForCastError(error);
162
+ }
163
+ },
164
+
165
+ async disconnect() {
166
+ if (context.managed) {
167
+ await context.connection.close();
168
+ }
169
+ }
170
+ };
171
+ }
172
+
173
+ function createMongoSettingsStore(options = {}) {
174
+ const collection = options.collection || DEFAULT_SETTINGS_COLLECTION;
175
+ const context = createConnectionContext(options);
176
+ const schema = new context.mongoose.Schema({
177
+ key: { type: String, unique: true, index: true },
178
+ value: context.mongoose.Schema.Types.Mixed
179
+ }, {
180
+ strict: false
181
+ });
182
+ const Setting = getModel(context.connection, modelName('Setting', collection), schema, collection);
183
+
184
+ async function ready() {
185
+ await context.ready;
186
+ await initModel(Setting);
187
+ }
188
+
189
+ return {
190
+ async get(key) {
191
+ await ready();
192
+ const setting = await Setting.findOne({ key }).lean();
193
+ return setting ? setting.value : null;
194
+ },
195
+
196
+ async set(key, value) {
197
+ await ready();
198
+ await Setting.findOneAndUpdate(
199
+ { key },
200
+ { $set: { key, value } },
201
+ { upsert: true, new: true, setDefaultsOnInsert: true }
202
+ ).lean();
203
+ },
204
+
205
+ async getAll() {
206
+ await ready();
207
+ const settings = await Setting.find({}).lean();
208
+ return Object.fromEntries(settings.map((setting) => [setting.key, setting.value]));
209
+ },
210
+
211
+ async disconnect() {
212
+ if (context.managed) {
213
+ await context.connection.close();
214
+ }
215
+ }
216
+ };
217
+ }
218
+
219
+ module.exports = {
220
+ createMongoSettingsStore,
221
+ createMongoUsersStore
222
+ };