@stonyx/orm 0.2.1-alpha.3 → 0.2.1-alpha.31

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 CHANGED
@@ -1,7 +1,11 @@
1
+ [![CI](https://github.com/abofs/stonyx-orm/actions/workflows/ci.yml/badge.svg)](https://github.com/abofs/stonyx-orm/actions/workflows/ci.yml)
2
+ [![npm version](https://img.shields.io/npm/v/@stonyx/orm.svg)](https://www.npmjs.com/package/@stonyx/orm)
3
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
4
+
1
5
  # @stonyx/orm
2
6
 
3
7
  A lightweight ORM for Stonyx projects, featuring model definitions, serializers, relationships, transforms, and optional REST server integration.
4
- `@stonyx/orm` provides a structured way to define models, manage relationships, and persist data in JSON files. It also allows integration with the Stonyx REST server for automatic route setup and access control.
8
+ `@stonyx/orm` provides a structured way to define models, manage relationships, and persist data in JSON files or MySQL. It also allows integration with the Stonyx REST server for automatic route setup and access control.
5
9
 
6
10
  ## Highlights
7
11
 
@@ -9,8 +13,9 @@ A lightweight ORM for Stonyx projects, featuring model definitions, serializers,
9
13
  - **Models**: Define attributes with type-safe proxies (`attr`) and relationships (`hasMany`, `belongsTo`).
10
14
  - **Serializers**: Map raw data into model-friendly structures, including nested properties.
11
15
  - **Transforms**: Apply custom transformations on data values automatically.
12
- - **DB Integration**: Optional file-based persistence with auto-save support.
16
+ - **DB Integration**: Optional file-based persistence with auto-save support, or MySQL for production workloads.
13
17
  - **REST Server Integration**: Automatic route setup with customizable access control.
18
+ - **Lifecycle Hooks**: Middleware-based before/after hooks for validation, authorization, side effects, and auditing.
14
19
 
15
20
  ## Installation
16
21
 
@@ -32,9 +37,18 @@ const {
32
37
  ORM_USE_REST_SERVER,
33
38
  DB_AUTO_SAVE,
34
39
  DB_FILE,
40
+ DB_MODE,
41
+ DB_DIRECTORY,
35
42
  DB_SCHEMA_PATH,
36
- DB_SAVE_INTERVAL
37
- } = process;
43
+ DB_SAVE_INTERVAL,
44
+ MYSQL_HOST,
45
+ MYSQL_PORT,
46
+ MYSQL_USER,
47
+ MYSQL_PASSWORD,
48
+ MYSQL_DATABASE,
49
+ MYSQL_CONNECTION_LIMIT,
50
+ MYSQL_MIGRATIONS_DIR,
51
+ } = process.env;
38
52
 
39
53
  export default {
40
54
  orm: {
@@ -44,6 +58,8 @@ export default {
44
58
  db: {
45
59
  autosave: DB_AUTO_SAVE ?? 'false',
46
60
  file: DB_FILE ?? 'db.json',
61
+ mode: DB_MODE ?? 'file', // 'file' (single db.json) or 'directory' (one file per collection)
62
+ directory: DB_DIRECTORY ?? 'db', // directory name for collection files when mode is 'directory'
47
63
  saveInterval: DB_SAVE_INTERVAL ?? 3600, // 1 hour
48
64
  schema: DB_SCHEMA_PATH ?? './config/db-schema.js'
49
65
  },
@@ -53,6 +69,16 @@ export default {
53
69
  serializer: ORM_SERIALIZER_PATH ?? './serializers',
54
70
  transform: ORM_TRANSFORM_PATH ?? './transforms'
55
71
  },
72
+ mysql: MYSQL_HOST ? {
73
+ host: MYSQL_HOST ?? 'localhost',
74
+ port: parseInt(MYSQL_PORT ?? '3306'),
75
+ user: MYSQL_USER ?? 'root',
76
+ password: MYSQL_PASSWORD ?? '',
77
+ database: MYSQL_DATABASE ?? 'stonyx',
78
+ connectionLimit: parseInt(MYSQL_CONNECTION_LIMIT ?? '10'),
79
+ migrationsDir: MYSQL_MIGRATIONS_DIR ?? 'migrations',
80
+ migrationsTable: '__migrations',
81
+ } : undefined,
56
82
  restServer: {
57
83
  enabled: ORM_USE_REST_SERVER ?? 'true',
58
84
  route: ORM_REST_ROUTE ?? '/'
@@ -61,16 +87,13 @@ export default {
61
87
  };
62
88
  ```
63
89
 
64
- Then initialize the Stonyx framework, which auto-initializes all of its modules, including `@stonyx/rest-server`:
65
-
66
- ```js
67
- import Stonyx from 'stonyx';
68
- import config from './config/environment.js';
90
+ Then run the application via the Stonyx CLI, which auto-initializes all modules including the ORM:
69
91
 
70
- new Stonyx(config);
92
+ ```bash
93
+ stonyx serve
71
94
  ```
72
95
 
73
- For further framework initialization instructions, see the [Stonyx repository](https://github.com/abofs/stonyx).
96
+ For further framework instructions, see the [Stonyx repository](https://github.com/abofs/stonyx).
74
97
 
75
98
  ## Models
76
99
 
@@ -90,6 +113,22 @@ export default class OwnerModel extends Model {
90
113
  }
91
114
  ```
92
115
 
116
+ ### Overriding Plural Names
117
+
118
+ By default, model names are auto-pluralized for REST routes, JSON:API URLs, and DB table names (e.g., `animal` → `animals`). When auto-pluralization produces the wrong result, override it with `static pluralName`:
119
+
120
+ ```js
121
+ import { Model, attr } from '@stonyx/orm';
122
+
123
+ export default class PersonModel extends Model {
124
+ static pluralName = 'people';
125
+
126
+ name = attr('string');
127
+ }
128
+ ```
129
+
130
+ The override is picked up automatically during ORM initialization. All routes, JSON:API type references, and MySQL table names will use the overridden value.
131
+
93
132
  ## Serializers
94
133
 
95
134
  Based on the following sample payload structure which represents a poorly structure third-party data source:
@@ -154,7 +193,7 @@ export default function(value) {
154
193
 
155
194
  ## Database (DB) Integration
156
195
 
157
- The ORM can automatically save records to a JSON file with optional auto-save intervals.
196
+ The ORM can automatically save records to a JSON file or a directory of collection files, with optional auto-save intervals.
158
197
 
159
198
  ```js
160
199
  import Orm from '@stonyx/orm';
@@ -168,11 +207,47 @@ const dbRecord = Orm.db;
168
207
 
169
208
  Configuration options are in `config/environment.js`:
170
209
 
171
- * `DB_AUTO_SAVE`: Whether to auto-save.
210
+ * `DB_AUTO_SAVE`: Auto-save mode — `'true'` (cron-based interval), `'false'` (disabled), or `'onUpdate'` (save after every create/update/delete via REST API).
172
211
  * `DB_FILE`: File path to store data.
173
- * `DB_SAVE_INTERVAL`: Interval in seconds for auto-save.
212
+ * `DB_MODE`: Storage mode — `'file'` (single JSON file, default) or `'directory'` (one file per collection in a directory).
213
+ * `DB_DIRECTORY`: Directory name for collection files when mode is `'directory'` (default: `'db'`).
214
+ * `DB_SAVE_INTERVAL`: Interval in seconds for auto-save (only applies when `DB_AUTO_SAVE` is `'true'`).
174
215
  * `DB_SCHEMA_PATH`: Path to DB schema.
175
216
 
217
+ In directory mode, each collection is stored as `{directory}/{collection}.json` (e.g., `db/animals.json`, `db/owners.json`). The main `db.json` is kept as a skeleton with empty arrays. Migration commands are available: `stonyx db:migrate-to-directory` and `stonyx db:migrate-to-file`.
218
+
219
+ ### MySQL Mode
220
+
221
+ Set the `MYSQL_HOST` environment variable to enable MySQL persistence. The ORM loads all records into memory on startup and persists CRUD operations to MySQL automatically. Supports schema-aware migration generation, apply, rollback, and drift detection.
222
+
223
+ | Command | Description |
224
+ |---------|-------------|
225
+ | `stonyx db:generate-migration <desc>` | Generate a migration from model schema diffs |
226
+ | `stonyx db:migrate` | Apply pending migrations |
227
+ | `stonyx db:migrate:rollback` | Rollback the most recent migration |
228
+ | `stonyx db:migrate:status` | Show migration status |
229
+
230
+ ### Running MySQL Tests
231
+
232
+ The ORM includes integration tests that run against a real MySQL database. These are optional — all other tests work without MySQL.
233
+
234
+ **One-time setup:**
235
+
236
+ ```bash
237
+ # Requires local MySQL 8.0+ running
238
+ ./scripts/setup-test-db.sh
239
+ ```
240
+
241
+ This creates a `stonyx_orm_test` database with a `stonyx_test` user. Safe to re-run.
242
+
243
+ **Running tests:**
244
+
245
+ ```bash
246
+ npm test
247
+ ```
248
+
249
+ MySQL integration tests run automatically when MySQL is available. In CI (where `CI=true`), they skip gracefully.
250
+
176
251
  ## REST Server Integration
177
252
 
178
253
  The ORM can automatically register REST routes using your access classes.
@@ -289,6 +364,372 @@ GET /animals/1
289
364
 
290
365
  - Only available on GET endpoints (not POST/PATCH)
291
366
 
367
+ ## Lifecycle Hooks
368
+
369
+ The ORM provides a powerful middleware-based hook system that allows you to run custom logic before and after CRUD operations. Hooks are perfect for validation, transformation, side effects, authorization, and auditing.
370
+
371
+ ### Overview
372
+
373
+ Hooks run at key points in the request lifecycle:
374
+
375
+ - **Before hooks**: Run before the operation executes. **Can halt operations** by returning a value (status code or response object).
376
+ - **After hooks**: Run after the operation completes (logging, notifications, cache invalidation).
377
+
378
+ ### Event Naming Convention
379
+
380
+ Events follow the pattern: `{timing}:{operation}:{modelName}`
381
+
382
+ **Operations:**
383
+ - `list` - GET collection (`/animals`)
384
+ - `get` - GET single record (`/animals/1`)
385
+ - `create` - POST new record (`/animals`)
386
+ - `update` - PATCH existing record (`/animals/1`)
387
+ - `delete` - DELETE record (`/animals/1`)
388
+
389
+ **Examples:**
390
+ - `before:create:animal` - Before creating an animal
391
+ - `after:list:owner` - After fetching owner collection
392
+ - `before:update:trait` - Before updating a trait
393
+
394
+ ### Hook Context Object
395
+
396
+ Each hook receives a context object with comprehensive information:
397
+
398
+ ```javascript
399
+ {
400
+ model: 'animal', // Model name
401
+ operation: 'create', // Operation type
402
+ request, // Express request object
403
+ params, // URL params (e.g., { id: 5 })
404
+ body, // Request body (POST/PATCH)
405
+ query, // Query parameters
406
+ state, // Request state object
407
+ record, // Record instance (after hooks, single operations)
408
+ records, // Record array (after hooks, list operations)
409
+ response, // Response data (after hooks)
410
+ oldState, // Previous record state (update/delete operations only)
411
+ recordId, // Record ID (delete operations in after hooks)
412
+ }
413
+ ```
414
+
415
+ **Important Notes**:
416
+ - `oldState` is only available for `update` and `delete` operations
417
+ - It contains a deep copy of the record's state **before** the operation executes (captured before the `before` hook fires)
418
+ - The deep copy is created via JSON serialization (`JSON.parse(JSON.stringify())`) to ensure complete isolation
419
+ - For `delete` operations, `recordId` is provided in after hooks since the record may no longer exist in the store
420
+ - `oldState` is captured from `record.__data` or the record itself, providing access to the raw data structure
421
+
422
+ ### Usage Examples
423
+
424
+ #### Basic Hook Registration
425
+
426
+ ```javascript
427
+ import { beforeHook, afterHook } from '@stonyx/orm';
428
+
429
+ // Validation before creating - can halt by returning a value
430
+ beforeHook('create', 'animal', (context) => {
431
+ const { age } = context.body.data.attributes;
432
+ if (age < 0) {
433
+ return 400; // Halt with 400 Bad Request
434
+ }
435
+ // Return undefined to continue
436
+ });
437
+
438
+ // Logging after updates
439
+ afterHook('update', 'animal', (context) => {
440
+ console.log(`Animal ${context.record.id} was updated`);
441
+ });
442
+ ```
443
+
444
+ #### Halting Operations
445
+
446
+ Before hooks can halt operations by returning a value:
447
+
448
+ ```javascript
449
+ import { beforeHook } from '@stonyx/orm';
450
+
451
+ // Return a status code to halt with that HTTP status
452
+ beforeHook('create', 'animal', (context) => {
453
+ if (!context.body.data.attributes.name) {
454
+ return 400; // Bad Request
455
+ }
456
+ });
457
+
458
+ // Return an object to send a custom response
459
+ beforeHook('delete', 'animal', (context) => {
460
+ const animal = store.get('animal', context.params.id);
461
+ if (animal.protected) {
462
+ return { errors: [{ detail: 'Cannot delete protected animals' }] };
463
+ }
464
+ });
465
+
466
+ // Return undefined (or nothing) to allow operation to continue
467
+ beforeHook('update', 'animal', (context) => {
468
+ console.log('Update proceeding...');
469
+ // No return = operation continues
470
+ });
471
+ ```
472
+
473
+ #### Data Transformation
474
+
475
+ ```javascript
476
+ // Normalize data before saving
477
+ beforeHook('create', 'owner', (context) => {
478
+ const attrs = context.body.data.attributes;
479
+ if (attrs.email) {
480
+ attrs.email = attrs.email.toLowerCase().trim();
481
+ }
482
+ });
483
+ ```
484
+
485
+ #### Side Effects
486
+
487
+ ```javascript
488
+ // Send notification after animal is adopted (using oldState to detect changes)
489
+ afterHook('update', 'animal', async (context) => {
490
+ // Use oldState to compare before/after values
491
+ if (context.oldState && context.oldState.owner !== context.record.owner) {
492
+ await sendNotification({
493
+ type: 'adoption',
494
+ animalId: context.record.id,
495
+ previousOwner: context.oldState.owner,
496
+ newOwner: context.record.owner
497
+ });
498
+ }
499
+ });
500
+
501
+ // Cache invalidation
502
+ afterHook('delete', 'animal', async (context) => {
503
+ await cache.invalidate(`owner:${context.params.id}:pets`);
504
+ });
505
+ ```
506
+
507
+ #### Change Detection
508
+
509
+ The `oldState` property (available for `update` and `delete` operations) enables precise change tracking:
510
+
511
+ ```javascript
512
+ // Detect specific field changes
513
+ afterHook('update', 'animal', async (context) => {
514
+ if (!context.oldState) return; // No old state for create operations
515
+
516
+ // Check if a specific field changed
517
+ if (context.oldState.age !== context.record.age) {
518
+ console.log(`Age changed from ${context.oldState.age} to ${context.record.age}`);
519
+ }
520
+
521
+ // Track multiple field changes
522
+ const changedFields = [];
523
+ for (const key in context.record.__data) {
524
+ if (context.oldState[key] !== context.record.__data[key]) {
525
+ changedFields.push(key);
526
+ }
527
+ }
528
+
529
+ if (changedFields.length > 0) {
530
+ console.log(`Fields changed: ${changedFields.join(', ')}`);
531
+ }
532
+ });
533
+
534
+ // Access deleted record data
535
+ afterHook('delete', 'animal', async (context) => {
536
+ console.log(`Deleted animal: ${context.oldState.type} (age: ${context.oldState.age})`);
537
+ // oldState contains full snapshot of the deleted record
538
+ });
539
+ ```
540
+
541
+ #### Authorization
542
+
543
+ ```javascript
544
+ // Additional access control - halt with 403 if unauthorized
545
+ beforeHook('delete', 'animal', (context) => {
546
+ const user = context.state.currentUser;
547
+ const animal = store.get('animal', context.params.id);
548
+
549
+ if (animal.owner !== user.id && !user.isAdmin) {
550
+ return 403; // Forbidden
551
+ }
552
+ });
553
+ ```
554
+
555
+ #### Auditing
556
+
557
+ ```javascript
558
+ // Audit log for all changes with field-level change tracking
559
+ afterHook('update', 'animal', async (context) => {
560
+ // Compare oldState with current record to capture exact changes
561
+ const changes = {};
562
+ if (context.oldState) {
563
+ for (const [key, newValue] of Object.entries(context.record.__data || context.record)) {
564
+ if (context.oldState[key] !== newValue) {
565
+ changes[key] = { from: context.oldState[key], to: newValue };
566
+ }
567
+ }
568
+ }
569
+
570
+ await auditLog.create({
571
+ operation: 'update',
572
+ model: context.model,
573
+ recordId: context.record.id,
574
+ userId: context.state.currentUser?.id,
575
+ timestamp: new Date(),
576
+ changes // Precise field-level changes: { age: { from: 2, to: 3 } }
577
+ });
578
+ });
579
+
580
+ // Audit deletes with full record snapshot
581
+ afterHook('delete', 'animal', async (context) => {
582
+ await auditLog.create({
583
+ operation: 'delete',
584
+ model: context.model,
585
+ recordId: context.recordId,
586
+ userId: context.state.currentUser?.id,
587
+ timestamp: new Date(),
588
+ deletedData: context.oldState // Full snapshot of deleted record
589
+ });
590
+ });
591
+ ```
592
+
593
+ #### Error Handling
594
+
595
+ For after hooks, wrap in try/catch if errors should not propagate:
596
+
597
+ ```javascript
598
+ afterHook('create', 'animal', async (context) => {
599
+ try {
600
+ await sendWelcomeEmail(context.record.owner);
601
+ } catch (error) {
602
+ // Error is logged but doesn't fail the create operation
603
+ console.error('Failed to send welcome email:', error);
604
+ }
605
+ });
606
+ ```
607
+
608
+ ### Hook Lifecycle Management
609
+
610
+ #### Unsubscribing
611
+
612
+ ```javascript
613
+ import { beforeHook } from '@stonyx/orm';
614
+
615
+ // Get unsubscribe function
616
+ const unsubscribe = beforeHook('create', 'animal', handler);
617
+
618
+ // Later, remove the hook
619
+ unsubscribe();
620
+ ```
621
+
622
+ #### Clearing Hooks
623
+
624
+ ```javascript
625
+ import { clearHook, clearAllHooks } from '@stonyx/orm';
626
+
627
+ // Remove all hooks for a specific operation:model
628
+ clearHook('create', 'animal');
629
+
630
+ // Remove only before hooks
631
+ clearHook('create', 'animal', 'before');
632
+
633
+ // Remove only after hooks
634
+ clearHook('create', 'animal', 'after');
635
+
636
+ // Remove ALL hooks (useful for testing)
637
+ clearAllHooks();
638
+ ```
639
+
640
+ ### Advanced Patterns
641
+
642
+ #### Conditional Hooks
643
+
644
+ ```javascript
645
+ beforeHook('update', 'animal', (context) => {
646
+ // Only validate if age is being updated
647
+ if ('age' in context.body.data.attributes) {
648
+ const { age } = context.body.data.attributes;
649
+ if (age < 0 || age > 50) {
650
+ return 400; // Bad Request
651
+ }
652
+ }
653
+ });
654
+ ```
655
+
656
+ #### Cross-Model Hooks
657
+
658
+ ```javascript
659
+ // Update owner's pet count when animal is created
660
+ afterHook('create', 'animal', async (context) => {
661
+ const owner = store.get('owner', context.record.owner);
662
+ if (owner) {
663
+ owner.petCount = (owner.petCount || 0) + 1;
664
+ }
665
+ });
666
+ ```
667
+
668
+ #### Sequential Middleware
669
+
670
+ ```javascript
671
+ // Multiple hooks run in registration order
672
+ beforeHook('create', 'post', (context) => {
673
+ console.log('First middleware');
674
+ context.customData = { checked: true };
675
+ });
676
+
677
+ beforeHook('create', 'post', (context) => {
678
+ console.log('Second middleware');
679
+ // Can access data from previous hooks
680
+ if (!context.customData?.checked) {
681
+ return 403;
682
+ }
683
+ });
684
+ ```
685
+
686
+ ### Hook Execution Order
687
+
688
+ 1. **Before hooks** fire first (sequentially, in registration order)
689
+ 2. **Main operation** executes (if no before hook halted)
690
+ 3. **After hooks** fire last (sequentially, in registration order)
691
+
692
+ Before hooks can halt the operation by returning a value. After hooks run after completion and cannot halt.
693
+
694
+ ### Best Practices
695
+
696
+ 1. **Keep hooks focused**: Each hook should do one thing well
697
+ 2. **Use async/await**: Hooks support async functions for consistency
698
+ 3. **Return values intentionally**: Only return a value from before hooks when you want to halt
699
+ 4. **Document side effects**: Make it clear what each hook does
700
+ 5. **Test hooks independently**: Write unit tests for hook logic
701
+ 6. **Avoid heavy operations**: Keep hooks fast to maintain performance
702
+ 7. **Clean up in tests**: Use `clearAllHooks()` in test teardown
703
+
704
+ ### Testing Hooks
705
+
706
+ ```javascript
707
+ import { beforeHook, clearAllHooks } from '@stonyx/orm';
708
+
709
+ // Clean up after each test
710
+ afterEach(() => {
711
+ clearAllHooks();
712
+ });
713
+
714
+ // Test that validation hook halts with 400
715
+ test('validation hook rejects negative age', async () => {
716
+ beforeHook('create', 'animal', (context) => {
717
+ if (context.body.data.attributes.age < 0) {
718
+ return 400;
719
+ }
720
+ });
721
+
722
+ const response = await fetch('/animals', {
723
+ method: 'POST',
724
+ body: JSON.stringify({
725
+ data: { attributes: { age: -5 } }
726
+ })
727
+ });
728
+
729
+ assert.strictEqual(response.status, 400, 'Hook halted with 400');
730
+ });
731
+ ```
732
+
292
733
  ## Exported Helpers
293
734
 
294
735
  | Export | Description |
@@ -297,9 +738,18 @@ GET /animals/1
297
738
  | `belongsTo` | Define a one-to-one relationship. |
298
739
  | `hasMany` | Define a one-to-many relationship. |
299
740
  | `createRecord` | Instantiate a record with proper serialization and relationships. |
741
+ | `updateRecord` | Update an existing record with new data. |
300
742
  | `store` | Singleton store for all model instances. |
301
743
  | `relationships` | Access all relationships (`hasMany`, `belongsTo`, `global`, `pending`). |
744
+ | `beforeHook` | Register a before hook that can halt operations. |
745
+ | `afterHook` | Register an after hook for post-operation logic. |
746
+ | `clearHook` | Clear hooks for a specific operation:model. |
747
+ | `clearAllHooks` | Clear all registered hooks (useful for testing). |
748
+
749
+ ## Project Structure
750
+
751
+ For a full architectural reference, see [project-structure.md](project-structure.md).
302
752
 
303
753
  ## License
304
754
 
305
- Apache — do what you want, just keep attribution.
755
+ Apache 2.0 see [LICENSE.md](LICENSE.md).
@@ -4,20 +4,32 @@ const {
4
4
  ORM_REST_ROUTE,
5
5
  ORM_SERIALIZER_PATH,
6
6
  ORM_TRANSFORM_PATH,
7
+ ORM_VIEW_PATH,
7
8
  ORM_USE_REST_SERVER,
8
9
  DB_AUTO_SAVE,
9
10
  DB_FILE,
11
+ DB_MODE,
12
+ DB_DIRECTORY,
10
13
  DB_SCHEMA_PATH,
11
- DB_SAVE_INTERVAL
12
- } = process;
14
+ DB_SAVE_INTERVAL,
15
+ MYSQL_HOST,
16
+ MYSQL_PORT,
17
+ MYSQL_USER,
18
+ MYSQL_PASSWORD,
19
+ MYSQL_DATABASE,
20
+ MYSQL_CONNECTION_LIMIT,
21
+ MYSQL_MIGRATIONS_DIR,
22
+ } = process.env;
13
23
 
14
24
  export default {
15
25
  logColor: 'white',
16
26
  logMethod: 'db',
17
27
 
18
28
  db: {
19
- autosave: DB_AUTO_SAVE ?? 'false',
29
+ autosave: DB_AUTO_SAVE ?? 'false', // 'true' (cron interval), 'false' (disabled), 'onUpdate' (save after each write op)
20
30
  file: DB_FILE ?? 'db.json',
31
+ mode: DB_MODE ?? 'file', // 'file' (single db.json) or 'directory' (one file per collection)
32
+ directory: DB_DIRECTORY ?? 'db', // directory name for collection files when mode is 'directory'
21
33
  saveInterval: DB_SAVE_INTERVAL ?? 60 * 60, // 1 hour
22
34
  schema: DB_SCHEMA_PATH ?? './config/db-schema.js'
23
35
  },
@@ -25,10 +37,21 @@ export default {
25
37
  access: ORM_ACCESS_PATH ?? './access', // Optional for restServer access hooks
26
38
  model: ORM_MODEL_PATH ?? './models',
27
39
  serializer: ORM_SERIALIZER_PATH ?? './serializers',
28
- transform: ORM_TRANSFORM_PATH ?? './transforms'
40
+ transform: ORM_TRANSFORM_PATH ?? './transforms',
41
+ view: ORM_VIEW_PATH ?? './views'
29
42
  },
43
+ mysql: MYSQL_HOST ? {
44
+ host: MYSQL_HOST ?? 'localhost',
45
+ port: parseInt(MYSQL_PORT ?? '3306'),
46
+ user: MYSQL_USER ?? 'root',
47
+ password: MYSQL_PASSWORD ?? '',
48
+ database: MYSQL_DATABASE ?? 'stonyx',
49
+ connectionLimit: parseInt(MYSQL_CONNECTION_LIMIT ?? '10'),
50
+ migrationsDir: MYSQL_MIGRATIONS_DIR ?? 'migrations',
51
+ migrationsTable: '__migrations',
52
+ } : undefined,
30
53
  restServer: {
31
- enabled: ORM_USE_REST_SERVER ?? 'true', // Whether to load restServer for automatic route setup or
54
+ enabled: ORM_USE_REST_SERVER ?? 'true', // Whether to load restServer for automatic route setup or
32
55
  route: ORM_REST_ROUTE ?? '/',
33
56
  }
34
- }
57
+ }
package/package.json CHANGED
@@ -4,13 +4,20 @@
4
4
  "stonyx-async",
5
5
  "stonyx-module"
6
6
  ],
7
- "version": "0.2.1-alpha.3",
7
+ "version": "0.2.1-alpha.31",
8
8
  "description": "",
9
9
  "main": "src/main.js",
10
10
  "type": "module",
11
+ "bin": {
12
+ "stonyx-orm": "./src/cli.js"
13
+ },
11
14
  "exports": {
12
15
  ".": "./src/index.js",
13
- "./db": "./src/exports/db.js"
16
+ "./db": "./src/exports/db.js",
17
+ "./standalone-db": "./src/standalone-db.js",
18
+ "./migrate": "./src/migrate.js",
19
+ "./commands": "./src/commands.js",
20
+ "./hooks": "./src/hooks.js"
14
21
  },
15
22
  "repository": {
16
23
  "type": "git",
@@ -21,6 +28,11 @@
21
28
  "contributors": [
22
29
  "Stone Costa <stone.costa@synamicd.com>"
23
30
  ],
31
+ "files": [
32
+ "src",
33
+ "config",
34
+ "README.md"
35
+ ],
24
36
  "publishConfig": {
25
37
  "access": "public",
26
38
  "provenance": true
@@ -30,17 +42,30 @@
30
42
  },
31
43
  "homepage": "https://github.com/abofs/stonyx-orm#readme",
32
44
  "dependencies": {
33
- "stonyx": "^0.2.2",
34
- "@stonyx/events": "^0.1.0",
35
- "@stonyx/cron": "^0.2.0"
45
+ "@stonyx/cron": "0.2.1-beta.29",
46
+ "@stonyx/events": "0.1.1-beta.9",
47
+ "stonyx": "0.2.3-beta.11"
48
+ },
49
+ "peerDependencies": {
50
+ "@stonyx/rest-server": ">=0.2.1-beta.14",
51
+ "mysql2": "^3.0.0"
52
+ },
53
+ "peerDependenciesMeta": {
54
+ "mysql2": {
55
+ "optional": true
56
+ },
57
+ "@stonyx/rest-server": {
58
+ "optional": true
59
+ }
36
60
  },
37
61
  "devDependencies": {
38
- "@stonyx/rest-server": "^0.2.0",
39
- "@stonyx/utils": "^0.2.2",
62
+ "@stonyx/rest-server": "0.2.1-beta.30",
63
+ "@stonyx/utils": "0.2.3-beta.7",
64
+ "mysql2": "^3.20.0",
40
65
  "qunit": "^2.24.1",
41
66
  "sinon": "^21.0.0"
42
67
  },
43
68
  "scripts": {
44
- "test": "qunit --require ./stonyx-bootstrap.cjs"
69
+ "test": "stonyx test"
45
70
  }
46
71
  }