@stonyx/orm 0.2.1-alpha.2 → 0.2.1-alpha.21
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/code-style-rules.md +44 -0
- package/.claude/hooks.md +250 -0
- package/.claude/index.md +292 -0
- package/.claude/usage-patterns.md +300 -0
- package/.claude/views.md +292 -0
- package/.github/workflows/ci.yml +5 -25
- package/.github/workflows/publish.yml +24 -116
- package/README.md +461 -15
- package/config/environment.js +29 -6
- package/improvements.md +139 -0
- package/package.json +24 -8
- package/project-structure.md +343 -0
- package/scripts/setup-test-db.sh +21 -0
- package/src/aggregates.js +93 -0
- package/src/belongs-to.js +4 -1
- package/src/commands.js +170 -0
- package/src/db.js +132 -6
- package/src/has-many.js +4 -1
- package/src/hooks.js +124 -0
- package/src/index.js +12 -2
- package/src/main.js +77 -4
- package/src/manage-record.js +30 -4
- package/src/migrate.js +72 -0
- package/src/model-property.js +2 -2
- package/src/model.js +11 -0
- package/src/mysql/connection.js +28 -0
- package/src/mysql/migration-generator.js +286 -0
- package/src/mysql/migration-runner.js +110 -0
- package/src/mysql/mysql-db.js +473 -0
- package/src/mysql/query-builder.js +64 -0
- package/src/mysql/schema-introspector.js +325 -0
- package/src/mysql/type-map.js +37 -0
- package/src/orm-request.js +313 -53
- package/src/plural-registry.js +12 -0
- package/src/record.js +35 -8
- package/src/serializer.js +9 -2
- package/src/setup-rest-server.js +5 -2
- package/src/store.js +130 -1
- package/src/utils.js +1 -1
- package/src/view-resolver.js +183 -0
- package/src/view.js +21 -0
- package/test-events-setup.js +41 -0
- package/test-hooks-manual.js +54 -0
- package/test-hooks-with-logging.js +52 -0
- package/.claude/project-structure.md +0 -578
- package/stonyx-bootstrap.cjs +0 -30
package/src/store.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { relationships } from '@stonyx/orm';
|
|
1
|
+
import Orm, { relationships } from '@stonyx/orm';
|
|
2
2
|
import { TYPES } from './relationships.js';
|
|
3
|
+
import ViewResolver from './view-resolver.js';
|
|
3
4
|
|
|
4
5
|
export default class Store {
|
|
5
6
|
constructor() {
|
|
@@ -9,17 +10,145 @@ export default class Store {
|
|
|
9
10
|
this.data = new Map();
|
|
10
11
|
}
|
|
11
12
|
|
|
13
|
+
/**
|
|
14
|
+
* Synchronous memory-only access.
|
|
15
|
+
* Returns the record if it exists in the in-memory store, undefined otherwise.
|
|
16
|
+
* Does NOT query the database. For memory:false models, use find() instead.
|
|
17
|
+
*/
|
|
12
18
|
get(key, id) {
|
|
13
19
|
if (!id) return this.data.get(key);
|
|
14
20
|
|
|
15
21
|
return this.data.get(key)?.get(id);
|
|
16
22
|
}
|
|
17
23
|
|
|
24
|
+
/**
|
|
25
|
+
* Async authoritative read. Always queries MySQL for memory: false models.
|
|
26
|
+
* For memory: true models, returns from store (already loaded on boot).
|
|
27
|
+
* @param {string} modelName - The model name
|
|
28
|
+
* @param {string|number} id - The record ID
|
|
29
|
+
* @returns {Promise<Record|undefined>}
|
|
30
|
+
*/
|
|
31
|
+
async find(modelName, id) {
|
|
32
|
+
// For views in non-MySQL mode, use view resolver
|
|
33
|
+
if (Orm.instance?.isView?.(modelName) && !this._mysqlDb) {
|
|
34
|
+
const resolver = new ViewResolver(modelName);
|
|
35
|
+
return resolver.resolveOne(id);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// For memory: true models, the store is authoritative
|
|
39
|
+
if (this._isMemoryModel(modelName)) {
|
|
40
|
+
return this.get(modelName, id);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// For memory: false models, always query MySQL
|
|
44
|
+
if (this._mysqlDb) {
|
|
45
|
+
return this._mysqlDb.findRecord(modelName, id);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Fallback to store (JSON mode or no MySQL)
|
|
49
|
+
return this.get(modelName, id);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Async read for all records of a model. Always queries MySQL for memory: false models.
|
|
54
|
+
* For memory: true models, returns from store.
|
|
55
|
+
* @param {string} modelName - The model name
|
|
56
|
+
* @param {Object} [conditions] - Optional WHERE conditions
|
|
57
|
+
* @returns {Promise<Record[]>}
|
|
58
|
+
*/
|
|
59
|
+
async findAll(modelName, conditions) {
|
|
60
|
+
// For views in non-MySQL mode, use view resolver
|
|
61
|
+
if (Orm.instance?.isView?.(modelName) && !this._mysqlDb) {
|
|
62
|
+
const resolver = new ViewResolver(modelName);
|
|
63
|
+
const records = await resolver.resolveAll();
|
|
64
|
+
|
|
65
|
+
if (!conditions || Object.keys(conditions).length === 0) return records;
|
|
66
|
+
|
|
67
|
+
return records.filter(record =>
|
|
68
|
+
Object.entries(conditions).every(([key, value]) => record.__data[key] === value)
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// For memory: true models without conditions, return from store
|
|
73
|
+
if (this._isMemoryModel(modelName) && !conditions) {
|
|
74
|
+
const modelStore = this.get(modelName);
|
|
75
|
+
return modelStore ? Array.from(modelStore.values()) : [];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// For memory: false models (or filtered queries), always query MySQL
|
|
79
|
+
if (this._mysqlDb) {
|
|
80
|
+
return this._mysqlDb.findAll(modelName, conditions);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Fallback to store (JSON mode) — apply conditions in-memory if provided
|
|
84
|
+
const modelStore = this.get(modelName);
|
|
85
|
+
if (!modelStore) return [];
|
|
86
|
+
|
|
87
|
+
const records = Array.from(modelStore.values());
|
|
88
|
+
|
|
89
|
+
if (!conditions || Object.keys(conditions).length === 0) return records;
|
|
90
|
+
|
|
91
|
+
return records.filter(record =>
|
|
92
|
+
Object.entries(conditions).every(([key, value]) => record.__data[key] === value)
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Async query — always hits MySQL, never reads from memory cache.
|
|
98
|
+
* Use for complex queries, aggregations, or when you need guaranteed freshness.
|
|
99
|
+
* @param {string} modelName - The model name
|
|
100
|
+
* @param {Object} conditions - WHERE conditions
|
|
101
|
+
* @returns {Promise<Record[]>}
|
|
102
|
+
*/
|
|
103
|
+
async query(modelName, conditions = {}) {
|
|
104
|
+
if (this._mysqlDb) {
|
|
105
|
+
return this._mysqlDb.findAll(modelName, conditions);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Fallback: filter in-memory store
|
|
109
|
+
const modelStore = this.get(modelName);
|
|
110
|
+
if (!modelStore) return [];
|
|
111
|
+
|
|
112
|
+
const records = Array.from(modelStore.values());
|
|
113
|
+
|
|
114
|
+
if (Object.keys(conditions).length === 0) return records;
|
|
115
|
+
|
|
116
|
+
return records.filter(record =>
|
|
117
|
+
Object.entries(conditions).every(([key, value]) => record.__data[key] === value)
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Set by Orm during init — resolves memory flag for a model name.
|
|
123
|
+
* @type {Function|null}
|
|
124
|
+
*/
|
|
125
|
+
_memoryResolver = null;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Set by Orm during init — reference to the MysqlDB instance for on-demand queries.
|
|
129
|
+
* @type {MysqlDB|null}
|
|
130
|
+
*/
|
|
131
|
+
_mysqlDb = null;
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Check if a model is configured for in-memory storage.
|
|
135
|
+
* @private
|
|
136
|
+
*/
|
|
137
|
+
_isMemoryModel(modelName) {
|
|
138
|
+
if (this._memoryResolver) return this._memoryResolver(modelName);
|
|
139
|
+
return true; // default to memory if resolver not set yet
|
|
140
|
+
}
|
|
141
|
+
|
|
18
142
|
set(key, value) {
|
|
19
143
|
this.data.set(key, value);
|
|
20
144
|
}
|
|
21
145
|
|
|
22
146
|
remove(key, id) {
|
|
147
|
+
// Guard: read-only views cannot have records removed
|
|
148
|
+
if (Orm.instance?.isView?.(key)) {
|
|
149
|
+
throw new Error(`Cannot remove records from read-only view '${key}'`);
|
|
150
|
+
}
|
|
151
|
+
|
|
23
152
|
if (id) return this.unloadRecord(key, id);
|
|
24
153
|
|
|
25
154
|
this.unloadAllRecords(key);
|
package/src/utils.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { pluralize as basePluralize } from '@stonyx/utils/string';
|
|
2
2
|
|
|
3
|
+
// Wrapper to handle dasherized model names (e.g., "access-link" → "access-links")
|
|
3
4
|
export function pluralize(word) {
|
|
4
5
|
if (word.includes('-')) {
|
|
5
6
|
const parts = word.split('-');
|
|
6
7
|
const pluralizedLast = basePluralize(parts.pop());
|
|
7
|
-
|
|
8
8
|
return [...parts, pluralizedLast].join('-');
|
|
9
9
|
}
|
|
10
10
|
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import Orm, { createRecord, store } from '@stonyx/orm';
|
|
2
|
+
import { AggregateProperty } from './aggregates.js';
|
|
3
|
+
import { get } from '@stonyx/utils/object';
|
|
4
|
+
|
|
5
|
+
export default class ViewResolver {
|
|
6
|
+
constructor(viewName) {
|
|
7
|
+
this.viewName = viewName;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
async resolveAll() {
|
|
11
|
+
const orm = Orm.instance;
|
|
12
|
+
const { modelClass: viewClass } = orm.getRecordClasses(this.viewName);
|
|
13
|
+
|
|
14
|
+
if (!viewClass) return [];
|
|
15
|
+
|
|
16
|
+
const source = viewClass.source;
|
|
17
|
+
if (!source) return [];
|
|
18
|
+
|
|
19
|
+
const sourceRecords = await store.findAll(source);
|
|
20
|
+
if (!sourceRecords || sourceRecords.length === 0) {
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const resolveMap = viewClass.resolve || {};
|
|
25
|
+
const viewInstance = new viewClass(this.viewName);
|
|
26
|
+
const aggregateFields = {};
|
|
27
|
+
const regularFields = {};
|
|
28
|
+
|
|
29
|
+
// Categorize fields on the view instance
|
|
30
|
+
for (const [key, value] of Object.entries(viewInstance)) {
|
|
31
|
+
if (key.startsWith('__')) continue;
|
|
32
|
+
if (key === 'id') continue;
|
|
33
|
+
|
|
34
|
+
if (value instanceof AggregateProperty) {
|
|
35
|
+
aggregateFields[key] = value;
|
|
36
|
+
} else if (typeof value !== 'function') {
|
|
37
|
+
// Regular attr or direct value — not a relationship handler
|
|
38
|
+
regularFields[key] = value;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const groupByField = viewClass.groupBy;
|
|
43
|
+
|
|
44
|
+
if (groupByField) {
|
|
45
|
+
return this._resolveGroupBy(sourceRecords, groupByField, aggregateFields, regularFields, resolveMap, viewClass);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
return this._resolvePerRecord(sourceRecords, aggregateFields, regularFields, resolveMap, viewClass);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
_resolvePerRecord(sourceRecords, aggregateFields, regularFields, resolveMap, viewClass) {
|
|
52
|
+
const results = [];
|
|
53
|
+
|
|
54
|
+
for (const sourceRecord of sourceRecords) {
|
|
55
|
+
const rawData = { id: sourceRecord.id };
|
|
56
|
+
|
|
57
|
+
// Compute aggregate fields from source record's relationships
|
|
58
|
+
for (const [key, aggProp] of Object.entries(aggregateFields)) {
|
|
59
|
+
const relatedRecords = sourceRecord.__relationships?.[aggProp.relationship]
|
|
60
|
+
|| sourceRecord[aggProp.relationship];
|
|
61
|
+
const relArray = Array.isArray(relatedRecords) ? relatedRecords : [];
|
|
62
|
+
rawData[key] = aggProp.compute(relArray);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Apply resolve map entries
|
|
66
|
+
for (const [key, resolver] of Object.entries(resolveMap)) {
|
|
67
|
+
if (typeof resolver === 'function') {
|
|
68
|
+
rawData[key] = resolver(sourceRecord);
|
|
69
|
+
} else if (typeof resolver === 'string') {
|
|
70
|
+
rawData[key] = get(sourceRecord.__data || sourceRecord, resolver)
|
|
71
|
+
?? get(sourceRecord, resolver);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Map regular attr fields from source record if not already set
|
|
76
|
+
for (const key of Object.keys(regularFields)) {
|
|
77
|
+
if (rawData[key] !== undefined) continue;
|
|
78
|
+
|
|
79
|
+
const sourceValue = sourceRecord.__data?.[key] ?? sourceRecord[key];
|
|
80
|
+
if (sourceValue !== undefined) {
|
|
81
|
+
rawData[key] = sourceValue;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Set belongsTo source relationship
|
|
86
|
+
const viewInstanceForRel = new viewClass(this.viewName);
|
|
87
|
+
for (const [key, value] of Object.entries(viewInstanceForRel)) {
|
|
88
|
+
if (typeof value === 'function' && key !== 'id') {
|
|
89
|
+
// This is a relationship handler — pass the source record id
|
|
90
|
+
rawData[key] = sourceRecord.id;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Clear existing record from store to allow re-resolution
|
|
95
|
+
const viewStore = store.get(this.viewName);
|
|
96
|
+
if (viewStore?.has(rawData.id)) {
|
|
97
|
+
viewStore.delete(rawData.id);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const record = createRecord(this.viewName, rawData, { isDbRecord: true });
|
|
101
|
+
results.push(record);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return results;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
_resolveGroupBy(sourceRecords, groupByField, aggregateFields, regularFields, resolveMap, viewClass) {
|
|
108
|
+
// Group source records by the groupBy field value
|
|
109
|
+
const groups = new Map();
|
|
110
|
+
for (const record of sourceRecords) {
|
|
111
|
+
const key = record.__data?.[groupByField] ?? record[groupByField];
|
|
112
|
+
if (!groups.has(key)) {
|
|
113
|
+
groups.set(key, []);
|
|
114
|
+
}
|
|
115
|
+
groups.get(key).push(record);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const results = [];
|
|
119
|
+
|
|
120
|
+
for (const [groupKey, groupRecords] of groups) {
|
|
121
|
+
const rawData = { id: groupKey };
|
|
122
|
+
|
|
123
|
+
// Compute aggregate fields
|
|
124
|
+
for (const [key, aggProp] of Object.entries(aggregateFields)) {
|
|
125
|
+
if (aggProp.relationship === undefined) {
|
|
126
|
+
// Field-level aggregate — compute over group records directly
|
|
127
|
+
rawData[key] = aggProp.compute(groupRecords);
|
|
128
|
+
} else {
|
|
129
|
+
// Relationship aggregate — flatten related records across all group members
|
|
130
|
+
const allRelated = [];
|
|
131
|
+
for (const record of groupRecords) {
|
|
132
|
+
const relatedRecords = record.__relationships?.[aggProp.relationship]
|
|
133
|
+
|| record[aggProp.relationship];
|
|
134
|
+
if (Array.isArray(relatedRecords)) {
|
|
135
|
+
allRelated.push(...relatedRecords);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
rawData[key] = aggProp.compute(allRelated);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Apply resolve map entries — functions receive the group array
|
|
143
|
+
for (const [key, resolver] of Object.entries(resolveMap)) {
|
|
144
|
+
if (typeof resolver === 'function') {
|
|
145
|
+
rawData[key] = resolver(groupRecords);
|
|
146
|
+
} else if (typeof resolver === 'string') {
|
|
147
|
+
// String path — take value from first record in group
|
|
148
|
+
const first = groupRecords[0];
|
|
149
|
+
rawData[key] = get(first.__data || first, resolver)
|
|
150
|
+
?? get(first, resolver);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Map regular attr fields from first record if not already set
|
|
155
|
+
for (const key of Object.keys(regularFields)) {
|
|
156
|
+
if (rawData[key] !== undefined) continue;
|
|
157
|
+
const first = groupRecords[0];
|
|
158
|
+
const sourceValue = first.__data?.[key] ?? first[key];
|
|
159
|
+
if (sourceValue !== undefined) {
|
|
160
|
+
rawData[key] = sourceValue;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Clear existing record from store to allow re-resolution
|
|
165
|
+
const viewStore = store.get(this.viewName);
|
|
166
|
+
if (viewStore?.has(rawData.id)) {
|
|
167
|
+
viewStore.delete(rawData.id);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const record = createRecord(this.viewName, rawData, { isDbRecord: true });
|
|
171
|
+
results.push(record);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return results;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
async resolveOne(id) {
|
|
178
|
+
const all = await this.resolveAll();
|
|
179
|
+
return all.find(record => {
|
|
180
|
+
return record.id === id || record.id == id;
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
package/src/view.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { attr } from '@stonyx/orm';
|
|
2
|
+
|
|
3
|
+
export default class View {
|
|
4
|
+
static memory = false;
|
|
5
|
+
static readOnly = true;
|
|
6
|
+
static pluralName = undefined;
|
|
7
|
+
static source = undefined;
|
|
8
|
+
static groupBy = undefined;
|
|
9
|
+
static resolve = undefined;
|
|
10
|
+
|
|
11
|
+
id = attr('number');
|
|
12
|
+
|
|
13
|
+
constructor(name) {
|
|
14
|
+
this.__name = name;
|
|
15
|
+
|
|
16
|
+
// Enforce readOnly — cannot be overridden to false
|
|
17
|
+
if (this.constructor.readOnly !== true) {
|
|
18
|
+
throw new Error(`View '${name}' cannot override readOnly to false`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Debug script to verify event setup
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import Stonyx from 'stonyx';
|
|
6
|
+
import config from './config/environment.js';
|
|
7
|
+
import Orm from './src/main.js';
|
|
8
|
+
import { subscribe } from '@stonyx/events';
|
|
9
|
+
|
|
10
|
+
// Override paths for tests
|
|
11
|
+
Object.assign(config.paths, {
|
|
12
|
+
access: './test/sample/access',
|
|
13
|
+
model: './test/sample/models',
|
|
14
|
+
serializer: './test/sample/serializers',
|
|
15
|
+
transform: './test/sample/transforms'
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
// Override db settings for tests
|
|
19
|
+
Object.assign(config.db, {
|
|
20
|
+
file: './test/sample/db.json',
|
|
21
|
+
schema: './test/sample/db-schema.js'
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
new Stonyx(config, import.meta.dirname);
|
|
25
|
+
|
|
26
|
+
const orm = new Orm();
|
|
27
|
+
await orm.init();
|
|
28
|
+
|
|
29
|
+
console.log('ORM initialized');
|
|
30
|
+
console.log('Store keys:', Array.from(Orm.store.data.keys()));
|
|
31
|
+
|
|
32
|
+
// Try subscribing to an event
|
|
33
|
+
try {
|
|
34
|
+
const unsubscribe = subscribe('before:create:animal', (context) => {
|
|
35
|
+
console.log('Hook called!', context);
|
|
36
|
+
});
|
|
37
|
+
console.log('✓ Successfully subscribed to before:create:animal');
|
|
38
|
+
unsubscribe();
|
|
39
|
+
} catch (error) {
|
|
40
|
+
console.error('✗ Failed to subscribe:', error.message);
|
|
41
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manual test script for hooks functionality
|
|
3
|
+
* Run with: node test-hooks-manual.js
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { setup, subscribe, emit } from '@stonyx/events';
|
|
7
|
+
|
|
8
|
+
console.log('Testing hooks system...\n');
|
|
9
|
+
|
|
10
|
+
// Setup events
|
|
11
|
+
const eventNames = ['before:create:animal', 'after:create:animal'];
|
|
12
|
+
setup(eventNames);
|
|
13
|
+
|
|
14
|
+
let beforeCalled = false;
|
|
15
|
+
let afterCalled = false;
|
|
16
|
+
let contextReceived = null;
|
|
17
|
+
|
|
18
|
+
// Subscribe to hooks
|
|
19
|
+
const unsubscribe1 = subscribe('before:create:animal', async (context) => {
|
|
20
|
+
console.log('✓ before:create:animal hook called');
|
|
21
|
+
console.log(' Context:', JSON.stringify(context, null, 2));
|
|
22
|
+
beforeCalled = true;
|
|
23
|
+
contextReceived = context;
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const unsubscribe2 = subscribe('after:create:animal', async (context) => {
|
|
27
|
+
console.log('✓ after:create:animal hook called');
|
|
28
|
+
console.log(' Context:', JSON.stringify(context, null, 2));
|
|
29
|
+
afterCalled = true;
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
// Simulate hook execution
|
|
33
|
+
const testContext = {
|
|
34
|
+
model: 'animal',
|
|
35
|
+
operation: 'create',
|
|
36
|
+
body: { data: { type: 'animals', attributes: { name: 'Test' } } }
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
console.log('Emitting before:create:animal...');
|
|
40
|
+
await emit('before:create:animal', testContext);
|
|
41
|
+
|
|
42
|
+
console.log('\nEmitting after:create:animal...');
|
|
43
|
+
await emit('after:create:animal', { ...testContext, record: { id: 1, name: 'Test' } });
|
|
44
|
+
|
|
45
|
+
console.log('\n--- Test Results ---');
|
|
46
|
+
console.log('Before hook called:', beforeCalled ? '✓ PASS' : '✗ FAIL');
|
|
47
|
+
console.log('After hook called:', afterCalled ? '✓ PASS' : '✗ FAIL');
|
|
48
|
+
console.log('Context passed correctly:', contextReceived?.model === 'animal' ? '✓ PASS' : '✗ FAIL');
|
|
49
|
+
|
|
50
|
+
// Cleanup
|
|
51
|
+
unsubscribe1();
|
|
52
|
+
unsubscribe2();
|
|
53
|
+
|
|
54
|
+
console.log('\n✓ Hooks system working correctly!');
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test to verify hooks wrapper is being called
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { emit } from '@stonyx/events';
|
|
6
|
+
|
|
7
|
+
// Simulate the _withHooks wrapper
|
|
8
|
+
function _withHooks(operation, handler, model) {
|
|
9
|
+
console.log(`Creating wrapper for ${operation} on ${model}`);
|
|
10
|
+
|
|
11
|
+
return async (request, state) => {
|
|
12
|
+
console.log(`Wrapper called for ${operation} on ${model}`);
|
|
13
|
+
|
|
14
|
+
const context = {
|
|
15
|
+
model,
|
|
16
|
+
operation,
|
|
17
|
+
request,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
console.log(`About to emit before:${operation}:${model}`);
|
|
21
|
+
await emit(`before:${operation}:${model}`, context);
|
|
22
|
+
console.log(`Emitted before hook`);
|
|
23
|
+
|
|
24
|
+
const response = await handler(request, state);
|
|
25
|
+
console.log(`Handler completed`);
|
|
26
|
+
|
|
27
|
+
context.response = response;
|
|
28
|
+
await emit(`after:${operation}:${model}`, context);
|
|
29
|
+
console.log(`Emitted after hook`);
|
|
30
|
+
|
|
31
|
+
return response;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Simulate a handler
|
|
36
|
+
const createHandler = ({ body }) => {
|
|
37
|
+
console.log('Original handler called');
|
|
38
|
+
return { data: { id: 1, ...body } };
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
// Create wrapped handler
|
|
42
|
+
const wrappedHandler = _withHooks('create', createHandler, 'animal');
|
|
43
|
+
|
|
44
|
+
// Simulate a request
|
|
45
|
+
const mockRequest = {
|
|
46
|
+
body: { name: 'Test' }
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
console.log('\n=== Testing wrapper ===');
|
|
50
|
+
const result = await wrappedHandler(mockRequest, {});
|
|
51
|
+
console.log('Result:', result);
|
|
52
|
+
console.log('\n✓ Wrapper test completed');
|