@stonyx/orm 0.2.1-beta.76 → 0.2.1-beta.78
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 +5 -1
- package/src/cli.js +177 -0
- package/src/record.js +5 -0
- package/src/standalone-db.js +176 -0
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
|
@@ -4,13 +4,17 @@
|
|
|
4
4
|
"stonyx-async",
|
|
5
5
|
"stonyx-module"
|
|
6
6
|
],
|
|
7
|
-
"version": "0.2.1-beta.
|
|
7
|
+
"version": "0.2.1-beta.78",
|
|
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
16
|
"./db": "./src/exports/db.js",
|
|
17
|
+
"./standalone-db": "./src/standalone-db.js",
|
|
14
18
|
"./migrate": "./src/migrate.js",
|
|
15
19
|
"./commands": "./src/commands.js",
|
|
16
20
|
"./hooks": "./src/hooks.js"
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Standalone CLI for ORM database operations.
|
|
5
|
+
*
|
|
6
|
+
* Performs CRUD operations on the JSON database without requiring
|
|
7
|
+
* the full Stonyx bootstrap. Supports both file and directory modes.
|
|
8
|
+
*
|
|
9
|
+
* Usage:
|
|
10
|
+
* stonyx-orm create <collection> <json-data>
|
|
11
|
+
* stonyx-orm list <collection>
|
|
12
|
+
* stonyx-orm get <collection> <id>
|
|
13
|
+
* stonyx-orm delete <collection> <id>
|
|
14
|
+
*
|
|
15
|
+
* Configuration (environment variables):
|
|
16
|
+
* DB_MODE — 'file' or 'directory' (default: 'directory')
|
|
17
|
+
* DB_PATH — Path to db.json (default: 'db.json')
|
|
18
|
+
* DB_DIRECTORY — Directory name for collection files (default: 'db')
|
|
19
|
+
*
|
|
20
|
+
* Configuration (CLI flag):
|
|
21
|
+
* --config <path> — Path to a JSON config file with { mode, dbPath, directory }
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import StandaloneDB from './standalone-db.js';
|
|
25
|
+
import fs from 'fs/promises';
|
|
26
|
+
|
|
27
|
+
const USAGE = `Usage: stonyx-orm <command> [options]
|
|
28
|
+
|
|
29
|
+
Commands:
|
|
30
|
+
create <collection> <json-data> Create a record
|
|
31
|
+
list <collection> List all records
|
|
32
|
+
get <collection> <id> Get a record by ID
|
|
33
|
+
delete <collection> <id> Delete a record by ID
|
|
34
|
+
|
|
35
|
+
Options:
|
|
36
|
+
--config <path> Path to JSON config file
|
|
37
|
+
--help Show this help message
|
|
38
|
+
|
|
39
|
+
Environment variables:
|
|
40
|
+
DB_MODE 'file' or 'directory' (default: 'directory')
|
|
41
|
+
DB_PATH Path to db.json (default: 'db.json')
|
|
42
|
+
DB_DIRECTORY Directory name for collection files (default: 'db')`;
|
|
43
|
+
|
|
44
|
+
async function loadConfig(args) {
|
|
45
|
+
const config = {};
|
|
46
|
+
|
|
47
|
+
// Check for --config flag
|
|
48
|
+
const configIndex = args.indexOf('--config');
|
|
49
|
+
|
|
50
|
+
if (configIndex !== -1 && args[configIndex + 1]) {
|
|
51
|
+
const configPath = args[configIndex + 1];
|
|
52
|
+
|
|
53
|
+
try {
|
|
54
|
+
const content = await fs.readFile(configPath, 'utf-8');
|
|
55
|
+
Object.assign(config, JSON.parse(content));
|
|
56
|
+
} catch (err) {
|
|
57
|
+
console.error(`Error reading config file '${configPath}': ${err.message}`);
|
|
58
|
+
process.exit(1);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// Remove --config and its value from args
|
|
62
|
+
args.splice(configIndex, 2);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Environment variables override config file, config file overrides defaults
|
|
66
|
+
return {
|
|
67
|
+
mode: process.env.DB_MODE || config.mode || 'directory',
|
|
68
|
+
dbPath: process.env.DB_PATH || config.dbPath || 'db.json',
|
|
69
|
+
directory: process.env.DB_DIRECTORY || config.directory || 'db',
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function parseArgs(argv) {
|
|
74
|
+
// Strip node binary and script path
|
|
75
|
+
const args = argv.slice(2);
|
|
76
|
+
|
|
77
|
+
if (args.includes('--help') || args.includes('-h') || args.length === 0) {
|
|
78
|
+
console.log(USAGE);
|
|
79
|
+
process.exit(0);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return args;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function run() {
|
|
86
|
+
const args = parseArgs(process.argv);
|
|
87
|
+
const config = await loadConfig(args);
|
|
88
|
+
const db = new StandaloneDB(config);
|
|
89
|
+
|
|
90
|
+
const [command, collection, ...rest] = args;
|
|
91
|
+
|
|
92
|
+
if (!command) {
|
|
93
|
+
console.error('Error: No command specified.\n');
|
|
94
|
+
console.log(USAGE);
|
|
95
|
+
process.exit(1);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (!collection && command !== '--help') {
|
|
99
|
+
console.error(`Error: No collection specified for '${command}' command.\n`);
|
|
100
|
+
console.log(USAGE);
|
|
101
|
+
process.exit(1);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
switch (command) {
|
|
106
|
+
case 'list': {
|
|
107
|
+
const records = await db.list(collection);
|
|
108
|
+
console.log(JSON.stringify(records, null, 2));
|
|
109
|
+
break;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
case 'get': {
|
|
113
|
+
const id = rest[0];
|
|
114
|
+
|
|
115
|
+
if (!id) {
|
|
116
|
+
console.error("Error: 'get' command requires an <id> argument.");
|
|
117
|
+
process.exit(1);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const record = await db.get(collection, id);
|
|
121
|
+
|
|
122
|
+
if (!record) {
|
|
123
|
+
console.error(`Record with id '${id}' not found in '${collection}'.`);
|
|
124
|
+
process.exit(1);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
console.log(JSON.stringify(record, null, 2));
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
case 'create': {
|
|
132
|
+
const jsonStr = rest.join(' ');
|
|
133
|
+
|
|
134
|
+
if (!jsonStr) {
|
|
135
|
+
console.error("Error: 'create' command requires <json-data> argument.");
|
|
136
|
+
process.exit(1);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
let data;
|
|
140
|
+
|
|
141
|
+
try {
|
|
142
|
+
data = JSON.parse(jsonStr);
|
|
143
|
+
} catch {
|
|
144
|
+
console.error(`Error: Invalid JSON data: ${jsonStr}`);
|
|
145
|
+
process.exit(1);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const created = await db.create(collection, data);
|
|
149
|
+
console.log(JSON.stringify(created, null, 2));
|
|
150
|
+
break;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
case 'delete': {
|
|
154
|
+
const deleteId = rest[0];
|
|
155
|
+
|
|
156
|
+
if (!deleteId) {
|
|
157
|
+
console.error("Error: 'delete' command requires an <id> argument.");
|
|
158
|
+
process.exit(1);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const removed = await db.delete(collection, deleteId);
|
|
162
|
+
console.log(JSON.stringify(removed, null, 2));
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
default:
|
|
167
|
+
console.error(`Error: Unknown command '${command}'.\n`);
|
|
168
|
+
console.log(USAGE);
|
|
169
|
+
process.exit(1);
|
|
170
|
+
}
|
|
171
|
+
} catch (err) {
|
|
172
|
+
console.error(`Error: ${err.message}`);
|
|
173
|
+
process.exit(1);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
run();
|
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
|
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Standalone JSON database layer for CLI usage.
|
|
3
|
+
*
|
|
4
|
+
* Reads and writes directly to JSON files without requiring the Stonyx
|
|
5
|
+
* bootstrap, ORM init, or any framework dependencies. Supports both
|
|
6
|
+
* single-file and directory modes.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import fs from 'fs/promises';
|
|
10
|
+
import path from 'path';
|
|
11
|
+
|
|
12
|
+
export default class StandaloneDB {
|
|
13
|
+
/**
|
|
14
|
+
* @param {Object} options
|
|
15
|
+
* @param {string} options.dbPath - Path to db.json (file mode) or parent of db dir (directory mode)
|
|
16
|
+
* @param {string} [options.mode='directory'] - 'file' or 'directory'
|
|
17
|
+
* @param {string} [options.directory='db'] - Directory name when mode is 'directory'
|
|
18
|
+
*/
|
|
19
|
+
constructor(options = {}) {
|
|
20
|
+
this.mode = options.mode || 'directory';
|
|
21
|
+
this.dbPath = options.dbPath || 'db.json';
|
|
22
|
+
this.directory = options.directory || 'db';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Resolve the directory path for directory mode.
|
|
27
|
+
*/
|
|
28
|
+
getDirPath() {
|
|
29
|
+
const dbDir = path.dirname(path.resolve(this.dbPath));
|
|
30
|
+
return path.join(dbDir, this.directory);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* List available collections by inspecting either the db.json keys
|
|
35
|
+
* or the files in the db directory.
|
|
36
|
+
*/
|
|
37
|
+
async getCollections() {
|
|
38
|
+
if (this.mode === 'directory') {
|
|
39
|
+
const dirPath = this.getDirPath();
|
|
40
|
+
|
|
41
|
+
try {
|
|
42
|
+
const files = await fs.readdir(dirPath);
|
|
43
|
+
return files
|
|
44
|
+
.filter(f => f.endsWith('.json'))
|
|
45
|
+
.map(f => f.replace('.json', ''));
|
|
46
|
+
} catch {
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// File mode — read db.json and return its top-level keys
|
|
52
|
+
try {
|
|
53
|
+
const data = await this._readJSON(this.dbPath);
|
|
54
|
+
return Object.keys(data).filter(key => Array.isArray(data[key]));
|
|
55
|
+
} catch {
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Read all records for a collection.
|
|
62
|
+
*/
|
|
63
|
+
async readCollection(collection) {
|
|
64
|
+
if (this.mode === 'directory') {
|
|
65
|
+
const filePath = path.join(this.getDirPath(), `${collection}.json`);
|
|
66
|
+
return this._readJSON(filePath);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const data = await this._readJSON(this.dbPath);
|
|
70
|
+
return data[collection] || [];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Write all records for a collection.
|
|
75
|
+
*/
|
|
76
|
+
async writeCollection(collection, records) {
|
|
77
|
+
if (this.mode === 'directory') {
|
|
78
|
+
const dirPath = this.getDirPath();
|
|
79
|
+
await fs.mkdir(dirPath, { recursive: true });
|
|
80
|
+
|
|
81
|
+
const filePath = path.join(dirPath, `${collection}.json`);
|
|
82
|
+
await this._writeJSON(filePath, records);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// File mode — read full db, update collection, write back
|
|
87
|
+
let data;
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
data = await this._readJSON(this.dbPath);
|
|
91
|
+
} catch {
|
|
92
|
+
data = {};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
data[collection] = records;
|
|
96
|
+
await this._writeJSON(this.dbPath, data);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Get a single record by id.
|
|
101
|
+
*/
|
|
102
|
+
async get(collection, id) {
|
|
103
|
+
const records = await this.readCollection(collection);
|
|
104
|
+
const numericId = Number(id);
|
|
105
|
+
|
|
106
|
+
return records.find(r =>
|
|
107
|
+
r.id === id || r.id === numericId
|
|
108
|
+
) || null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* List all records in a collection.
|
|
113
|
+
*/
|
|
114
|
+
async list(collection) {
|
|
115
|
+
return this.readCollection(collection);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Create a new record. Auto-assigns an integer id if none provided.
|
|
120
|
+
*/
|
|
121
|
+
async create(collection, data) {
|
|
122
|
+
const records = await this.readCollection(collection);
|
|
123
|
+
|
|
124
|
+
if (!data.id) {
|
|
125
|
+
const maxId = records.reduce((max, r) => {
|
|
126
|
+
const rid = typeof r.id === 'number' ? r.id : 0;
|
|
127
|
+
return rid > max ? rid : max;
|
|
128
|
+
}, 0);
|
|
129
|
+
|
|
130
|
+
data.id = maxId + 1;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Check for duplicate id
|
|
134
|
+
const existing = records.find(r => r.id === data.id);
|
|
135
|
+
if (existing) {
|
|
136
|
+
throw new Error(`Record with id ${data.id} already exists in '${collection}'`);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
records.push(data);
|
|
140
|
+
await this.writeCollection(collection, records);
|
|
141
|
+
|
|
142
|
+
return data;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Delete a record by id.
|
|
147
|
+
*/
|
|
148
|
+
async delete(collection, id) {
|
|
149
|
+
const records = await this.readCollection(collection);
|
|
150
|
+
const numericId = Number(id);
|
|
151
|
+
|
|
152
|
+
const index = records.findIndex(r =>
|
|
153
|
+
r.id === id || r.id === numericId
|
|
154
|
+
);
|
|
155
|
+
|
|
156
|
+
if (index === -1) {
|
|
157
|
+
throw new Error(`Record with id '${id}' not found in '${collection}'`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const [removed] = records.splice(index, 1);
|
|
161
|
+
await this.writeCollection(collection, records);
|
|
162
|
+
|
|
163
|
+
return removed;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// -- Private helpers --
|
|
167
|
+
|
|
168
|
+
async _readJSON(filePath) {
|
|
169
|
+
const content = await fs.readFile(filePath, 'utf-8');
|
|
170
|
+
return JSON.parse(content);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async _writeJSON(filePath, data) {
|
|
174
|
+
await fs.writeFile(filePath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
|
|
175
|
+
}
|
|
176
|
+
}
|