@liorandb/db 1.0.5 → 1.0.7

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,172 +1,340 @@
1
1
  # LioranDB Server
2
2
 
3
- LioranDB Server is a Node.js + TypeScript REST API server built on top of **LioranDB Core**, designed to manage databases, collections, and documents, while providing user authentication. It is intended as the backend for applications using the LioranDB database engine.
3
+ A lightweight, self-hosted database server built with Node.js and Express. LioranDB provides a REST API for managing databases, collections, and documents with JWT-based authentication.
4
4
 
5
- ---
5
+ ## Features
6
6
 
7
- ## Table of Contents
7
+ - 🔐 **JWT Authentication** - Secure user authentication and authorization
8
+ - 🗄️ **Database Management** - Create, delete, and manage multiple databases
9
+ - 📚 **Collections** - Organize documents into logical collections
10
+ - 📄 **Document Operations** - CRUD operations with query support
11
+ - 💾 **Persistent Storage** - Built-in data persistence
12
+ - 🚀 **RESTful API** - Easy-to-use REST endpoints
13
+ - 📊 **Statistics** - Database and collection statistics
14
+ - 🖥️ **CLI Tool** - Command-line interface for database management
15
+ - 🔄 **CORS Support** - Cross-origin resource sharing enabled
8
16
 
9
- * [Features](#features)
10
- * [Tech Stack](#tech-stack)
11
- * [Setup](#setup)
12
- * [Environment Variables](#environment-variables)
13
- * [Scripts](#scripts)
14
- * [API Endpoints](#api-endpoints)
15
- * [Project Structure](#project-structure)
16
- * [License](#license)
17
+ ## Quick Start
17
18
 
18
- ---
19
+ ### Prerequisites
19
20
 
20
- ## Features
21
+ - Node.js 16.x or higher
22
+ - npm or yarn
21
23
 
22
- * User authentication (register/login) with JWT tokens
23
- * CRUD operations for databases, collections, and documents
24
- * Health check endpoint
25
- * TypeScript support with strict typing
26
- * Middleware for authentication
24
+ ### Installation
27
25
 
28
- ---
26
+ #### Option 1: Global Installation (Recommended)
27
+
28
+ Install LioranDB globally to use the CLI and server anywhere:
29
29
 
30
- ## Tech Stack
30
+ ```bash
31
+ npm i -g @liorandb/db
32
+ ```
31
33
 
32
- * Node.js
33
- * TypeScript
34
- * Express.js
35
- * LioranDB Core
36
- * bcryptjs
37
- * jsonwebtoken
38
- * dotenv
34
+ Then access the tools via npx:
39
35
 
40
- ---
36
+ ```bash
37
+ # Start the server
38
+ npx ldb-serve
41
39
 
42
- ## Setup
40
+ # Run the CLI tool
41
+ npx ldb-cli
42
+ ```
43
43
 
44
- 1. Clone the repository
44
+ #### Option 2: Local Installation
45
45
 
46
+ 1. Clone the repository:
46
47
  ```bash
47
- git clone <repo_url>
48
+ git clone https://github.com/LioranGroupOfficial/Liorandb.git
48
49
  cd server
49
50
  ```
50
51
 
51
- 2. Install dependencies
52
-
52
+ 2. Install dependencies:
53
53
  ```bash
54
54
  npm install
55
55
  ```
56
56
 
57
- 3. Create a `.env` file at the root:
57
+ 3. Start the server:
58
+ ```bash
59
+ npm run dev
60
+ ```
61
+
62
+ The server will start on `http://localhost:4000`
63
+
64
+ ## Usage
65
+
66
+ ### Server Binaries
58
67
 
59
- ```env
60
- PORT=4000
61
- JWT_SECRET=<your_jwt_secret>
62
- JWT_EXPIRES_IN=7d
68
+ Once installed globally or locally, you have access to:
69
+
70
+ ```bash
71
+ # Start the server (port 4000)
72
+ ldb-serve
73
+
74
+ # Run the CLI tool for database management
75
+ ldb-cli
63
76
  ```
64
77
 
65
- 4. Run the development server
78
+ ### Using npx
79
+
80
+ If installed globally, you can also use npx:
66
81
 
67
82
  ```bash
83
+ npx ldb-serve
84
+ npx ldb-cli
85
+ ```
86
+
87
+ ## Development
88
+
89
+ ### Available Commands (Local Development)
90
+
91
+ ```bash
92
+ # Start development server with hot reload
68
93
  npm run dev
94
+
95
+ # Build TypeScript to JavaScript
96
+ npm run build
97
+
98
+ # Start production server
99
+ npm start
100
+
101
+ # Run CLI tool
102
+ npm run cli
69
103
  ```
70
104
 
71
- The server will start on `http://localhost:4000` (or your configured PORT).
105
+ ### Project Structure
72
106
 
73
- ---
107
+ ```
108
+ src/
109
+ ├── app.ts # Express app configuration
110
+ ├── server.ts # Server entry point
111
+ ├── cli/
112
+ │ └── index.ts # CLI tool implementation
113
+ ├── config/
114
+ │ └── database.ts # Database configuration
115
+ ├── controllers/
116
+ │ ├── auth.controller.ts
117
+ │ ├── collection.controller.ts
118
+ │ ├── database.controller.ts
119
+ │ └── document.controller.ts
120
+ ├── middleware/
121
+ │ ├── auth.middleware.ts
122
+ │ └── requestLogger.middleware.ts
123
+ ├── routes/
124
+ │ ├── auth.routes.ts
125
+ │ ├── collection.routes.ts
126
+ │ ├── database.routes.ts
127
+ │ └── document.routes.ts
128
+ ├── types/
129
+ │ ├── auth-user.ts
130
+ │ └── express.d.ts
131
+ └── utils/
132
+ ├── hostLogger.ts
133
+ └── token.ts
134
+ ```
74
135
 
75
- ## Environment Variables
136
+ ## API Documentation
76
137
 
77
- * `PORT` – Port number for the server (default: 4000)
78
- * `JWT_SECRET` – Secret key used for signing JWT tokens **(required)**
79
- * `JWT_EXPIRES_IN` – JWT expiration time (default: `7d`)
138
+ ### Base URL
139
+ ```
140
+ http://<host>:4000
141
+ ```
80
142
 
81
- ---
143
+ ### Authentication
82
144
 
83
- ## Scripts
145
+ Most endpoints require JWT authentication. Include the token in the Authorization header:
84
146
 
85
- * `npm run dev` – Start the development server with hot reload
86
- * `npm run build` – Compile TypeScript to JavaScript (`dist/` folder)
87
- * `npm start` – Run the compiled server
147
+ ```
148
+ Authorization: Bearer <token>
149
+ ```
88
150
 
89
- ---
151
+ ### Core Endpoints
90
152
 
91
- ## API Endpoints
153
+ #### Health Check
154
+ - **GET** `/health` - Server health status
155
+ - **GET** `/` - Host information
92
156
 
93
- ### Health Check
157
+ #### Authentication
158
+ - **POST** `/auth/register` - Create new user account
159
+ - **POST** `/auth/login` - Login and get JWT token
94
160
 
95
- * `GET /health` – Returns server status
161
+ #### Database Management
162
+ - **GET** `/databases` - List all databases
163
+ - **POST** `/databases` - Create new database
164
+ - **DELETE** `/databases/:db` - Delete database
165
+ - **PATCH** `/databases/:db/rename` - Rename database
166
+ - **GET** `/databases/:db/stats` - Get database statistics
96
167
 
97
- ### Authentication
168
+ #### Collections
169
+ - **GET** `/db/:db/collections` - List collections
170
+ - **POST** `/db/:db/collections` - Create collection
171
+ - **DELETE** `/db/:db/collections/:col` - Delete collection
172
+ - **PATCH** `/db/:db/collections/:col/rename` - Rename collection
173
+ - **GET** `/db/:db/collections/:col/stats` - Get collection statistics
98
174
 
99
- * `POST /auth/register` – Register a new user
100
- * `POST /auth/login` Login and receive JWT token
175
+ #### Documents
176
+ - **POST** `/db/:db/collections/:col` - Insert single document
177
+ - **POST** `/db/:db/collections/:col/bulk` - Insert multiple documents
178
+ - **POST** `/db/:db/collections/:col/find` - Query documents
179
+ - **PATCH** `/db/:db/collections/:col/updateMany` - Update documents
180
+ - **POST** `/db/:db/collections/:col/deleteMany` - Delete documents
181
+ - **POST** `/db/:db/collections/:col/count` - Count documents
101
182
 
102
- ### Databases
183
+ For detailed API documentation, see [API.md](./API.md)
103
184
 
104
- * `GET /databases` – List all databases
105
- * `POST /databases` – Create a new database
106
- * `DELETE /databases/:db` – Delete a database
185
+ ## Example Usage
107
186
 
108
- ### Collections
187
+ ### Register and Login
109
188
 
110
- * `GET /db/:db/collections` – List all collections in a database
111
- * `POST /db/:db/collections` – Create a new collection
189
+ ```bash
190
+ # Register
191
+ curl -X POST http://localhost:4000/auth/register \
192
+ -H "Content-Type: application/json" \
193
+ -d '{"username":"admin","password":"password123"}'
194
+
195
+ # Login
196
+ curl -X POST http://localhost:4000/auth/login \
197
+ -H "Content-Type: application/json" \
198
+ -d '{"username":"admin","password":"password123"}'
199
+ ```
112
200
 
113
- ### Documents
201
+ ### Create Database
114
202
 
115
- * `POST /db/:db/collections/:col` – Insert a document
116
- * `POST /db/:db/collections/:col/find` – Find documents by query
117
- * `GET /db/:db/collections/:col/:id` Get a single document by ID
118
- * `PATCH /db/:db/collections/:col/:id` – Update a document by ID
119
- * `DELETE /db/:db/collections/:col/:id` – Delete a document by ID
203
+ ```bash
204
+ curl -X POST http://localhost:4000/databases \
205
+ -H "Authorization: Bearer <token>" \
206
+ -H "Content-Type: application/json" \
207
+ -d '{"name":"mydb"}'
208
+ ```
120
209
 
121
- > All database, collection, and document endpoints require **Bearer JWT authentication**
210
+ ### Create Collection
122
211
 
123
- ---
212
+ ```bash
213
+ curl -X POST http://localhost:4000/db/mydb/collections \
214
+ -H "Authorization: Bearer <token>" \
215
+ -H "Content-Type: application/json" \
216
+ -d '{"name":"users"}'
217
+ ```
124
218
 
125
- ## Project Structure
126
-
127
- ```
128
- server/
129
- ├─ src/
130
- ├─ config/
131
- │ └─ database.ts # LioranDB manager and auth collection
132
- │ ├─ controllers/
133
- │ │ ├─ auth.controller.ts
134
- │ │ ├─ collection.controller.ts
135
- │ │ ├─ database.controller.ts
136
- │ │ └─ document.controller.ts
137
- │ ├─ middleware/
138
- │ │ └─ auth.middleware.ts
139
- │ ├─ routes/
140
- │ │ ├─ auth.routes.ts
141
- │ │ ├─ collection.routes.ts
142
- │ │ ├─ database.routes.ts
143
- │ │ └─ document.routes.ts
144
- │ ├─ types/
145
- │ │ ├─ auth-user.ts
146
- │ │ └─ express.d.ts
147
- │ ├─ utils/
148
- │ │ └─ token.ts
149
- │ ├─ app.ts
150
- │ └─ server.ts
151
- ├─ package.json
152
- ├─ tsconfig.json
153
- └─ .env
219
+ ### Insert Document
220
+
221
+ ```bash
222
+ curl -X POST http://localhost:4000/db/mydb/collections/users \
223
+ -H "Authorization: Bearer <token>" \
224
+ -H "Content-Type: application/json" \
225
+ -d '{"name":"John","age":30,"email":"john@example.com"}'
154
226
  ```
155
227
 
156
- ---
228
+ ### Query Documents
157
229
 
158
- ## License
230
+ ```bash
231
+ curl -X POST http://localhost:4000/db/mydb/collections/users/find \
232
+ -H "Authorization: Bearer <token>" \
233
+ -H "Content-Type: application/json" \
234
+ -d '{"query":{"age":{"$gt":25}}}'
235
+ ```
159
236
 
160
- This project is licensed under the **ISC License**.
237
+ ## Configuration
161
238
 
162
- ---
239
+ The server uses environment-based configuration:
240
+
241
+ - **PORT**: Server port (default: 4000)
242
+ - **NODE_ENV**: Environment mode (development/production)
243
+
244
+ ### Server Settings
245
+
246
+ The server runs on `0.0.0.0:4000` to accept connections from all network interfaces.
247
+
248
+ ## Dependencies
249
+
250
+ | Package | Version | Purpose |
251
+ |---------|---------|---------|
252
+ | express | ^5.2.1 | Web framework |
253
+ | jsonwebtoken | ^9.0.3 | JWT handling |
254
+ | bcryptjs | ^3.0.3 | Password hashing |
255
+ | cors | ^2.8.6 | Cross-origin support |
256
+ | @liorandb/core | ^1.0.9 | Core database logic |
257
+
258
+ ## Development Dependencies
259
+
260
+ - TypeScript 5.9.3
261
+ - ts-node 10.9.2
262
+ - ts-node-dev 2.0.0
263
+ - nodemon 3.1.11
264
+
265
+ ## Error Handling
266
+
267
+ The API returns standard HTTP status codes:
268
+
269
+ | Code | Meaning |
270
+ |------|---------|
271
+ | 200 | Success |
272
+ | 400 | Bad request |
273
+ | 401 | Unauthorized |
274
+ | 409 | Conflict |
275
+ | 500 | Server error |
276
+
277
+ ## CLI Tool
278
+
279
+ The server includes a command-line interface for database management.
280
+
281
+ **Global installation:**
282
+ ```bash
283
+ ldb-cli
284
+ ```
285
+
286
+ **Via npx:**
287
+ ```bash
288
+ npx ldb-cli
289
+ ```
290
+
291
+ **Local development:**
292
+ ```bash
293
+ npm run cli
294
+ ```
295
+
296
+ ## Security
297
+
298
+ - Passwords are hashed using bcryptjs
299
+ - JWT tokens are used for API authentication
300
+ - CORS is enabled for cross-origin requests
301
+ - Request logging for monitoring
302
+
303
+ ## Performance
304
+
305
+ - Request logging middleware for tracking
306
+ - CORS enabled for efficient cross-origin communication
307
+ - Express.json() middleware for JSON parsing
308
+
309
+ ## Troubleshooting
310
+
311
+ ### Port Already in Use
312
+ If port 4000 is already in use, the server will fail to start. Either:
313
+ - Stop the service using port 4000
314
+ - Modify the PORT environment variable
315
+
316
+ ### Authentication Failed
317
+ - Ensure you're including the Authorization header
318
+ - Verify the JWT token hasn't expired
319
+ - Check that you registered/logged in first
320
+
321
+ ### Database Not Found
322
+ - Ensure the database name is correct
323
+ - Create the database first with POST /databases
324
+
325
+ ## Related Projects
326
+
327
+ - **LioranDB Studio** - Web UI for database management
328
+ - **LioranDB Core** - Core database engine
329
+
330
+ ## License
331
+
332
+ LDEP License
163
333
 
164
- ## Notes
334
+ ## Author
165
335
 
166
- * Make sure to set a strong `JWT_SECRET` in `.env`
167
- * The server is designed to work with **LioranDB Core**, which is a peer-to-peer database engine.
168
- * TypeScript strict mode is enabled for safer coding.
336
+ Lioran Group
169
337
 
170
338
  ---
171
339
 
172
- For further documentation on **LioranDB Core**, refer to its repository: [LioranDB Core](https://www.npmjs.com/package/@liorandb/core)
340
+ For more detailed information, see [API.md](./API.md) for complete endpoint documentation and [SETUP.md](./SETUP.md) for deployment instructions.
@@ -4,7 +4,12 @@ exports.manager = void 0;
4
4
  exports.getAuthCollection = getAuthCollection;
5
5
  // src/config/database.ts
6
6
  const core_1 = require("@liorandb/core");
7
- exports.manager = new core_1.LioranManager();
7
+ const cli_1 = require("../utils/cli");
8
+ const cli = (0, cli_1.parseCLIArgs)();
9
+ exports.manager = new core_1.LioranManager({
10
+ rootPath: cli.rootPath || "./lioran-data",
11
+ encryptionKey: cli.encryptionKey || "default-encryption-key",
12
+ });
8
13
  async function getAuthCollection() {
9
14
  const db = await exports.manager.db("_auth");
10
15
  await db.createCollection("users").catch(() => { });
package/dist/server.js CHANGED
@@ -5,24 +5,37 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  };
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  // src/server.ts
8
+ const os_1 = __importDefault(require("os"));
8
9
  const app_1 = __importDefault(require("./app"));
10
+ const cli_1 = require("./utils/cli");
11
+ const cli = (0, cli_1.parseCLIArgs)();
12
+ console.log("⚙ Runtime Config:");
13
+ console.log(`📁 DB Root Path : ${cli.rootPath || "./lioran-data"}`);
14
+ console.log(`🔐 Encryption : ${cli.encryptionKey ? "Enabled" : "Disabled"}`);
9
15
  const PORT = 4000;
16
+ function printHostAddresses(port) {
17
+ const urls = new Set();
18
+ // Localhost
19
+ urls.add(`http://localhost:${port}`);
20
+ urls.add(`http://127.0.0.1:${port}`);
21
+ // Network interfaces
22
+ const nets = os_1.default.networkInterfaces();
23
+ for (const name of Object.keys(nets)) {
24
+ for (const net of nets[name] || []) {
25
+ if (net.family === "IPv4" && !net.internal) {
26
+ urls.add(`http://${net.address}:${port}`);
27
+ }
28
+ }
29
+ }
30
+ console.log("🌐 Available Host URLs:");
31
+ for (const url of urls) {
32
+ console.log(` → ${url}`);
33
+ }
34
+ }
10
35
  app_1.default.listen(PORT, "0.0.0.0", () => {
11
36
  console.log("======================================");
12
37
  console.log("🚀 LioranDB Host is LIVE");
13
38
  console.log(`📡 Listening on port: ${PORT}`);
14
- // print all running host IPs
15
- console.log(`🌐 Host Address: localhost:4000`);
16
- const os = require("os");
17
- const networkInterfaces = os.networkInterfaces();
18
- for (const interfaceName in networkInterfaces) {
19
- const interfaceInfo = networkInterfaces[interfaceName];
20
- for (const addressInfo of interfaceInfo) {
21
- if (addressInfo.family === "IPv4" && !addressInfo.internal) {
22
- console.log(`🌐 Host Address: ${addressInfo.address}:4000`);
23
- }
24
- }
25
- }
26
- // console.log(`🧠 Mode: ${process.env.NODE_ENV || "development"}`);
39
+ printHostAddresses(PORT);
27
40
  console.log("======================================");
28
41
  });
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.parseCLIArgs = parseCLIArgs;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ function parseCLIArgs() {
10
+ const args = process.argv.slice(2);
11
+ let rootPath;
12
+ let encryptionKey;
13
+ for (let i = 0; i < args.length; i++) {
14
+ const arg = args[i];
15
+ if (arg === "--root") {
16
+ rootPath = args[++i];
17
+ continue;
18
+ }
19
+ if (arg === "-ed") {
20
+ encryptionKey = args[++i];
21
+ continue;
22
+ }
23
+ if (arg === "-ef") {
24
+ const file = args[++i];
25
+ const fullPath = path_1.default.resolve(file);
26
+ if (!fs_1.default.existsSync(fullPath)) {
27
+ console.error(`❌ Encryption key file not found: ${fullPath}`);
28
+ process.exit(1);
29
+ }
30
+ encryptionKey = fs_1.default.readFileSync(fullPath, "utf8").trim();
31
+ continue;
32
+ }
33
+ }
34
+ return { rootPath, encryptionKey };
35
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liorandb/db",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
4
4
  "description": "LioranDB server and CLI",
5
5
  "main": "dist/server.js",
6
6
  "bin": {