@astratra/store-postgres 1.0.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 +21 -0
- package/README.md +117 -0
- package/package.json +43 -0
- package/src/index.d.ts +60 -0
- package/src/index.js +206 -0
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,117 @@
|
|
|
1
|
+
# @astratra/store-postgres
|
|
2
|
+
|
|
3
|
+
Adapters PostgreSQL réels pour les stores `usersStore` et `settingsStore`
|
|
4
|
+
attendus par `@astratra/saas-kit` — même contrat que `@astratra/store-mongo`,
|
|
5
|
+
moteur différent. Les deux packages sont indépendants ; un projet Astratra
|
|
6
|
+
choisit celui qui correspond à sa base de données.
|
|
7
|
+
|
|
8
|
+
Le package ne change pas `saas-kit` : il fournit juste une implémentation
|
|
9
|
+
persistante du même contrat que les stores mémoire de développement.
|
|
10
|
+
|
|
11
|
+
## Installation
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
npm install @astratra/store-postgres pg
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`pg` est une dépendance peer optionnelle du package. En pratique, une
|
|
18
|
+
application qui gère déjà sa propre connexion Postgres garde son propre
|
|
19
|
+
`Pool`.
|
|
20
|
+
|
|
21
|
+
## Utilisateurs
|
|
22
|
+
|
|
23
|
+
```js
|
|
24
|
+
const { Pool } = require('pg');
|
|
25
|
+
const { createPostgresUsersStore } = require('@astratra/store-postgres');
|
|
26
|
+
|
|
27
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
28
|
+
|
|
29
|
+
const usersStore = createPostgresUsersStore({
|
|
30
|
+
pool,
|
|
31
|
+
usersTable: 'app_users'
|
|
32
|
+
});
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
La table est créée automatiquement au premier usage (`CREATE TABLE IF NOT
|
|
36
|
+
EXISTS`) avec un schéma volontairement souple : `email` et `role` sont des
|
|
37
|
+
colonnes indexées pour les requêtes rapides, mais l'objet utilisateur complet
|
|
38
|
+
(y compris tout champ métier propre à l'application — `name`, `avatar`,
|
|
39
|
+
`tenantId`...) est stocké tel quel dans une colonne `data JSONB`. Aucun schéma
|
|
40
|
+
SQL rigide à maintenir côté application.
|
|
41
|
+
|
|
42
|
+
Par défaut, `email` a un index unique. Pour désactiver cette contrainte :
|
|
43
|
+
|
|
44
|
+
```js
|
|
45
|
+
const usersStore = createPostgresUsersStore({
|
|
46
|
+
pool,
|
|
47
|
+
uniqueEmail: false
|
|
48
|
+
});
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Paramètres
|
|
52
|
+
|
|
53
|
+
```js
|
|
54
|
+
const { createPostgresSettingsStore } = require('@astratra/store-postgres');
|
|
55
|
+
|
|
56
|
+
const settingsStore = createPostgresSettingsStore({
|
|
57
|
+
pool,
|
|
58
|
+
settingsTable: 'app_settings'
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
await settingsStore.set('timezone', 'Europe/Paris');
|
|
62
|
+
const allSettings = await settingsStore.getAll();
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`settingsStore` stocke chaque réglage sous forme `{ key, value JSONB }`.
|
|
66
|
+
|
|
67
|
+
## Avec `@astratra/saas-kit`
|
|
68
|
+
|
|
69
|
+
```js
|
|
70
|
+
const { createSaasApp } = require('@astratra/saas-kit');
|
|
71
|
+
const {
|
|
72
|
+
createPostgresSettingsStore,
|
|
73
|
+
createPostgresUsersStore
|
|
74
|
+
} = require('@astratra/store-postgres');
|
|
75
|
+
|
|
76
|
+
const app = createSaasApp({
|
|
77
|
+
usersStore: createPostgresUsersStore({ pool }),
|
|
78
|
+
settingsStore: createPostgresSettingsStore({ pool }),
|
|
79
|
+
notify,
|
|
80
|
+
verifyPassword
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Les méthodes retournent toujours des objets JavaScript simples (jamais une
|
|
85
|
+
ligne `pg` brute) : `{ ...donnéesJSONB, id }`.
|
|
86
|
+
|
|
87
|
+
## Cycle de vie de connexion
|
|
88
|
+
|
|
89
|
+
Chemin recommandé : passer un `pool` déjà géré par l'application. Dans ce
|
|
90
|
+
mode, l'adapter ne ferme jamais ce pool.
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
const usersStore = createPostgresUsersStore({ pool });
|
|
94
|
+
await usersStore.disconnect(); // no-op pour un pool injecté
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Pour un script ou un petit service autonome, l'adapter peut créer et gérer
|
|
98
|
+
son propre `Pool` via `connectionString`. Dans ce cas, `disconnect()` ferme
|
|
99
|
+
réellement ce pool.
|
|
100
|
+
|
|
101
|
+
```js
|
|
102
|
+
const usersStore = createPostgresUsersStore({
|
|
103
|
+
connectionString: process.env.DATABASE_URL
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
// ...
|
|
107
|
+
await usersStore.disconnect();
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Tests
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
npm test --workspace @astratra/store-postgres
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Les tests utilisent `pg-mem` (moteur SQL compatible Postgres en mémoire),
|
|
117
|
+
donc aucune instance PostgreSQL externe n'est requise.
|
package/package.json
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@astratra/store-postgres",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "PostgreSQL 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
|
+
"postgres",
|
|
23
|
+
"postgresql",
|
|
24
|
+
"saas"
|
|
25
|
+
],
|
|
26
|
+
"license": "MIT",
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public"
|
|
29
|
+
},
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"pg": ">=8"
|
|
32
|
+
},
|
|
33
|
+
"peerDependenciesMeta": {
|
|
34
|
+
"pg": {
|
|
35
|
+
"optional": true
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"jest": "30.4.2",
|
|
40
|
+
"pg": "^8.13.1",
|
|
41
|
+
"pg-mem": "^3.0.5"
|
|
42
|
+
}
|
|
43
|
+
}
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export type Awaitable<T> = T | Promise<T>;
|
|
2
|
+
|
|
3
|
+
export interface PgPoolLike {
|
|
4
|
+
query(text: string, values?: unknown[]): Promise<{ rows: any[] }>;
|
|
5
|
+
end(): Awaitable<void>;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface PostgresStoreOptions {
|
|
9
|
+
pool?: PgPoolLike;
|
|
10
|
+
connectionString?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface PostgresUsersStoreOptions extends PostgresStoreOptions {
|
|
14
|
+
usersTable?: string;
|
|
15
|
+
uniqueEmail?: boolean;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface PostgresSettingsStoreOptions extends PostgresStoreOptions {
|
|
19
|
+
settingsTable?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface PostgresUser {
|
|
23
|
+
id: string;
|
|
24
|
+
email?: string;
|
|
25
|
+
role?: string;
|
|
26
|
+
[key: string]: unknown;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface PostgresUserBase {
|
|
30
|
+
id: string;
|
|
31
|
+
email?: string;
|
|
32
|
+
role?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface UsersListOptions {
|
|
36
|
+
role?: string;
|
|
37
|
+
limit?: number;
|
|
38
|
+
offset?: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface PostgresUsersStore<TUser extends PostgresUserBase = PostgresUser> {
|
|
42
|
+
findByEmail(email: string): Promise<TUser | null>;
|
|
43
|
+
findById(id: string): Promise<TUser | null>;
|
|
44
|
+
create(userData: Partial<TUser> & Record<string, unknown>): Promise<TUser>;
|
|
45
|
+
list(options?: UsersListOptions): Promise<TUser[]>;
|
|
46
|
+
update(id: string, patch: Partial<TUser> & Record<string, unknown>): Promise<TUser | null>;
|
|
47
|
+
disconnect(): Promise<void>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface PostgresSettingsStore<TSettings extends object = Record<string, unknown>> {
|
|
51
|
+
get<TKey extends keyof TSettings & string>(key: TKey): Promise<TSettings[TKey] | null>;
|
|
52
|
+
get(key: string): Promise<unknown | null>;
|
|
53
|
+
set<TKey extends keyof TSettings & string>(key: TKey, value: TSettings[TKey]): Promise<void>;
|
|
54
|
+
set(key: string, value: unknown): Promise<void>;
|
|
55
|
+
getAll(): Promise<Partial<TSettings>>;
|
|
56
|
+
disconnect(): Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function createPostgresUsersStore<TUser extends PostgresUserBase = PostgresUser>(options: PostgresUsersStoreOptions): PostgresUsersStore<TUser>;
|
|
60
|
+
export function createPostgresSettingsStore<TSettings extends object = Record<string, unknown>>(options: PostgresSettingsStoreOptions): PostgresSettingsStore<TSettings>;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
const { randomUUID } = require('crypto');
|
|
2
|
+
|
|
3
|
+
const DEFAULT_USERS_TABLE = 'astratra_users';
|
|
4
|
+
const DEFAULT_SETTINGS_TABLE = 'astratra_settings';
|
|
5
|
+
|
|
6
|
+
function loadPg() {
|
|
7
|
+
try {
|
|
8
|
+
return require('pg');
|
|
9
|
+
} catch (_error) {
|
|
10
|
+
throw new Error('@astratra/store-postgres requires pg. Install pg or pass it from an app that already depends on it.');
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function isValidIdentifier(name) {
|
|
15
|
+
return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function assertValidIdentifier(name, label) {
|
|
19
|
+
if (!isValidIdentifier(name)) {
|
|
20
|
+
throw new Error(`@astratra/store-postgres: invalid ${label} "${name}".`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function createConnectionContext(options = {}) {
|
|
25
|
+
if (options.pool) {
|
|
26
|
+
return { pool: options.pool, managed: false };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if (!options.connectionString) {
|
|
30
|
+
throw new Error('createPostgres store requires options.pool or options.connectionString.');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const { Pool } = loadPg();
|
|
34
|
+
return { pool: new Pool({ connectionString: options.connectionString }), managed: true };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
38
|
+
|
|
39
|
+
function isValidUuid(value) {
|
|
40
|
+
return typeof value === 'string' && UUID_PATTERN.test(value);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isInvalidTextRepresentation(error) {
|
|
44
|
+
return error && error.code === '22P02';
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function mergeUserRow(row) {
|
|
48
|
+
if (!row) return null;
|
|
49
|
+
return { ...row.data, id: row.id };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function createPostgresUsersStore(options = {}) {
|
|
53
|
+
const table = options.usersTable || DEFAULT_USERS_TABLE;
|
|
54
|
+
assertValidIdentifier(table, 'usersTable');
|
|
55
|
+
const uniqueEmail = options.uniqueEmail !== false;
|
|
56
|
+
const context = createConnectionContext(options);
|
|
57
|
+
const { pool } = context;
|
|
58
|
+
|
|
59
|
+
const ready = (async () => {
|
|
60
|
+
await pool.query(`
|
|
61
|
+
CREATE TABLE IF NOT EXISTS ${table} (
|
|
62
|
+
id UUID PRIMARY KEY,
|
|
63
|
+
email TEXT,
|
|
64
|
+
role TEXT,
|
|
65
|
+
data JSONB NOT NULL DEFAULT '{}'::jsonb
|
|
66
|
+
)
|
|
67
|
+
`);
|
|
68
|
+
if (uniqueEmail) {
|
|
69
|
+
await pool.query(`CREATE UNIQUE INDEX IF NOT EXISTS ${table}_email_unique_idx ON ${table} (email)`);
|
|
70
|
+
}
|
|
71
|
+
})();
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
async findByEmail(email) {
|
|
75
|
+
await ready;
|
|
76
|
+
const result = await pool.query(`SELECT id, data FROM ${table} WHERE email = $1 LIMIT 1`, [email]);
|
|
77
|
+
return mergeUserRow(result.rows[0]);
|
|
78
|
+
},
|
|
79
|
+
|
|
80
|
+
async findById(id) {
|
|
81
|
+
await ready;
|
|
82
|
+
if (!isValidUuid(id)) return null;
|
|
83
|
+
try {
|
|
84
|
+
const result = await pool.query(`SELECT id, data FROM ${table} WHERE id = $1 LIMIT 1`, [id]);
|
|
85
|
+
return mergeUserRow(result.rows[0]);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (isInvalidTextRepresentation(error)) return null;
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
},
|
|
91
|
+
|
|
92
|
+
async create(userData) {
|
|
93
|
+
await ready;
|
|
94
|
+
const data = { ...(userData || {}) };
|
|
95
|
+
delete data.id;
|
|
96
|
+
const id = randomUUID();
|
|
97
|
+
const email = data.email ?? null;
|
|
98
|
+
const role = data.role ?? null;
|
|
99
|
+
|
|
100
|
+
const result = await pool.query(
|
|
101
|
+
`INSERT INTO ${table} (id, email, role, data) VALUES ($1, $2, $3, $4) RETURNING id, data`,
|
|
102
|
+
[id, email, role, JSON.stringify(data)]
|
|
103
|
+
);
|
|
104
|
+
return mergeUserRow(result.rows[0]);
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
async list({ role, limit = 50, offset = 0 } = {}) {
|
|
108
|
+
await ready;
|
|
109
|
+
const safeLimit = Math.max(Number(limit) || 50, 0);
|
|
110
|
+
const safeOffset = Math.max(Number(offset) || 0, 0);
|
|
111
|
+
|
|
112
|
+
const result = role
|
|
113
|
+
? await pool.query(
|
|
114
|
+
`SELECT id, data FROM ${table} WHERE role = $1 ORDER BY id LIMIT $2 OFFSET $3`,
|
|
115
|
+
[role, safeLimit, safeOffset]
|
|
116
|
+
)
|
|
117
|
+
: await pool.query(
|
|
118
|
+
`SELECT id, data FROM ${table} ORDER BY id LIMIT $1 OFFSET $2`,
|
|
119
|
+
[safeLimit, safeOffset]
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
return result.rows.map(mergeUserRow);
|
|
123
|
+
},
|
|
124
|
+
|
|
125
|
+
async update(id, patch) {
|
|
126
|
+
await ready;
|
|
127
|
+
if (!isValidUuid(id)) return null;
|
|
128
|
+
const safePatch = { ...(patch || {}) };
|
|
129
|
+
delete safePatch.id;
|
|
130
|
+
|
|
131
|
+
try {
|
|
132
|
+
const existing = await pool.query(`SELECT id, data FROM ${table} WHERE id = $1 LIMIT 1`, [id]);
|
|
133
|
+
if (existing.rows.length === 0) return null;
|
|
134
|
+
|
|
135
|
+
const mergedData = { ...existing.rows[0].data, ...safePatch };
|
|
136
|
+
const email = mergedData.email ?? null;
|
|
137
|
+
const role = mergedData.role ?? null;
|
|
138
|
+
|
|
139
|
+
const result = await pool.query(
|
|
140
|
+
`UPDATE ${table} SET email = $1, role = $2, data = $3 WHERE id = $4 RETURNING id, data`,
|
|
141
|
+
[email, role, JSON.stringify(mergedData), id]
|
|
142
|
+
);
|
|
143
|
+
return mergeUserRow(result.rows[0]);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
if (isInvalidTextRepresentation(error)) return null;
|
|
146
|
+
throw error;
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
|
|
150
|
+
async disconnect() {
|
|
151
|
+
if (context.managed) {
|
|
152
|
+
await pool.end();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function createPostgresSettingsStore(options = {}) {
|
|
159
|
+
const table = options.settingsTable || DEFAULT_SETTINGS_TABLE;
|
|
160
|
+
assertValidIdentifier(table, 'settingsTable');
|
|
161
|
+
const context = createConnectionContext(options);
|
|
162
|
+
const { pool } = context;
|
|
163
|
+
|
|
164
|
+
const ready = (async () => {
|
|
165
|
+
await pool.query(`
|
|
166
|
+
CREATE TABLE IF NOT EXISTS ${table} (
|
|
167
|
+
key TEXT PRIMARY KEY,
|
|
168
|
+
value JSONB
|
|
169
|
+
)
|
|
170
|
+
`);
|
|
171
|
+
})();
|
|
172
|
+
|
|
173
|
+
return {
|
|
174
|
+
async get(key) {
|
|
175
|
+
await ready;
|
|
176
|
+
const result = await pool.query(`SELECT value FROM ${table} WHERE key = $1 LIMIT 1`, [key]);
|
|
177
|
+
return result.rows.length > 0 ? result.rows[0].value : null;
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
async set(key, value) {
|
|
181
|
+
await ready;
|
|
182
|
+
await pool.query(
|
|
183
|
+
`INSERT INTO ${table} (key, value) VALUES ($1, $2)
|
|
184
|
+
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value`,
|
|
185
|
+
[key, JSON.stringify(value)]
|
|
186
|
+
);
|
|
187
|
+
},
|
|
188
|
+
|
|
189
|
+
async getAll() {
|
|
190
|
+
await ready;
|
|
191
|
+
const result = await pool.query(`SELECT key, value FROM ${table}`);
|
|
192
|
+
return Object.fromEntries(result.rows.map((row) => [row.key, row.value]));
|
|
193
|
+
},
|
|
194
|
+
|
|
195
|
+
async disconnect() {
|
|
196
|
+
if (context.managed) {
|
|
197
|
+
await pool.end();
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
module.exports = {
|
|
204
|
+
createPostgresSettingsStore,
|
|
205
|
+
createPostgresUsersStore
|
|
206
|
+
};
|