@stonyx/orm 0.2.1-alpha.31 → 0.2.1-alpha.33
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 +23 -6
- package/package.json +1 -1
- package/src/belongs-to.js +7 -3
- package/src/has-many.js +4 -0
- package/src/main.js +8 -8
- package/src/manage-record.js +5 -3
- package/src/mysql/mysql-db.js +2 -2
- package/src/orm-request.js +3 -3
- package/src/record.js +5 -0
- package/src/store.js +17 -17
package/README.md
CHANGED
|
@@ -17,6 +17,23 @@ A lightweight ORM for Stonyx projects, featuring model definitions, serializers,
|
|
|
17
17
|
- **REST Server Integration**: Automatic route setup with customizable access control.
|
|
18
18
|
- **Lifecycle Hooks**: Middleware-based before/after hooks for validation, authorization, side effects, and auditing.
|
|
19
19
|
|
|
20
|
+
## Public API vs Internals
|
|
21
|
+
|
|
22
|
+
Records use a proxy that exposes model attributes as direct properties. Always use direct property access for reading and writing field values:
|
|
23
|
+
|
|
24
|
+
```js
|
|
25
|
+
// Correct: read/write via the proxy
|
|
26
|
+
const age = record.age;
|
|
27
|
+
record.age = 5;
|
|
28
|
+
|
|
29
|
+
// Correct: iterate fields using the record directly
|
|
30
|
+
for (const key of Object.keys(record.serialize())) {
|
|
31
|
+
console.log(key, record[key]);
|
|
32
|
+
}
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
All properties prefixed with `__` (`__data`, `__relationships`, `__model`, `__serializer`, `__serialized`) are **internal implementation details** and must not be accessed by consumer code. Bypassing the proxy by reading or writing `__data` directly skips type transforms and change tracking, which can lead to silent data corruption.
|
|
36
|
+
|
|
20
37
|
## Installation
|
|
21
38
|
|
|
22
39
|
```bash
|
|
@@ -417,7 +434,7 @@ Each hook receives a context object with comprehensive information:
|
|
|
417
434
|
- It contains a deep copy of the record's state **before** the operation executes (captured before the `before` hook fires)
|
|
418
435
|
- The deep copy is created via JSON serialization (`JSON.parse(JSON.stringify())`) to ensure complete isolation
|
|
419
436
|
- For `delete` operations, `recordId` is provided in after hooks since the record may no longer exist in the store
|
|
420
|
-
- `oldState` is captured
|
|
437
|
+
- `oldState` is captured as a deep copy of the record's data before the operation, providing access to the previous field values
|
|
421
438
|
|
|
422
439
|
### Usage Examples
|
|
423
440
|
|
|
@@ -520,8 +537,8 @@ afterHook('update', 'animal', async (context) => {
|
|
|
520
537
|
|
|
521
538
|
// Track multiple field changes
|
|
522
539
|
const changedFields = [];
|
|
523
|
-
for (const key
|
|
524
|
-
if (context.oldState[key] !== context.record
|
|
540
|
+
for (const key of Object.keys(context.oldState)) {
|
|
541
|
+
if (context.oldState[key] !== context.record[key]) {
|
|
525
542
|
changedFields.push(key);
|
|
526
543
|
}
|
|
527
544
|
}
|
|
@@ -560,9 +577,9 @@ afterHook('update', 'animal', async (context) => {
|
|
|
560
577
|
// Compare oldState with current record to capture exact changes
|
|
561
578
|
const changes = {};
|
|
562
579
|
if (context.oldState) {
|
|
563
|
-
for (const
|
|
564
|
-
if (context.oldState[key] !==
|
|
565
|
-
changes[key] = { from: context.oldState[key], to:
|
|
580
|
+
for (const key of Object.keys(context.oldState)) {
|
|
581
|
+
if (context.oldState[key] !== context.record[key]) {
|
|
582
|
+
changes[key] = { from: context.oldState[key], to: context.record[key] };
|
|
566
583
|
}
|
|
567
584
|
}
|
|
568
585
|
}
|
package/package.json
CHANGED
package/src/belongs-to.js
CHANGED
|
@@ -21,9 +21,13 @@ export default function belongsTo(modelName) {
|
|
|
21
21
|
const modelStore = store.get(modelName);
|
|
22
22
|
|
|
23
23
|
// Try to get existing record
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
let output;
|
|
25
|
+
|
|
26
|
+
if (typeof rawData === 'object') {
|
|
27
|
+
output = createRecord(modelName, rawData, options);
|
|
28
|
+
} else if (modelStore) {
|
|
29
|
+
output = modelStore.get(rawData);
|
|
30
|
+
}
|
|
27
31
|
|
|
28
32
|
// If not found and is a string ID, register as pending
|
|
29
33
|
if (!output && typeof rawData !== 'object') {
|
package/src/has-many.js
CHANGED
|
@@ -27,6 +27,10 @@ export default function hasMany(modelName) {
|
|
|
27
27
|
let record;
|
|
28
28
|
|
|
29
29
|
if (typeof elementData !== 'object') {
|
|
30
|
+
if (!modelStore) {
|
|
31
|
+
return queuePendingRelationship(pendingRelationshipQueue, pendingRelationships, modelName, elementData);
|
|
32
|
+
}
|
|
33
|
+
|
|
30
34
|
record = modelStore.get(elementData);
|
|
31
35
|
|
|
32
36
|
if (!record) {
|
package/src/main.js
CHANGED
|
@@ -111,9 +111,9 @@ export default class Orm {
|
|
|
111
111
|
|
|
112
112
|
if (config.orm.mysql) {
|
|
113
113
|
const { default: MysqlDB } = await import('./mysql/mysql-db.js');
|
|
114
|
-
this.
|
|
115
|
-
this.db = this.
|
|
116
|
-
promises.push(this.
|
|
114
|
+
this.sqlDb = new MysqlDB();
|
|
115
|
+
this.db = this.sqlDb;
|
|
116
|
+
promises.push(this.sqlDb.init());
|
|
117
117
|
} else if (this.options.dbType !== 'none') {
|
|
118
118
|
const db = new DB();
|
|
119
119
|
this.db = db;
|
|
@@ -131,9 +131,9 @@ export default class Orm {
|
|
|
131
131
|
return modelClass?.memory === true;
|
|
132
132
|
};
|
|
133
133
|
|
|
134
|
-
// Wire up
|
|
135
|
-
if (this.
|
|
136
|
-
Orm.store.
|
|
134
|
+
// Wire up SQL adapter reference for on-demand queries from store.find()/findAll()
|
|
135
|
+
if (this.sqlDb) {
|
|
136
|
+
Orm.store._sqlDb = this.sqlDb;
|
|
137
137
|
}
|
|
138
138
|
|
|
139
139
|
Orm.ready = await Promise.all(promises);
|
|
@@ -141,11 +141,11 @@ export default class Orm {
|
|
|
141
141
|
}
|
|
142
142
|
|
|
143
143
|
async startup() {
|
|
144
|
-
if (this.
|
|
144
|
+
if (this.sqlDb) await this.sqlDb.startup();
|
|
145
145
|
}
|
|
146
146
|
|
|
147
147
|
async shutdown() {
|
|
148
|
-
if (this.
|
|
148
|
+
if (this.sqlDb) await this.sqlDb.shutdown();
|
|
149
149
|
}
|
|
150
150
|
|
|
151
151
|
static get db() {
|
package/src/manage-record.js
CHANGED
|
@@ -23,6 +23,8 @@ export function createRecord(modelName, rawData={}, userOptions={}) {
|
|
|
23
23
|
const globalRelationships = relationships.get('global');
|
|
24
24
|
const pendingRelationships = relationships.get('pending');
|
|
25
25
|
|
|
26
|
+
if (!modelStore) throw new Error(`Model store for '${modelName}' is not registered. Ensure the model is defined before creating records.`);
|
|
27
|
+
|
|
26
28
|
assignRecordId(modelName, rawData);
|
|
27
29
|
if (modelStore.has(rawData.id)) return modelStore.get(rawData.id);
|
|
28
30
|
|
|
@@ -108,10 +110,10 @@ export function updateRecord(record, rawData, userOptions={}) {
|
|
|
108
110
|
function assignRecordId(modelName, rawData) {
|
|
109
111
|
if (rawData.id) return;
|
|
110
112
|
|
|
111
|
-
// In
|
|
112
|
-
if (Orm.instance?.
|
|
113
|
+
// In SQL mode with numeric IDs, defer to database auto-increment
|
|
114
|
+
if (Orm.instance?.sqlDb && !isStringIdModel(modelName)) {
|
|
113
115
|
rawData.id = `__pending_${Date.now()}_${Math.random()}`;
|
|
114
|
-
rawData.
|
|
116
|
+
rawData.__pendingSqlId = true;
|
|
115
117
|
return;
|
|
116
118
|
}
|
|
117
119
|
|
package/src/mysql/mysql-db.js
CHANGED
|
@@ -352,7 +352,7 @@ export default class MysqlDB {
|
|
|
352
352
|
const insertData = this._recordToRow(record, schema);
|
|
353
353
|
|
|
354
354
|
// For auto-increment models, remove the pending ID
|
|
355
|
-
const isPendingId = record.__data.
|
|
355
|
+
const isPendingId = record.__data.__pendingSqlId;
|
|
356
356
|
|
|
357
357
|
if (isPendingId) {
|
|
358
358
|
delete insertData.id;
|
|
@@ -380,7 +380,7 @@ export default class MysqlDB {
|
|
|
380
380
|
response.data.id = realId;
|
|
381
381
|
}
|
|
382
382
|
|
|
383
|
-
delete record.__data.
|
|
383
|
+
delete record.__data.__pendingSqlId;
|
|
384
384
|
}
|
|
385
385
|
}
|
|
386
386
|
|
package/src/orm-request.js
CHANGED
|
@@ -385,9 +385,9 @@ export default class OrmRequest extends Request {
|
|
|
385
385
|
// Execute main handler
|
|
386
386
|
const response = await handler(request, state);
|
|
387
387
|
|
|
388
|
-
// Persist to
|
|
389
|
-
if (Orm.instance.
|
|
390
|
-
await Orm.instance.
|
|
388
|
+
// Persist to SQL database for write operations
|
|
389
|
+
if (Orm.instance.sqlDb && WRITE_OPERATIONS.has(operation)) {
|
|
390
|
+
await Orm.instance.sqlDb.persist(operation, this.model, context, response);
|
|
391
391
|
}
|
|
392
392
|
|
|
393
393
|
// Add response and relevant records to context
|
package/src/record.js
CHANGED
|
@@ -3,12 +3,17 @@ import { getComputedProperties } from "./serializer.js";
|
|
|
3
3
|
import { camelCaseToKebabCase } from '@stonyx/utils/string';
|
|
4
4
|
import { getPluralName } from './plural-registry.js';
|
|
5
5
|
export default class Record {
|
|
6
|
+
/** @private */
|
|
6
7
|
__data = {};
|
|
8
|
+
/** @private */
|
|
7
9
|
__relationships = {};
|
|
10
|
+
/** @private */
|
|
8
11
|
__serialized = false;
|
|
9
12
|
|
|
10
13
|
constructor(model, serializer) {
|
|
14
|
+
/** @private */
|
|
11
15
|
this.__model = model;
|
|
16
|
+
/** @private */
|
|
12
17
|
this.__serializer = serializer;
|
|
13
18
|
|
|
14
19
|
}
|
package/src/store.js
CHANGED
|
@@ -22,15 +22,15 @@ export default class Store {
|
|
|
22
22
|
}
|
|
23
23
|
|
|
24
24
|
/**
|
|
25
|
-
* Async authoritative read. Always queries
|
|
25
|
+
* Async authoritative read. Always queries the SQL database for memory: false models.
|
|
26
26
|
* For memory: true models, returns from store (already loaded on boot).
|
|
27
27
|
* @param {string} modelName - The model name
|
|
28
28
|
* @param {string|number} id - The record ID
|
|
29
29
|
* @returns {Promise<Record|undefined>}
|
|
30
30
|
*/
|
|
31
31
|
async find(modelName, id) {
|
|
32
|
-
// For views in non-
|
|
33
|
-
if (Orm.instance?.isView?.(modelName) && !this.
|
|
32
|
+
// For views in non-SQL mode, use view resolver
|
|
33
|
+
if (Orm.instance?.isView?.(modelName) && !this._sqlDb) {
|
|
34
34
|
const resolver = new ViewResolver(modelName);
|
|
35
35
|
return resolver.resolveOne(id);
|
|
36
36
|
}
|
|
@@ -40,12 +40,12 @@ export default class Store {
|
|
|
40
40
|
return this.get(modelName, id);
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
// For memory: false models, always query
|
|
44
|
-
if (this.
|
|
45
|
-
return this.
|
|
43
|
+
// For memory: false models, always query the SQL database
|
|
44
|
+
if (this._sqlDb) {
|
|
45
|
+
return this._sqlDb.findRecord(modelName, id);
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
// Fallback to store (JSON mode or no
|
|
48
|
+
// Fallback to store (JSON mode or no SQL adapter)
|
|
49
49
|
return this.get(modelName, id);
|
|
50
50
|
}
|
|
51
51
|
|
|
@@ -57,8 +57,8 @@ export default class Store {
|
|
|
57
57
|
* @returns {Promise<Record[]>}
|
|
58
58
|
*/
|
|
59
59
|
async findAll(modelName, conditions) {
|
|
60
|
-
// For views in non-
|
|
61
|
-
if (Orm.instance?.isView?.(modelName) && !this.
|
|
60
|
+
// For views in non-SQL mode, use view resolver
|
|
61
|
+
if (Orm.instance?.isView?.(modelName) && !this._sqlDb) {
|
|
62
62
|
const resolver = new ViewResolver(modelName);
|
|
63
63
|
const records = await resolver.resolveAll();
|
|
64
64
|
|
|
@@ -75,9 +75,9 @@ export default class Store {
|
|
|
75
75
|
return modelStore ? Array.from(modelStore.values()) : [];
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
// For memory: false models (or filtered queries), always query
|
|
79
|
-
if (this.
|
|
80
|
-
return this.
|
|
78
|
+
// For memory: false models (or filtered queries), always query the SQL database
|
|
79
|
+
if (this._sqlDb) {
|
|
80
|
+
return this._sqlDb.findAll(modelName, conditions);
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
// Fallback to store (JSON mode) — apply conditions in-memory if provided
|
|
@@ -101,8 +101,8 @@ export default class Store {
|
|
|
101
101
|
* @returns {Promise<Record[]>}
|
|
102
102
|
*/
|
|
103
103
|
async query(modelName, conditions = {}) {
|
|
104
|
-
if (this.
|
|
105
|
-
return this.
|
|
104
|
+
if (this._sqlDb) {
|
|
105
|
+
return this._sqlDb.findAll(modelName, conditions);
|
|
106
106
|
}
|
|
107
107
|
|
|
108
108
|
// Fallback: filter in-memory store
|
|
@@ -125,10 +125,10 @@ export default class Store {
|
|
|
125
125
|
_memoryResolver = null;
|
|
126
126
|
|
|
127
127
|
/**
|
|
128
|
-
* Set by Orm during init — reference to the
|
|
129
|
-
* @type {
|
|
128
|
+
* Set by Orm during init — reference to the SQL adapter instance for on-demand queries.
|
|
129
|
+
* @type {object|null}
|
|
130
130
|
*/
|
|
131
|
-
|
|
131
|
+
_sqlDb = null;
|
|
132
132
|
|
|
133
133
|
/**
|
|
134
134
|
* Check if a model is configured for in-memory storage.
|