@igxjs/node-components 1.0.9 → 1.0.11

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.
@@ -1,302 +0,0 @@
1
- # HTTP Handlers
2
-
3
- Custom error handling utilities with standardized HTTP status codes and error responses for Express.js applications.
4
-
5
- ## Overview
6
-
7
- The HTTP Handlers module provides:
8
- - Standardized error handling middleware
9
- - Custom error classes
10
- - HTTP status codes and messages constants
11
- - 404 handler for unmatched routes
12
- - Utility functions for error formatting
13
- - Axios error handling helpers
14
-
15
- ## Available Exports
16
-
17
- ```javascript
18
- import {
19
- httpCodes, // HTTP status code constants
20
- httpMessages, // HTTP status message constants
21
- httpErrorHandler, // Error handling middleware
22
- httpNotFoundHandler, // 404 handler middleware
23
- CustomError, // Custom error class
24
- httpHelper, // Utility functions
25
- httpError // Error factory function
26
- } from '@igxjs/node-components';
27
- ```
28
-
29
- ## Quick Start
30
-
31
- ```javascript
32
- import express from 'express';
33
- import {
34
- httpCodes,
35
- httpErrorHandler,
36
- httpNotFoundHandler,
37
- httpError
38
- } from '@igxjs/node-components';
39
-
40
- const app = express();
41
-
42
- // Your routes
43
- app.get('/api/data', async (req, res, next) => {
44
- try {
45
- const data = await fetchData();
46
- res.json(data);
47
- } catch (error) {
48
- next(httpError(httpCodes.SYSTEM_FAILURE, 'Failed to fetch data', error));
49
- }
50
- });
51
-
52
- // Add 404 handler before error handler
53
- app.use(httpNotFoundHandler);
54
-
55
- // Add error handler as the last middleware
56
- app.use(httpErrorHandler);
57
-
58
- app.listen(3000);
59
- ```
60
-
61
- ## HTTP Status Codes
62
-
63
- The `httpCodes` object provides constants for common HTTP status codes:
64
-
65
- ```javascript
66
- import { httpCodes } from '@igxjs/node-components';
67
-
68
- // Success codes
69
- httpCodes.OK // 200
70
- httpCodes.CREATED // 201
71
- httpCodes.NO_CONTENT // 204
72
-
73
- // Client error codes
74
- httpCodes.BAD_REQUEST // 400
75
- httpCodes.UNAUTHORIZED // 401
76
- httpCodes.FORBIDDEN // 403
77
- httpCodes.NOT_FOUND // 404
78
- httpCodes.NOT_ACCEPTABLE // 406
79
- httpCodes.CONFLICT // 409
80
- httpCodes.LOCKED // 423
81
-
82
- // Server error codes
83
- httpCodes.SYSTEM_FAILURE // 500
84
- httpCodes.NOT_IMPLEMENTED // 501
85
- ```
86
-
87
- ## HTTP Status Messages
88
-
89
- Corresponding status messages are available via `httpMessages`:
90
-
91
- ```javascript
92
- import { httpMessages } from '@igxjs/node-components';
93
-
94
- httpMessages.OK // 'OK'
95
- httpMessages.BAD_REQUEST // 'Bad Request'
96
- httpMessages.UNAUTHORIZED // 'Unauthorized'
97
- // ... etc.
98
- ```
99
-
100
- ## CustomError Class
101
-
102
- Create custom errors with specific HTTP status codes:
103
-
104
- ```javascript
105
- import { CustomError, httpCodes } from '@igxjs/node-components';
106
-
107
- // Constructor: new CustomError(code, message, error?, data?)
108
- throw new CustomError(
109
- httpCodes.BAD_REQUEST,
110
- 'Email is required',
111
- null,
112
- { field: 'email' }
113
- );
114
- ```
115
-
116
- **Properties:**
117
- - `code` (number) - HTTP status code
118
- - `message` (string) - Error message
119
- - `error` (object, optional) - Original error object
120
- - `data` (object, optional) - Additional error data
121
-
122
- ## httpError Function
123
-
124
- Convenience function to create CustomError instances:
125
-
126
- ```javascript
127
- import { httpError, httpCodes } from '@igxjs/node-components';
128
-
129
- // Same as: new CustomError(code, message, error, data)
130
- throw httpError(
131
- httpCodes.UNAUTHORIZED,
132
- 'Invalid credentials',
133
- originalError,
134
- { attempted: username }
135
- );
136
- ```
137
-
138
- ## Middleware
139
-
140
- ### httpErrorHandler
141
-
142
- Express error handling middleware that processes CustomError and other errors:
143
-
144
- ```javascript
145
- import { httpErrorHandler } from '@igxjs/node-components';
146
-
147
- // Add as the last middleware
148
- app.use(httpErrorHandler);
149
- ```
150
-
151
- **Features:**
152
- - Automatically handles `CustomError` instances
153
- - Sets appropriate HTTP status codes
154
- - Adds CORS headers
155
- - Logs error details to console
156
- - Returns standardized JSON error responses
157
-
158
- **Response Format:**
159
- ```json
160
- {
161
- "error": {
162
- "code": 400,
163
- "message": "Email is required",
164
- "data": { "field": "email" }
165
- }
166
- }
167
- ```
168
-
169
- ### httpNotFoundHandler
170
-
171
- Middleware that catches all unmatched routes and returns 404:
172
-
173
- ```javascript
174
- import { httpNotFoundHandler } from '@igxjs/node-components';
175
-
176
- // Add before error handler
177
- app.use(httpNotFoundHandler);
178
- app.use(httpErrorHandler);
179
- ```
180
-
181
- ## httpHelper Utilities
182
-
183
- ### `handleAxiosError(error, defaultMessage?)`
184
-
185
- Analyze and convert Axios/HTTP errors to CustomError:
186
-
187
- ```javascript
188
- import axios from 'axios';
189
- import { httpHelper } from '@igxjs/node-components';
190
-
191
- try {
192
- const response = await axios.get('https://api.example.com/data');
193
- return response.data;
194
- } catch (error) {
195
- // Converts Axios error to CustomError with extracted status and message
196
- throw httpHelper.handleAxiosError(error, 'API request failed');
197
- }
198
- ```
199
-
200
- ### `format(str, ...args)`
201
-
202
- Format strings with placeholders:
203
-
204
- ```javascript
205
- import { httpHelper } from '@igxjs/node-components';
206
-
207
- const message = httpHelper.format(
208
- 'User {0} not found in {1}',
209
- 'john@example.com',
210
- 'database'
211
- );
212
- // Result: 'User john@example.com not found in database'
213
- ```
214
-
215
- ### `toZodMessage(error)`
216
-
217
- Generate friendly Zod validation error messages:
218
-
219
- ```javascript
220
- import { z } from 'zod';
221
- import { httpHelper, httpError, httpCodes } from '@igxjs/node-components';
222
-
223
- const userSchema = z.object({
224
- email: z.string().email(),
225
- age: z.number().min(18)
226
- });
227
-
228
- app.post('/api/users', (req, res, next) => {
229
- try {
230
- const validated = userSchema.parse(req.body);
231
- // Process validated data
232
- } catch (error) {
233
- if (error instanceof z.ZodError) {
234
- const message = httpHelper.toZodMessage(error);
235
- throw httpError(httpCodes.BAD_REQUEST, message, error);
236
- }
237
- next(error);
238
- }
239
- });
240
- ```
241
-
242
- ## Complete Example
243
-
244
- ```javascript
245
- import express from 'express';
246
- import {
247
- httpCodes,
248
- httpMessages,
249
- httpError,
250
- httpErrorHandler,
251
- httpNotFoundHandler,
252
- CustomError
253
- } from '@igxjs/node-components';
254
-
255
- const app = express();
256
- app.use(express.json());
257
-
258
- // Routes
259
- app.get('/api/health', (req, res) => {
260
- res.json({ status: httpMessages.OK });
261
- });
262
-
263
- app.post('/api/login', async (req, res, next) => {
264
- try {
265
- const { username, password } = req.body;
266
-
267
- if (!username || !password) {
268
- throw httpError(
269
- httpCodes.BAD_REQUEST,
270
- 'Username and password are required'
271
- );
272
- }
273
-
274
- const user = await authenticate(username, password);
275
-
276
- if (!user) {
277
- throw new CustomError(
278
- httpCodes.UNAUTHORIZED,
279
- 'Invalid credentials'
280
- );
281
- }
282
-
283
- res.json({ user });
284
- } catch (error) {
285
- next(error);
286
- }
287
- });
288
-
289
- // 404 handler
290
- app.use(httpNotFoundHandler);
291
-
292
- // Error handler (must be last)
293
- app.use(httpErrorHandler);
294
-
295
- app.listen(3000);
296
- ```
297
-
298
- ## Related Documentation
299
-
300
- - [JWT Manager](./jwt-manager.md) - For token-based authentication
301
- - [SessionManager](./session-manager.md) - For session-based authentication
302
- - [Back to main documentation](../README.md)
@@ -1,124 +0,0 @@
1
- # JWT Manager
2
-
3
- Provides JWT (JSON Web Token) encryption and decryption utilities using the `jose` library with JWE (JSON Web Encryption) for secure token management.
4
-
5
- ## Overview
6
-
7
- JwtManager provides secure token-based authentication using:
8
- - JWE (JSON Web Encryption) for encrypted tokens
9
- - Configurable expiration times
10
- - Standard JWT claims (issuer, audience, subject)
11
- - Clock tolerance for time synchronization issues
12
- - Easy integration with Express.js applications
13
-
14
- ## Configuration Options
15
-
16
- ```javascript
17
- // Example configuration object
18
- const jwtOptions = {
19
- algorithm: 'dir', // JWE algorithm (default: 'dir')
20
- encryption: 'A256GCM', // JWE encryption method (default: 'A256GCM')
21
- expirationTime: '10m', // Token expiration (default: '10m')
22
- clockTolerance: 30, // Clock tolerance in seconds (default: 30)
23
- secretHashAlgorithm: 'SHA-256', // Hash algorithm for secret derivation (default: 'SHA-256')
24
- issuer: 'your-app', // Optional JWT issuer claim
25
- audience: 'your-users', // Optional JWT audience claim
26
- subject: 'user-session' // Optional JWT subject claim
27
- };
28
- ```
29
-
30
- ## Basic Usage
31
-
32
- ```javascript
33
- import { JwtManager } from '@igxjs/node-components';
34
-
35
- // Create instance with default configuration
36
- const jwtManager = new JwtManager({
37
- expirationTime: '1h',
38
- issuer: 'my-app',
39
- audience: 'my-users'
40
- });
41
-
42
- // Encrypt user data
43
- const userData = {
44
- userId: '12345',
45
- email: 'user@example.com',
46
- roles: ['admin', 'user']
47
- };
48
-
49
- const secret = 'your-secret-key';
50
- const token = await jwtManager.encrypt(userData, secret);
51
-
52
- console.log('Encrypted Token:', token);
53
-
54
- // Decrypt token
55
- try {
56
- const result = await jwtManager.decrypt(token, secret);
57
- console.log('Decrypted Payload:', result.payload);
58
- console.log('Protected Header:', result.protectedHeader);
59
- } catch (error) {
60
- console.error('Token validation failed:', error);
61
- }
62
- ```
63
-
64
- ## API Reference
65
-
66
- ### Constructor
67
-
68
- **`new JwtManager(options?)`**
69
-
70
- Create a new JwtManager instance. All options are optional with sensible defaults.
71
-
72
- **Parameters:**
73
- - `options` (JwtManagerOptions, optional) - Configuration options
74
-
75
- ### Methods
76
-
77
- #### `encrypt(data, input, options?)`
78
-
79
- Generate an encrypted JWT token.
80
-
81
- **Parameters:**
82
- - `data` (JWTPayload) - User data payload to encrypt
83
- - `input` (string) - Secret key or password for encryption
84
- - `options` (JwtEncryptOptions, optional) - Per-call configuration overrides
85
-
86
- **Returns:** `Promise<string>` - Encrypted JWT token
87
-
88
- #### `decrypt(token, input, options?)`
89
-
90
- Decrypt and validate a JWT token.
91
-
92
- **Parameters:**
93
- - `token` (string) - JWT token to decrypt
94
- - `input` (string) - Secret key or password for decryption
95
- - `options` (JwtDecryptOptions, optional) - Per-call configuration overrides
96
-
97
- **Returns:** `Promise<JWTDecryptResult>` - Object containing `payload` and `protectedHeader`
98
-
99
- ## Configuration Details
100
-
101
- ### Algorithms
102
- - `'dir'` (default) - Direct encryption with shared symmetric key
103
- - `'A128KW'`, `'A192KW'`, `'A256KW'` - AES Key Wrap algorithms
104
-
105
- ### Encryption Methods
106
- - `'A256GCM'` (default) - AES-GCM with 256-bit key
107
- - `'A128GCM'`, `'A192GCM'` - AES-GCM with 128/192-bit keys
108
-
109
- ### Expiration Time Format
110
- - `'10m'` - 10 minutes
111
- - `'1h'` - 1 hour
112
- - `'7d'` - 7 days
113
- - `'30s'` - 30 seconds
114
-
115
- ### JWT Claims
116
- - `issuer` (iss) - Token issuer identification
117
- - `audience` (aud) - Intended token recipient
118
- - `subject` (sub) - Token subject (usually user ID)
119
-
120
- ## Related Documentation
121
-
122
- - [SessionManager](./session-manager.md) - For SSO-based session management
123
- - [HTTP Handlers](./http-handlers.md) - For error handling in authentication flows
124
- - [Back to main documentation](../README.md)
@@ -1,210 +0,0 @@
1
- # RedisManager
2
-
3
- Redis connection management with TLS support and automatic reconnection handling.
4
-
5
- ## Overview
6
-
7
- RedisManager provides a robust Redis client with:
8
- - TLS/SSL support for secure connections
9
- - Automatic reconnection handling
10
- - Connection status monitoring
11
- - Clean disconnection management
12
-
13
- **Note:** RedisManager is used internally by the [SessionManager](./session-manager.md), so you typically don't need to use it directly unless you need custom Redis operations.
14
-
15
- ## Usage Example
16
-
17
- ```javascript
18
- import { RedisManager } from '@igxjs/node-components';
19
-
20
- const redisManager = new RedisManager();
21
-
22
- // Connect to Redis (with optional TLS certificate)
23
- const connected = await redisManager.connect(
24
- 'rediss://localhost:6379',
25
- '/path/to/cert.pem'
26
- );
27
-
28
- if (connected) {
29
- // Get Redis client for direct operations
30
- const client = redisManager.getClient();
31
- await client.set('key', 'value');
32
- const value = await client.get('key');
33
- console.log(value); // 'value'
34
-
35
- // Check connection status
36
- const isConnected = await redisManager.isConnected();
37
- console.log('Connected:', isConnected);
38
-
39
- // Disconnect when done
40
- await redisManager.disConnect();
41
- }
42
- ```
43
-
44
- ## Connection URLs
45
-
46
- RedisManager supports two URL formats:
47
-
48
- ### Standard Redis (non-TLS)
49
- ```javascript
50
- await redisManager.connect('redis://localhost:6379');
51
- await redisManager.connect('redis://username:password@host:6379');
52
- ```
53
-
54
- ### Secure Redis (TLS)
55
- ```javascript
56
- // Requires certificate path for TLS
57
- await redisManager.connect(
58
- 'rediss://localhost:6379',
59
- '/path/to/certificate.pem'
60
- );
61
- ```
62
-
63
- ## Advanced Usage
64
-
65
- ### Custom Operations
66
-
67
- ```javascript
68
- import { RedisManager } from '@igxjs/node-components';
69
-
70
- const redisManager = new RedisManager();
71
- await redisManager.connect(process.env.REDIS_URL);
72
-
73
- const client = redisManager.getClient();
74
-
75
- // String operations
76
- await client.set('user:1', JSON.stringify({ name: 'John' }));
77
- const user = JSON.parse(await client.get('user:1'));
78
-
79
- // Hash operations
80
- await client.hSet('user:2', 'name', 'Jane');
81
- await client.hSet('user:2', 'email', 'jane@example.com');
82
- const userData = await client.hGetAll('user:2');
83
-
84
- // List operations
85
- await client.lPush('tasks', 'task1');
86
- await client.lPush('tasks', 'task2');
87
- const tasks = await client.lRange('tasks', 0, -1);
88
-
89
- // Set operations
90
- await client.sAdd('tags', 'javascript');
91
- await client.sAdd('tags', 'nodejs');
92
- const tags = await client.sMembers('tags');
93
-
94
- // Expiration
95
- await client.setEx('temporary', 3600, 'expires in 1 hour');
96
- await client.expire('user:1', 3600);
97
-
98
- // Clean up
99
- await redisManager.disConnect();
100
- ```
101
-
102
- ### Connection Monitoring
103
-
104
- ```javascript
105
- const redisManager = new RedisManager();
106
-
107
- // Check if connected before operations
108
- if (await redisManager.isConnected()) {
109
- const client = redisManager.getClient();
110
- // Perform operations
111
- } else {
112
- console.log('Redis not connected');
113
- }
114
- ```
115
-
116
- ### Error Handling
117
-
118
- ```javascript
119
- const redisManager = new RedisManager();
120
-
121
- try {
122
- const connected = await redisManager.connect(process.env.REDIS_URL);
123
-
124
- if (!connected) {
125
- console.error('Failed to connect to Redis');
126
- // Fall back to memory storage or handle appropriately
127
- return;
128
- }
129
-
130
- const client = redisManager.getClient();
131
- await client.set('key', 'value');
132
-
133
- } catch (error) {
134
- console.error('Redis operation failed:', error);
135
- } finally {
136
- await redisManager.disConnect();
137
- }
138
- ```
139
-
140
- ## API Methods
141
-
142
- ### `connect(redisUrl, certPath?)`
143
-
144
- Connect to Redis server.
145
-
146
- **Parameters:**
147
- - `redisUrl` (string) - Redis connection URL (`redis://` or `rediss://`)
148
- - `certPath` (string, optional) - Path to TLS certificate file (required for `rediss://`)
149
-
150
- **Returns:** `Promise<boolean>` - Returns `true` if connected successfully
151
-
152
- **Example:**
153
- ```javascript
154
- // Non-TLS connection
155
- await redisManager.connect('redis://localhost:6379');
156
-
157
- // TLS connection
158
- await redisManager.connect('rediss://localhost:6379', '/path/to/cert.pem');
159
- ```
160
-
161
- ### `getClient()`
162
-
163
- Get the Redis client instance for direct operations.
164
-
165
- **Returns:** Redis client object
166
-
167
- **Example:**
168
- ```javascript
169
- const client = redisManager.getClient();
170
- await client.set('key', 'value');
171
- await client.get('key');
172
- ```
173
-
174
- ### `isConnected()`
175
-
176
- Check if Redis connection is active and responsive.
177
-
178
- **Returns:** `Promise<boolean>` - Returns `true` if connected and responsive
179
-
180
- **Example:**
181
- ```javascript
182
- const connected = await redisManager.isConnected();
183
- if (connected) {
184
- // Proceed with operations
185
- }
186
- ```
187
-
188
- ### `disConnect()`
189
-
190
- Disconnect from Redis server and clean up resources.
191
-
192
- **Returns:** `Promise<void>`
193
-
194
- **Example:**
195
- ```javascript
196
- await redisManager.disConnect();
197
- ```
198
-
199
- ## Features
200
-
201
- - **Automatic Reconnection**: Handles connection drops and reconnects automatically
202
- - **TLS Support**: Secure connections with certificate-based authentication
203
- - **Connection Pooling**: Efficient connection management
204
- - **Error Handling**: Graceful error handling and logging
205
- - **Health Checks**: Built-in connection status monitoring
206
-
207
- ## Related Documentation
208
-
209
- - [SessionManager](./session-manager.md) - Uses RedisManager for session storage
210
- - [Back to main documentation](../README.md)