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