json-database-st 1.0.5 → 1.0.6

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 (2) hide show
  1. package/README.md +76 -57
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,73 +1,95 @@
1
- # JSON Database By ST
1
+ # JSON Database ST
2
2
 
3
- [![npm version](https://badge.fury.io/js/json-database-st.svg)](https://badge.fury.io/js/json-database-st)
3
+ [![NPM Version](https://badge.fury.io/js/json-database-st.svg)](https://badge.fury.io/js/json-database-st)
4
+ [![NPM Downloads](https://img.shields.io/npm/dm/json-database-st.svg)](https://www.npmjs.com/package/json-database-st)
4
5
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
6
 
6
- A simple, promise-based JSON file database for Node.js applications. Features atomic file operations, lodash integration for easy data access, transactions, batching, and basic querying.
7
+ A secure, performant, and feature-rich JSON file database for Node.js. Designed for projects that need simple, persistent data storage without the overhead of a traditional database server, but with modern features like **encryption, indexing, and schema validation**.
7
8
 
8
- Ideal for small projects, prototypes, configuration management, or simple data persistence needs where a full database server is overkill.
9
+ Ideal for small to medium-sized projects, configuration management, user session data, or any application where data safety and integrity are critical.
9
10
 
10
11
  ## Features
11
12
 
12
- * **Promise-based API:** Fully asynchronous methods.
13
- * **Atomic Writes:** Prevents data corruption from concurrent writes using an internal lock.
14
- * **Simple API:** `get`, `set`, `has`, `delete`, `push` (deep unique), `pull` (deep removal), `clear`.
15
- * **Lodash Integration:** Use dot/bracket notation paths (e.g., `'users.john.age'`) via `lodash`.
16
- * **Transactions:** Execute multiple reads/writes as a single atomic unit (`transaction`).
17
- * **Batch Operations:** Efficiently perform multiple `set`, `delete`, `push`, or `pull` operations in one atomic write (`batch`).
18
- * **Basic Querying:** Filter object properties based on a predicate function (`query`).
19
- * **File Auto-Creation:** Creates the JSON file (with `{}`) if it doesn't exist.
20
- * **Pretty Print Option:** Optionally format the JSON file for readability.
21
- * **Dependencies:** Only requires `lodash`. Uses built-in `fs.promises`.
13
+ * **🔒 Security First:**
14
+ * **Encryption at Rest:** Built-in AES-256-GCM encryption protects your data on disk.
15
+ * **Path Traversal Protection:** Prevents malicious file path inputs.
16
+ * **Secure by Default:** Fails safely if data is tampered with or the key is wrong.
17
+
18
+ * **⚡ High-Performance Indexing:**
19
+ * Create indexes on your data fields (e.g., `users.email`).
20
+ * Enjoy near-instantaneous `O(1)` lookups with `findByIndex()`, avoiding slow full-database scans.
21
+
22
+ * **🤝 Atomic & Reliable:**
23
+ * **Atomic Writes:** All write operations (`set`, `transaction`, `batch`, etc.) are queued and executed atomically, preventing data corruption.
24
+ * **Transactions:** Execute complex multi-step operations as a single, indivisible unit.
25
+ * **Batching:** Perform multiple simple operations in a single, efficient disk write.
26
+
27
+ * **✅ Data Integrity:**
28
+ * **Schema Validation:** Integrate with libraries like Zod or Joi to enforce data structures on every write, preventing bad data from ever being saved.
29
+ * **Deep Uniqueness:** The `push()` method automatically prevents duplicate entries in arrays using deep object comparison.
30
+
31
+ * **📢 Modern & DX-Focused API:**
32
+ * **Promise-based:** Fully asynchronous `async/await` friendly API.
33
+ * **Event-Driven:** Emits `write`, `change`, and `error` events for reactive programming, auditing, or real-time updates.
34
+ * **Intuitive & Powerful:** A clean API (`get`, `set`, `find`) powered by `lodash` for flexible path notation.
22
35
 
23
36
  ## Installation
24
37
 
25
38
  ```bash
26
- # Make sure you have lodash installed as well
39
+ # This package requires lodash as a peer dependency
27
40
  npm install json-database-st lodash
28
41
  ```
29
42
 
43
+ ## Quick Start: Secure & Indexed Database
30
44
 
31
- ## Quick Start
45
+ This example demonstrates setting up a secure, encrypted database with a high-speed index on user emails.
32
46
 
33
47
  ```javascript
34
- const JSONDatabase = require('json-database-st'); // Use your package name
48
+ const JSONDatabase = require('json-database-st');
35
49
  const path = require('path');
50
+ const crypto = require('crypto');
51
+
52
+ // 1. Generate a secure key (run once and store it in environment variables)
53
+ // const encryptionKey = crypto.randomBytes(32).toString('hex');
54
+ // console.log('Your secure encryption key:', encryptionKey);
55
+ const ENCRYPTION_KEY = 'd0a7e8c1b2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9'; // Example key
36
56
 
37
- // Initialize (creates 'mydata.json' if needed)
38
- const db = new JSONDatabase(path.join(__dirname, 'mydata'), { prettyPrint: true });
57
+ // 2. Initialize the database with encryption and an index
58
+ const db = new JSONDatabase(path.join(__dirname, 'secure-data.json'), {
59
+ encryptionKey: ENCRYPTION_KEY,
60
+ indices: [
61
+ { name: 'user-email', path: 'users', field: 'email', unique: true }
62
+ ]
63
+ });
39
64
 
40
65
  async function run() {
41
66
  try {
42
- // Set data
43
- await db.set('user.name', 'Bob');
44
- await db.set('user.settings.theme', 'dark');
45
-
46
- // Get data
47
- const theme = await db.get('user.settings.theme', 'light'); // Default value
48
- console.log(`Theme: ${theme}`); // -> Theme: dark
49
-
50
- // Push unique items (uses deep compare)
51
- await db.push('user.tags', 'vip', { type: 'beta' });
52
- await db.push('user.tags', { type: 'beta' }); // Won't be added again
53
- console.log('Tags:', await db.get('user.tags')); // -> ['vip', { type: 'beta' }]
54
-
55
- // Check existence
56
- console.log('Has user age?', await db.has('user.age')); // -> false
57
-
58
- // Delete
59
- await db.delete('user.settings');
60
- console.log('User object:', await db.get('user')); // -> { name: 'Bob', tags: [...] }
61
-
62
- // Get Stats
63
- console.log('DB Stats:', db.getStats());
67
+ // 3. Set data. The index will be updated automatically.
68
+ await db.set('users.alice', { email: 'alice@example.com', name: 'Alice' });
69
+ await db.set('users.bob', { email: 'bob@example.com', name: 'Bob' });
70
+
71
+ // This would throw an IndexViolationError because the email is not unique
72
+ // await db.set('users.impostor', { email: 'alice@example.com', name: 'Impostor' });
73
+
74
+ // 4. Use the high-speed index for an instant lookup
75
+ console.log('--- Finding user with index ---');
76
+ const alice = await db.findByIndex('user-email', 'alice@example.com');
77
+ console.log('Found user:', alice); // -> { email: 'alice@example.com', name: 'Alice' }
78
+
79
+ // 5. Perform a transaction
80
+ await db.transaction(data => {
81
+ data.users.bob.lastLogin = Date.now();
82
+ return data; // Must return the modified data
83
+ });
84
+
85
+ console.log('\n--- Bob after transaction ---');
86
+ console.log(await db.get('users.bob'));
64
87
 
65
88
  } catch (err) {
66
89
  console.error('Database operation failed:', err);
67
90
  } finally {
68
- // IMPORTANT: Always close the DB when done
91
+ // 6. IMPORTANT: Always close the DB for a graceful shutdown
69
92
  await db.close();
70
- console.log('Database closed.');
71
93
  }
72
94
  }
73
95
 
@@ -76,9 +98,9 @@ run();
76
98
 
77
99
  ## Documentation
78
100
 
79
- **Full API details and advanced usage examples are available in the hosted documentation:**
101
+ **Full API details and advanced usage examples are available on the hosted documentation site:**
80
102
 
81
- **[View Documentation](https://sethunthunder111.github.io/json-database-st/)**
103
+ **[View Full Documentation Website](https://sethunthunder111.github.io/json-database-st/)**
82
104
 
83
105
  ## API Summary
84
106
 
@@ -90,27 +112,24 @@ run();
90
112
  * `async push(path, ...items)`
91
113
  * `async pull(path, ...itemsToRemove)`
92
114
  * `async transaction(asyncFn)`
93
- * `async batch(operations)`
94
- * `async query(predicateFn, [options])`
115
+ * `async batch(operations, [options])`
116
+ * `async find(collectionPath, predicate)`
117
+ * `async findByIndex(indexName, value)`
95
118
  * `async clear()`
96
119
  * `getStats()`
97
120
  * `async close()`
98
- * Properties: `filename`, `config`
99
-
100
- ## Concurrency and Atomicity
101
-
102
- Writes are queued and executed one after another for a given instance, ensuring file integrity. Reads use an in-memory cache for speed. See Core Concepts in the full documentation for details.
121
+ * Events: `.on('write', handler)`, `.on('change', handler)`, `.on('error', handler)`
103
122
 
104
123
  ## Limitations
105
124
 
106
- * Best suited for small to medium-sized JSON files. Performance degrades with very large files.
107
- * Loads the entire database into memory.
108
- * Designed for single-process access to a given file. Not suitable for distributed systems.
125
+ * **In-Memory Operation:** The entire database file is loaded into memory on initialization. This makes it extremely fast for reads but limits the practical file size to what can comfortably fit in your available RAM.
126
+ * **Single-Process Focus:** While writes are atomic, this library is designed for use by a single Node.js process. Using it with multiple processes writing to the same file (e.g., in a cluster) is not recommended and can lead to race conditions.
127
+ * **Not a Replacement for SQL/NoSQL Servers:** For very large datasets, high write concurrency, complex queries, or multi-process/multi-server needs, a dedicated database system like PostgreSQL, MongoDB, or SQLite is the appropriate choice.
109
128
 
110
129
  ## Contributing
111
130
 
112
- Contributions (issues, PRs) are welcome! Please open an issue to discuss significant changes.
131
+ Contributions, issues, and feature requests are welcome! Please feel free to open an issue to discuss any significant changes.
113
132
 
114
133
  ## License
115
134
 
116
- [MIT](LICENSE)
135
+ [MIT](LICENSE)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "json-database-st",
3
- "version": "1.0.5",
3
+ "version": "1.0.6",
4
4
  "description": "A simple, promise-based JSON file database for Node.js with atomic operations and lodash integration.",
5
5
  "main": "JSONDatabase.js",
6
6
  "scripts": {