@misterzik/espressojs 3.2.6 → 3.3.1

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/QUICKSTART.md ADDED
@@ -0,0 +1,213 @@
1
+ # EspressoJS Quick Start Guide
2
+
3
+ Get your Express.js server running in under 5 minutes!
4
+
5
+ ## 🚀 Installation
6
+
7
+ ```bash
8
+ npm install --save @misterzik/espressojs
9
+ ```
10
+
11
+ ## 📝 Step-by-Step Setup
12
+
13
+ ### Step 1: Initialize Configuration
14
+
15
+ ```bash
16
+ node cli init
17
+ ```
18
+
19
+ This creates a `config.json` file with sensible defaults.
20
+
21
+ ### Step 2: Create Your Entry Files
22
+
23
+ **Create `index.js`:**
24
+ ```javascript
25
+ require("@misterzik/espressojs");
26
+ ```
27
+
28
+ **Create `cli.js`:**
29
+ ```javascript
30
+ require('@misterzik/espressojs/cli');
31
+ ```
32
+
33
+ ### Step 3: Create Public Directory
34
+
35
+ ```bash
36
+ mkdir public
37
+ ```
38
+
39
+ **Create `public/index.html`:**
40
+ ```html
41
+ <!DOCTYPE html>
42
+ <html lang="en">
43
+ <head>
44
+ <meta charset="UTF-8">
45
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
46
+ <title>EspressoJS</title>
47
+ </head>
48
+ <body>
49
+ <h1>Welcome to EspressoJS!</h1>
50
+ <p>Your Express server is running successfully.</p>
51
+ </body>
52
+ </html>
53
+ ```
54
+
55
+ ### Step 4: Run Your Server
56
+
57
+ ```bash
58
+ node cli run
59
+ ```
60
+
61
+ Visit `http://localhost:8080` in your browser!
62
+
63
+ ## 🎯 Next Steps
64
+
65
+ ### Add Custom Routes
66
+
67
+ **Create `routes/api.js`:**
68
+ ```javascript
69
+ const express = require('express');
70
+ const router = express.Router();
71
+
72
+ router.get('/hello', (req, res) => {
73
+ res.json({ message: 'Hello from EspressoJS!' });
74
+ });
75
+
76
+ module.exports = router;
77
+ ```
78
+
79
+ **Enable API in `config.json`:**
80
+ ```json
81
+ {
82
+ "api": {
83
+ "enabled": true
84
+ }
85
+ }
86
+ ```
87
+
88
+ Test it: `http://localhost:8080/api/hello`
89
+
90
+ ### Add MongoDB
91
+
92
+ **Update `config.json`:**
93
+ ```json
94
+ {
95
+ "mongoDB": {
96
+ "enabled": true,
97
+ "uri": "your-cluster.mongodb.net",
98
+ "instance": "myDatabase"
99
+ }
100
+ }
101
+ ```
102
+
103
+ **Create `.env`:**
104
+ ```env
105
+ MONGO_USER=your_username
106
+ MONGO_TOKEN=your_password
107
+ ```
108
+
109
+ ### Use Health Checks
110
+
111
+ Built-in endpoints:
112
+ - `http://localhost:8080/health` - Full health check
113
+ - `http://localhost:8080/ready` - Readiness probe
114
+ - `http://localhost:8080/alive` - Liveness probe
115
+
116
+ ## 📚 Common Commands
117
+
118
+ ```bash
119
+ # Show current configuration
120
+ node cli show
121
+
122
+ # Change environment
123
+ node cli env --instance=production --port=3000
124
+
125
+ # Validate configuration
126
+ node cli validate
127
+
128
+ # Get help
129
+ node cli --help
130
+ ```
131
+
132
+ ## 🔧 Configuration Options
133
+
134
+ Customize your `config.json`:
135
+
136
+ ```json
137
+ {
138
+ "instance": "development",
139
+ "port": 8080,
140
+ "hostname": "",
141
+ "mongoDB": {
142
+ "enabled": false,
143
+ "port": null,
144
+ "uri": "",
145
+ "instance": "database"
146
+ },
147
+ "api": {
148
+ "enabled": false,
149
+ "uri": "",
150
+ "url": "",
151
+ "method": "GET",
152
+ "headers": {
153
+ "Content-Type": "application/json"
154
+ }
155
+ }
156
+ }
157
+ ```
158
+
159
+ ## 🛡️ Security Features
160
+
161
+ EspressoJS includes:
162
+ - ✅ Helmet.js for secure headers
163
+ - ✅ Rate limiting (100 requests per 15 minutes)
164
+ - ✅ CORS enabled
165
+ - ✅ Request size limits (10MB)
166
+ - ✅ XSS protection
167
+
168
+ ## 📝 Logging
169
+
170
+ Logs are automatically created in the `logs/` directory:
171
+ - `combined.log` - All logs
172
+ - `error.log` - Errors only
173
+ - `exceptions.log` - Uncaught exceptions
174
+ - `rejections.log` - Unhandled rejections
175
+
176
+ ## 🎓 Examples
177
+
178
+ Check the `examples/` directory for:
179
+ - `basic-api.js` - REST API examples
180
+ - `mongodb-example.js` - MongoDB integration
181
+
182
+ ## 💡 Tips
183
+
184
+ 1. **Development Mode**: Use `npm run dev` for auto-restart
185
+ 2. **Production**: Set `NODE_ENV=production` in your environment
186
+ 3. **Custom Middleware**: Add to `index.js` before requiring EspressoJS
187
+ 4. **Error Handling**: Use the built-in `asyncHandler` for async routes
188
+
189
+ ## 🆘 Troubleshooting
190
+
191
+ **Port already in use?**
192
+ ```bash
193
+ node cli env --port=3000
194
+ ```
195
+
196
+ **MongoDB connection issues?**
197
+ - Check your `.env` credentials
198
+ - Verify MongoDB URI in `config.json`
199
+ - Ensure IP whitelist in MongoDB Atlas
200
+
201
+ **Missing favicon.ico error?**
202
+ - Create `public/favicon.ico` or ignore the warning
203
+
204
+ ## 📖 Full Documentation
205
+
206
+ See [README.md](./README.md) for complete documentation.
207
+
208
+ ## 🤝 Need Help?
209
+
210
+ - [GitHub Issues](https://github.com/misterzik/Espresso.js/issues)
211
+ - [GitHub Discussions](https://github.com/misterzik/Espresso.js/discussions)
212
+
213
+ Happy coding! ☕
package/README.md CHANGED
@@ -1,81 +1,387 @@
1
1
  ![Espresso](https://raw.githubusercontent.com/misterzik/Espresso.js/main/espresso.png)
2
2
 
3
- ## EspressoJS / Espresso
4
-
5
- ### Introducing Espresso.JS, your ultimate Express configuration starting point and boilerplate. With its simplicity and lack of opinionation, EspressoJS offers plug-and-play configurations built on top of Express.
6
-
7
- ### Whether you're a beginner or an experienced developer, EspressoJS will have you up and running with an Express instance in a matter of seconds. Say goodbye to tedious setup and hello to streamlined development with EspressoJS.
8
-
9
- ## Getting Started
10
-
11
- - Download [latest release](https://github.com/misterzik/Espresso.js/releases)
12
-
13
- `npm install --save @misterzik/espressojs`
14
-
15
- - Create `config.json` to handle the instances
16
-
17
- ```
18
- {
19
- "instance": "development",
20
- "port": 8080,
21
- "hostname": "",
22
- "mongoDB": {
23
- "enabled": false,
24
- "uri": "",
25
- "instance": "database"
26
- },
27
- "api": {
28
- "enabled": false,
29
- "uri": "https://swapi.dev/api/people/",
30
- "url": "",
31
- "method": "GET",
32
- "headers": {
33
- "Content-Type": "application/json"
34
- }
3
+ # EspressoJS
4
+
5
+ > **A modern, production-ready Express.js boilerplate with built-in security, logging, and best practices.**
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@misterzik/espressojs.svg)](https://www.npmjs.com/package/@misterzik/espressojs)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
9
+
10
+ ## 🚀 Features
11
+
12
+ - ⚡ **Quick Setup** - Get your Express server running in seconds
13
+ - 🔒 **Security First** - Helmet, rate limiting, and CORS pre-configured
14
+ - 📝 **Advanced Logging** - Winston logger with file and console transports
15
+ - 🛡️ **Error Handling** - Centralized error handling middleware
16
+ - 🔧 **Configuration Management** - JSON-based config with validation
17
+ - 💾 **MongoDB Ready** - Optional MongoDB integration with Mongoose
18
+ - 🏥 **Health Checks** - Built-in health, readiness, and liveness endpoints
19
+ - 🎯 **CLI Tools** - Powerful command-line interface for management
20
+ - 🔄 **Graceful Shutdown** - Proper cleanup of resources on exit
21
+ - 📦 **Production Ready** - Compression, caching, and optimization built-in
22
+
23
+ ## 📋 Requirements
24
+
25
+ - **Node.js** >= 14.x
26
+ - **npm** >= 6.x
27
+
28
+ ## 📦 Installation
29
+
30
+ ```bash
31
+ npm install --save @misterzik/espressojs
32
+ ```
33
+
34
+ ## 🎯 Quick Start
35
+
36
+ ### 1. Initialize Configuration
37
+
38
+ ```bash
39
+ node cli init
40
+ ```
41
+
42
+ This creates a `config.json` file with default settings:
43
+
44
+ ```json
45
+ {
46
+ "instance": "development",
47
+ "port": 8080,
48
+ "hostname": "",
49
+ "mongoDB": {
50
+ "enabled": false,
51
+ "port": null,
52
+ "uri": "",
53
+ "instance": "database"
54
+ },
55
+ "api": {
56
+ "enabled": false,
57
+ "uri": "",
58
+ "url": "",
59
+ "method": "GET",
60
+ "headers": {
61
+ "Content-Type": "application/json"
62
+ }
63
+ }
64
+ }
65
+ ```
66
+
67
+ ### 2. Create Environment File (Optional)
68
+
69
+ Create a `.env` file for sensitive data:
70
+
71
+ ```env
72
+ MONGO_USER=your_username
73
+ MONGO_TOKEN=your_password
74
+ API_TOKEN=your_api_token
75
+ NODE_ENV=development
76
+ ```
77
+
78
+ ### 3. Create Your Main File
79
+
80
+ Create `index.js` or `espresso.js`:
81
+
82
+ ```javascript
83
+ require("@misterzik/espressojs");
84
+ ```
85
+
86
+ ### 4. Create CLI File
87
+
88
+ Create `cli.js`:
89
+
90
+ ```javascript
91
+ require('@misterzik/espressojs/cli');
92
+ ```
93
+
94
+ ### 5. Run Your Server
95
+
96
+ ```bash
97
+ # Using the CLI
98
+ node cli run
99
+
100
+ # Or using npm scripts
101
+ npm start
102
+ ```
103
+
104
+ ## 🛠️ CLI Commands
105
+
106
+ EspressoJS comes with a powerful CLI for managing your application:
107
+
108
+ ```bash
109
+ # Show current configuration
110
+ node cli show
111
+
112
+ # Run the server
113
+ node cli run
114
+
115
+ # Update environment settings
116
+ node cli env --instance=production --port=3000
117
+
118
+ # Initialize new config
119
+ node cli init
120
+
121
+ # Validate configuration
122
+ node cli validate
123
+
124
+ # Show version information
125
+ node cli version
126
+
127
+ # Get help
128
+ node cli --help
129
+ ```
130
+
131
+ ## 📁 Project Structure
132
+
133
+ ```
134
+ your-project/
135
+ ├── config.json # Configuration file
136
+ ├── .env # Environment variables
137
+ ├── index.js # Main application file
138
+ ├── cli.js # CLI entry point
139
+ ├── public/ # Static files
140
+ │ ├── index.html
141
+ │ └── favicon.ico
142
+ ├── routes/ # Custom routes
143
+ │ ├── api.js
144
+ │ └── db.js
145
+ └── logs/ # Application logs (auto-created)
146
+ ├── combined.log
147
+ ├── error.log
148
+ ├── exceptions.log
149
+ └── rejections.log
150
+ ```
151
+
152
+ ## 🔧 Configuration
153
+
154
+ ### Environment Instances
155
+
156
+ EspressoJS supports three pre-configured environments:
157
+
158
+ - **development** - Development mode with debug logging
159
+ - **production** - Production mode with optimized settings
160
+ - **global** - Global/staging environment
161
+
162
+ ### Configuration Options
163
+
164
+ | Option | Type | Description | Default |
165
+ |--------|------|-------------|---------|
166
+ | `instance` | string | Environment instance | `development` |
167
+ | `port` | number | Server port | `8080` |
168
+ | `hostname` | string | Server hostname | `""` |
169
+ | `publicDirectory` | string | Public files directory | `"/public"` |
170
+ | `mongoDB.enabled` | boolean | Enable MongoDB | `false` |
171
+ | `mongoDB.uri` | string | MongoDB URI | `""` |
172
+ | `mongoDB.port` | number | MongoDB port | `null` |
173
+ | `mongoDB.instance` | string | Database name | `database` |
174
+ | `api.enabled` | boolean | Enable API routes | `false` |
175
+ | `api.uri` | string | External API URI | `""` |
176
+ | `api.method` | string | HTTP method | `GET` |
177
+ | `api.headers` | object | Request headers | `{"Content-Type": "application/json"}` |
178
+ | `api.timeout` | number | Request timeout (ms) | `30000` |
179
+ | `api.retries` | number | Retry attempts (0-5) | `0` |
180
+
181
+ ### Multiple API Endpoints
182
+
183
+ EspressoJS supports multiple API configurations using the pattern `api`, `api2`, `api3`, etc.:
184
+
185
+ ```json
186
+ {
187
+ "api": {
188
+ "enabled": true,
189
+ "uri": "https://api.example.com/v1/",
190
+ "method": "GET",
191
+ "headers": {
192
+ "Content-Type": "application/json"
35
193
  }
194
+ },
195
+ "api2": {
196
+ "uri": "https://api.example.com/v1/news",
197
+ "method": "GET",
198
+ "headers": {
199
+ "Content-Type": "application/json",
200
+ "Authorization": "Bearer TOKEN"
201
+ }
202
+ },
203
+ "api3": {
204
+ "enabled": true,
205
+ "uri": "https://api.example.com/api",
206
+ "method": "POST"
36
207
  }
37
- ```
208
+ }
209
+ ```
210
+
211
+ **Using Multiple APIs in Your Code:**
212
+
213
+ ```javascript
214
+ const { apiManager } = require('./index');
215
+
216
+ // Request from specific API
217
+ const data = await apiManager.request('api2', '/endpoint');
218
+
219
+ // Parallel requests
220
+ const [data1, data2] = await Promise.all([
221
+ apiManager.request('api', '/users'),
222
+ apiManager.request('api2', '/news')
223
+ ]);
224
+
225
+ // Check if API exists
226
+ if (apiManager.hasAPI('api3')) {
227
+ const data = await apiManager.request('api3', '/data');
228
+ }
229
+ ```
230
+
231
+ 📖 **[Full Multiple APIs Guide](./docs/MULTIPLE-APIS.md)**
232
+
233
+ ## 🏥 Health Check Endpoints
234
+
235
+ EspressoJS includes built-in health check endpoints:
236
+
237
+ - **GET /health** - Comprehensive health check with system metrics
238
+ - **GET /ready** - Readiness probe for orchestration
239
+ - **GET /alive** - Liveness probe for monitoring
240
+
241
+ Example response from `/health`:
242
+
243
+ ```json
244
+ {
245
+ "status": "OK",
246
+ "timestamp": "2024-01-01T00:00:00.000Z",
247
+ "uptime": 123.456,
248
+ "environment": "development",
249
+ "memory": {
250
+ "total": 16777216000,
251
+ "free": 8388608000,
252
+ "usage": {...}
253
+ },
254
+ "cpu": {
255
+ "cores": 8,
256
+ "loadAverage": [1.5, 1.3, 1.2]
257
+ },
258
+ "database": {
259
+ "status": "connected",
260
+ "name": "myDatabase"
261
+ }
262
+ }
263
+ ```
264
+
265
+ ## 🔒 Security Features
266
+
267
+ EspressoJS includes enterprise-grade security features:
38
268
 
39
- - Create `.env` if you don't want to use config. A mix is possible.
269
+ - **Helmet.js** - Sets secure HTTP headers
270
+ - **Rate Limiting** - Prevents abuse and DDoS attacks
271
+ - **CORS** - Configurable cross-origin resource sharing
272
+ - **Input Validation** - Express-validator integration
273
+ - **XSS Protection** - Cross-site scripting prevention
274
+ - **Content Security Policy** - CSP headers configured
40
275
 
41
- ```
42
- MONGO_USER=USER
43
- MONGO_TOKEN=PASSWORD
44
- API_TOKEN=APITOKEN
45
- ```
276
+ ## 📝 Logging
46
277
 
47
- - Create `espresso.js` and add the following requirements to call the packages.
278
+ Winston-based logging with multiple transports:
48
279
 
49
- ```
50
- require("@misterzik/espressojs");
51
- ```
280
+ ```javascript
281
+ const logger = require('./server/utils/logger');
52
282
 
53
- - Create `cli.js` and add the following requirements to call the packages.
283
+ logger.info('Information message');
284
+ logger.warn('Warning message');
285
+ logger.error('Error message');
286
+ logger.debug('Debug message');
287
+ logger.http('HTTP request');
288
+ ```
54
289
 
55
- ```
56
- require('@misterzik/espressojs/cli');
57
- ```
290
+ Logs are automatically written to:
291
+ - Console (formatted with colors)
292
+ - `logs/combined.log` (all logs)
293
+ - `logs/error.log` (errors only)
294
+ - `logs/exceptions.log` (uncaught exceptions)
295
+ - `logs/rejections.log` (unhandled rejections)
58
296
 
59
- - And you are all set to start, To run the instance, use:
60
- ```
61
- node cli run
62
- ```
297
+ ## 🔌 MongoDB Integration
298
+
299
+ Enable MongoDB in your `config.json`:
300
+
301
+ ```json
302
+ {
303
+ "mongoDB": {
304
+ "enabled": true,
305
+ "uri": "cluster0.mongodb.net",
306
+ "port": null,
307
+ "instance": "myDatabase"
308
+ }
309
+ }
310
+ ```
311
+
312
+ Set credentials in `.env`:
313
+
314
+ ```env
315
+ MONGO_USER=your_username
316
+ MONGO_TOKEN=your_password
317
+ ```
318
+
319
+ ## 🛣️ Custom Routes
320
+
321
+ Create custom routes in the `routes/` directory:
322
+
323
+ **routes/api.js:**
324
+ ```javascript
325
+ const express = require('express');
326
+ const router = express.Router();
327
+
328
+ router.get('/users', (req, res) => {
329
+ res.json({ users: [] });
330
+ });
331
+
332
+ module.exports = router;
333
+ ```
334
+
335
+ ## 🚀 Deployment
336
+
337
+ ### Production Mode
338
+
339
+ ```bash
340
+ # Set production environment
341
+ node cli env --instance=production --port=80
342
+
343
+ # Run in production
344
+ npm run prod
345
+ ```
346
+
347
+ ### Environment Variables
348
+
349
+ Set these in production:
350
+
351
+ ```env
352
+ NODE_ENV=production
353
+ PORT=80
354
+ MONGO_USER=prod_user
355
+ MONGO_TOKEN=prod_password
356
+ ```
357
+
358
+ ## 📊 NPM Scripts
359
+
360
+ ```json
361
+ {
362
+ "scripts": {
363
+ "start": "node cli run",
364
+ "dev": "node cli env --instance=development --port=8080 && node cli run",
365
+ "prod": "node cli env --instance=production --port=80 && node cli run",
366
+ "show": "node cli show"
367
+ }
368
+ }
369
+ ```
63
370
 
64
- ### Structured Files
371
+ ## 🤝 Contributing
65
372
 
66
- Pre-made Configurations:
373
+ Contributions are welcome! Please feel free to submit a Pull Request.
67
374
 
68
- - `server/config/config.global.js`
69
- - `server/config/config.production.js`
70
- - `server/config/config.development.js`
375
+ ## 📄 License
71
376
 
72
- ### Commands
377
+ MIT © [MisterZik](https://github.com/misterzik)
73
378
 
74
- - Stop server by pressing `CTRL + C` to terminated the Espresso process.
379
+ ## 🔗 Links
75
380
 
76
- ### Requirements
381
+ - [GitHub Repository](https://github.com/misterzik/Espresso.js)
382
+ - [npm Package](https://www.npmjs.com/package/@misterzik/espressojs)
383
+ - [Issue Tracker](https://github.com/misterzik/Espresso.js/issues)
77
384
 
78
- Installed prior using Espresso.JS
385
+ ## 💡 Support
79
386
 
80
- - NodeJS
81
- - NPM
387
+ If you find EspressoJS helpful, please consider giving it a ⭐ on GitHub!