@jcbuisson/express-x-drizzle 1.0.5 → 1.0.8
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/CLAUDE.md +29 -0
- package/package.json +19 -10
- package/src/drizzle-plugins.mjs +89 -124
package/CLAUDE.md
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
+
|
|
5
|
+
## Package
|
|
6
|
+
|
|
7
|
+
`@jcbuisson/express-x-drizzle` is an ESM-only NPM package (no build step). The single source file is `src/drizzle-plugins.mjs`; the package root re-exports it as `drizzle-plugins.mjs` via the `"main"` field in `package.json`.
|
|
8
|
+
|
|
9
|
+
No test runner or linter is configured. There are no build, test, or lint commands.
|
|
10
|
+
|
|
11
|
+
To publish: `npm publish` (package is public, not private).
|
|
12
|
+
|
|
13
|
+
## Architecture
|
|
14
|
+
|
|
15
|
+
The library exports one function: `drizzleOfflinePlugin(app, db, metadata, models)`.
|
|
16
|
+
|
|
17
|
+
**Parameters:**
|
|
18
|
+
- `app` — an `express-x` application instance (from `@jcbuisson/express-x`)
|
|
19
|
+
- `db` — a Drizzle ORM database instance
|
|
20
|
+
- `metadata` — a Drizzle table schema used to store per-record timestamps (`uid`, `created_at`, `updated_at`, `deleted_at`)
|
|
21
|
+
- `models` — array of Drizzle table schemas to expose as services
|
|
22
|
+
|
|
23
|
+
**What it does:**
|
|
24
|
+
|
|
25
|
+
1. **Per-model services** — For each table in `models`, registers an `express-x` service named after the table. Each service exposes: `findUnique`, `findMany`, `createWithMeta`, `updateWithMeta`, `deleteWithMeta`. All mutation methods write to both the model table and the `metadata` table inside a transaction, keeping timestamps in sync.
|
|
26
|
+
|
|
27
|
+
2. **`sync` service** — Implements an offline-first reconciliation algorithm. The client sends its local metadata dictionary (`{ uid → { created_at, updated_at, deleted_at } }`) plus a `cutoffDate`. The server computes set intersections between client UIDs and database UIDs, then determines add/update/delete operations for both sides. A `Mutex` (from `express-x`) serializes concurrent sync calls globally. The return value tells the client which records to add, update, or delete locally, and which UIDs the client should push to the database with full data.
|
|
28
|
+
|
|
29
|
+
**Key invariant:** The sync algorithm compares `updated_at` (falling back to `created_at`) timestamps to decide which side wins a conflict — the most recently updated side wins. Records marked `deleted_at` on the client trigger a soft-delete propagation to the database.
|
package/package.json
CHANGED
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jcbuisson/express-x-drizzle",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "",
|
|
3
|
+
"version": "1.0.8",
|
|
4
|
+
"description": "Drizzle ORM plugins for express-x framework",
|
|
5
5
|
"main": "src/drizzle-plugins.mjs",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"private": false,
|
|
8
|
-
"publishConfig": {
|
|
9
|
-
"access": "public"
|
|
8
|
+
"publishConfig": {
|
|
9
|
+
"access": "public"
|
|
10
10
|
},
|
|
11
11
|
"engines": {
|
|
12
12
|
"node": ">= 14.0.0",
|
|
13
13
|
"npm": ">= 6.0.0"
|
|
14
14
|
},
|
|
15
|
+
"imports": {
|
|
16
|
+
"#root/*": "./*"
|
|
17
|
+
},
|
|
15
18
|
"homepage": "",
|
|
16
19
|
"repository": {
|
|
17
20
|
"type": "git",
|
|
@@ -21,14 +24,20 @@
|
|
|
21
24
|
"license": "MIT",
|
|
22
25
|
"bugs": "",
|
|
23
26
|
"keywords": [],
|
|
24
|
-
"scripts": {
|
|
25
|
-
"dev": "",
|
|
26
|
-
"test": ""
|
|
27
|
-
},
|
|
27
|
+
"scripts": {},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@jcbuisson/express-x": "^3.0.
|
|
29
|
+
"@jcbuisson/express-x": "^3.0.5",
|
|
30
|
+
"@jcbuisson/express-x-client": "^3.0.5",
|
|
31
|
+
"@vueuse/core": "^14.3.0",
|
|
32
|
+
"dexie": "^4.4.2",
|
|
33
|
+
"drizzle-orm": "^0.45.2",
|
|
34
|
+
"fake-indexeddb": "^6.2.5",
|
|
35
|
+
"rxjs": "^7.8.2",
|
|
36
|
+
"socket.io-client": "^4.8.3",
|
|
37
|
+
"uuid": "^14.0.0"
|
|
30
38
|
},
|
|
31
39
|
"devDependencies": {
|
|
32
|
-
|
|
40
|
+
"@electric-sql/pglite": "^0.4.5",
|
|
41
|
+
"tsx": "^4.22.1"
|
|
33
42
|
}
|
|
34
43
|
}
|
package/src/drizzle-plugins.mjs
CHANGED
|
@@ -1,24 +1,33 @@
|
|
|
1
|
-
import
|
|
2
|
-
import { createServer } from "http"
|
|
3
|
-
import { Server } from "socket.io"
|
|
4
|
-
import bcrypt from 'bcryptjs'
|
|
1
|
+
import { and, eq, gt, gte, lt, lte, isNull, getTableName } from "drizzle-orm";
|
|
5
2
|
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
import { metadata } from '#root/src/db/schema.js';
|
|
9
|
-
import { Mutex, truncateString } from '@jcbuisson/express-x'
|
|
3
|
+
import { Mutex, truncateString, computeSyncResult } from '@jcbuisson/express-x'
|
|
10
4
|
|
|
11
5
|
|
|
12
6
|
////////////////////////// UTILITIES //////////////////////////
|
|
13
7
|
|
|
14
|
-
function whereToDrizzleFilters(table,
|
|
15
|
-
const conditions = Object.entries(
|
|
8
|
+
function whereToDrizzleFilters(table, where) {
|
|
9
|
+
const conditions = Object.entries(where)
|
|
16
10
|
.filter(([_, value]) => value !== undefined)
|
|
17
|
-
.map(([key, value]) =>
|
|
11
|
+
.map(([key, value]) => {
|
|
12
|
+
if (value === null) return isNull(table[key])
|
|
13
|
+
if (typeof value === 'object') {
|
|
14
|
+
// Collect ALL range bounds — a compound { gte:1, lte:10 } needs both
|
|
15
|
+
const bounds = []
|
|
16
|
+
if ('gte' in value) bounds.push(gte(table[key], value.gte))
|
|
17
|
+
if ('gt' in value) bounds.push(gt(table[key], value.gt))
|
|
18
|
+
if ('lte' in value) bounds.push(lte(table[key], value.lte))
|
|
19
|
+
if ('lt' in value) bounds.push(lt(table[key], value.lt))
|
|
20
|
+
if (bounds.length > 0) return and(...bounds)
|
|
21
|
+
}
|
|
22
|
+
return eq(table[key], value)
|
|
23
|
+
})
|
|
18
24
|
return conditions.length ? and(...conditions) : undefined;
|
|
19
25
|
}
|
|
20
26
|
|
|
21
27
|
|
|
28
|
+
// DOIT FAIRE UN ROLLBACK EN CAS D'ERREUR SERVEUR (EX: ERREUR SÉMANTIQUE TYPE PB CLÉ ÉTRANGÈRE OU AUTRE)
|
|
29
|
+
|
|
30
|
+
|
|
22
31
|
////////////////////////// DRIZZLE OFFLINE PLUGIN //////////////////////////
|
|
23
32
|
|
|
24
33
|
export function drizzleOfflinePlugin(app, db, metadata, models) {
|
|
@@ -39,154 +48,110 @@ export function drizzleOfflinePlugin(app, db, metadata, models) {
|
|
|
39
48
|
},
|
|
40
49
|
|
|
41
50
|
createWithMeta: async (uid, data, created_at) => {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
51
|
+
const ts = new Date(created_at)
|
|
52
|
+
return await db.transaction(async (tx) => {
|
|
53
|
+
// Upsert: if the model row already exists (e.g. a concurrent createWithMeta
|
|
54
|
+
// from the direct create() path landed before the sync's addDatabase step),
|
|
55
|
+
// update it instead of throwing a PK conflict that would rollback the
|
|
56
|
+
// client's Dexie record.
|
|
57
|
+
const [value] = await tx.insert(model)
|
|
58
|
+
.values({ uid, ...data })
|
|
59
|
+
.onConflictDoUpdate({ target: model.uid, set: data })
|
|
60
|
+
.returning();
|
|
61
|
+
// Upsert metadata: handles re-creation after a prior deleteWithMeta.
|
|
62
|
+
const [meta] = await tx.insert(metadata)
|
|
63
|
+
.values({ uid, created_at: ts })
|
|
64
|
+
.onConflictDoUpdate({
|
|
65
|
+
target: metadata.uid,
|
|
66
|
+
set: { created_at: ts, deleted_at: null, updated_at: null },
|
|
67
|
+
})
|
|
68
|
+
.returning();
|
|
45
69
|
return [value, meta]
|
|
46
70
|
})
|
|
47
71
|
},
|
|
48
|
-
|
|
72
|
+
|
|
49
73
|
updateWithMeta: async (uid, data, updated_at) => {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
const
|
|
74
|
+
const ts = updated_at ? new Date(updated_at) : null
|
|
75
|
+
return await db.transaction(async (tx) => {
|
|
76
|
+
const [value] = await tx.update(model).set(data).where(eq(model.uid, uid)).returning();
|
|
77
|
+
// Upsert metadata: if the row is missing (data-integrity gap where the
|
|
78
|
+
// model row exists but no metadata row), create it so the loop stops.
|
|
79
|
+
const [meta] = await tx.insert(metadata)
|
|
80
|
+
.values({ uid, updated_at: ts })
|
|
81
|
+
.onConflictDoUpdate({ target: metadata.uid, set: { updated_at: ts } })
|
|
82
|
+
.returning();
|
|
53
83
|
return [value, meta]
|
|
54
84
|
})
|
|
55
85
|
},
|
|
56
|
-
|
|
86
|
+
|
|
57
87
|
deleteWithMeta: async (uid, deleted_at) => {
|
|
58
|
-
db.transaction(async (tx) => {
|
|
59
|
-
const value = await tx.delete(model).where(eq(model.uid, uid)).returning();
|
|
60
|
-
const meta = await tx.update(metadata).set({ deleted_at }).where(eq(metadata.uid, uid)).returning();
|
|
88
|
+
return await db.transaction(async (tx) => {
|
|
89
|
+
const [value] = await tx.delete(model).where(eq(model.uid, uid)).returning();
|
|
90
|
+
const [meta] = await tx.update(metadata).set({ deleted_at: new Date(deleted_at) }).where(eq(metadata.uid, uid)).returning();
|
|
61
91
|
return [value, meta]
|
|
62
92
|
})
|
|
63
93
|
},
|
|
64
94
|
})
|
|
65
95
|
}
|
|
66
96
|
|
|
67
|
-
const
|
|
97
|
+
const syncMutexes = new Map()
|
|
68
98
|
|
|
69
99
|
// add a synchronization service
|
|
70
100
|
app.createService('sync', {
|
|
71
101
|
|
|
72
|
-
//
|
|
102
|
+
// CUTOFFDATE INUTILE ?
|
|
73
103
|
go: async (modelName, where, cutoffDate, clientMetadataDict) => {
|
|
74
|
-
|
|
104
|
+
|
|
105
|
+
// get or create a mutex specific to modelName + where
|
|
106
|
+
const mutexKey = `${modelName}:${JSON.stringify(Object.fromEntries(Object.entries(where).sort()))}`
|
|
107
|
+
if (!syncMutexes.has(mutexKey)) syncMutexes.set(mutexKey, new Mutex())
|
|
108
|
+
// acquire it: no other sync operation from another client on this model+where can occur in parallel
|
|
109
|
+
await syncMutexes.get(mutexKey).acquire()
|
|
110
|
+
|
|
75
111
|
try {
|
|
76
112
|
console.log('>>>>> SYNC', modelName, where, cutoffDate)
|
|
77
113
|
const databaseService = app.service(modelName)
|
|
78
114
|
|
|
79
|
-
//
|
|
115
|
+
// STEP1: get existing database `where` values and build a dictionary
|
|
80
116
|
const databaseValues = await databaseService.findMany(where)
|
|
81
|
-
|
|
82
117
|
const databaseValuesDict = databaseValues.reduce((accu, value) => {
|
|
83
118
|
accu[value.uid] = value
|
|
84
119
|
return accu
|
|
85
120
|
}, {})
|
|
86
|
-
|
|
87
|
-
//
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const databaseAndClientIds = new Set()
|
|
93
|
-
|
|
94
|
-
for (const uid in databaseValuesDict) {
|
|
95
|
-
if (uid in clientMetadataDict) {
|
|
96
|
-
databaseAndClientIds.add(uid)
|
|
97
|
-
} else {
|
|
98
|
-
onlyDatabaseIds.add(uid)
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
for (const uid in clientMetadataDict) {
|
|
103
|
-
if (uid in databaseValuesDict) {
|
|
104
|
-
databaseAndClientIds.add(uid)
|
|
105
|
-
} else {
|
|
106
|
-
onlyClientIds.add(uid)
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
// console.log('onlyDatabaseIds', onlyDatabaseIds)
|
|
110
|
-
// console.log('onlyClientIds', onlyClientIds)
|
|
111
|
-
// console.log('databaseAndClientIds', databaseAndClientIds)
|
|
112
|
-
|
|
113
|
-
// STEP 3: build add/update/delete sets
|
|
114
|
-
const addDatabase = []
|
|
115
|
-
const updateDatabase = []
|
|
116
|
-
const deleteDatabase = []
|
|
117
|
-
|
|
118
|
-
const addClient = []
|
|
119
|
-
const updateClient = []
|
|
120
|
-
const deleteClient = []
|
|
121
|
-
|
|
122
|
-
for (const uid of onlyDatabaseIds) {
|
|
123
|
-
const databaseValue = databaseValuesDict[uid]
|
|
124
|
-
const databaseMetaData = (await db.select().from(metadata).where(eq(metadata.uid, uid)))[0]
|
|
125
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
126
|
-
addClient.push([databaseValue, databaseMetaData])
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
for (const uid of onlyClientIds) {
|
|
130
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
131
|
-
if (clientMetaData.deleted_at) {
|
|
132
|
-
deleteClient.push([uid, clientMetaData.deleted_at])
|
|
133
|
-
} else if (new Date(clientMetaData.created_at) > cutoffDate) {
|
|
134
|
-
addDatabase.push(clientMetaData)
|
|
135
|
-
} else {
|
|
136
|
-
// ???
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
for (const uid of databaseAndClientIds) {
|
|
141
|
-
const databaseValue = databaseValuesDict[uid]
|
|
142
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
143
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
144
|
-
if (clientMetaData.deleted_at) {
|
|
145
|
-
deleteDatabase.push(uid)
|
|
146
|
-
deleteClient.push([uid, clientMetaData.deleted_at])
|
|
147
|
-
} else {
|
|
148
|
-
const databaseMetaData = (await db.select().from(metadata).where(eq(metadata.uid, uid)))[0]
|
|
149
|
-
|| { uid, created_at: new Date() } // should not happen
|
|
150
|
-
const clientUpdatedAt = new Date(clientMetaData.updated_at || clientMetaData.created_at)
|
|
151
|
-
const databaseUpdatedAt = new Date(databaseMetaData.updated_at || databaseMetaData.created_at)
|
|
152
|
-
const dateDifference = clientUpdatedAt - databaseUpdatedAt
|
|
153
|
-
// console.log('databaseMetaData', databaseMetaData, 'clientMetaData', clientMetaData, 'dateDifference', dateDifference)
|
|
154
|
-
if (dateDifference > 0) {
|
|
155
|
-
updateDatabase.push(clientMetaData)
|
|
156
|
-
} else if (dateDifference < 0) {
|
|
157
|
-
updateClient.push(databaseValue)
|
|
158
|
-
}
|
|
159
|
-
}
|
|
121
|
+
|
|
122
|
+
// STEP 2: fetch metadata for each database record
|
|
123
|
+
const databaseMetadataDict = {}
|
|
124
|
+
for (const uid of Object.keys(databaseValuesDict)) {
|
|
125
|
+
const meta = (await db.select().from(metadata).where(eq(metadata.uid, uid)))[0] ?? null
|
|
126
|
+
if (meta) databaseMetadataDict[uid] = meta
|
|
160
127
|
}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
// STEP4: execute database deletions
|
|
170
|
-
for (const uid of deleteDatabase) {
|
|
171
|
-
const clientMetaData = clientMetadataDict[uid]
|
|
172
|
-
// console.log('---delete', uid, clientMetaData)
|
|
173
|
-
await databaseService.deleteWithMeta(uid, clientMetaData.deleted_at)
|
|
128
|
+
|
|
129
|
+
// STEP 3: compute sync result
|
|
130
|
+
const result = computeSyncResult(databaseValuesDict, clientMetadataDict, databaseMetadataDict)
|
|
131
|
+
|
|
132
|
+
// STEP 4: execute server-side deletions
|
|
133
|
+
for (const uid of result.deleteDatabase) {
|
|
134
|
+
await databaseService.deleteWithMeta(uid, clientMetadataDict[uid].deleted_at)
|
|
174
135
|
}
|
|
175
|
-
|
|
176
|
-
// STEP5: return to client the changes to perform on its cache, and create/update to perform on database with full data
|
|
177
|
-
// Database creations & updates are done later by the client with complete data (this function only has client values's meta-data)
|
|
178
|
-
return {
|
|
179
|
-
toAdd: addClient,
|
|
180
|
-
toUpdate: updateClient,
|
|
181
|
-
toDelete: deleteClient,
|
|
182
136
|
|
|
183
|
-
|
|
184
|
-
|
|
137
|
+
console.log('addDatabase', truncateString(JSON.stringify(result.addDatabase)))
|
|
138
|
+
console.log('updateDatabase', truncateString(JSON.stringify(result.updateDatabase)))
|
|
139
|
+
console.log('addClient', truncateString(JSON.stringify(result.addClient)))
|
|
140
|
+
console.log('deleteClient', truncateString(JSON.stringify(result.deleteClient)))
|
|
141
|
+
console.log('updateClient', truncateString(JSON.stringify(result.updateClient)))
|
|
142
|
+
|
|
143
|
+
return {
|
|
144
|
+
addClient: result.addClient,
|
|
145
|
+
updateClient: result.updateClient,
|
|
146
|
+
deleteClient: result.deleteClient,
|
|
147
|
+
addDatabase: result.addDatabase,
|
|
148
|
+
updateDatabase: result.updateDatabase,
|
|
185
149
|
}
|
|
186
150
|
} catch(err) {
|
|
187
151
|
console.log('*** err sync', err)
|
|
152
|
+
throw err
|
|
188
153
|
} finally {
|
|
189
|
-
|
|
154
|
+
syncMutexes.get(mutexKey).release()
|
|
190
155
|
}
|
|
191
156
|
},
|
|
192
157
|
})
|