@venizia/ignis-docs 0.0.5 → 0.0.6-0

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 (98) hide show
  1. package/package.json +1 -1
  2. package/wiki/best-practices/architecture-decisions.md +0 -8
  3. package/wiki/best-practices/code-style-standards/control-flow.md +1 -1
  4. package/wiki/best-practices/performance-optimization.md +3 -3
  5. package/wiki/best-practices/security-guidelines.md +2 -2
  6. package/wiki/best-practices/troubleshooting-tips.md +1 -1
  7. package/wiki/guides/core-concepts/components-guide.md +1 -1
  8. package/wiki/guides/core-concepts/components.md +2 -2
  9. package/wiki/guides/core-concepts/dependency-injection.md +1 -1
  10. package/wiki/guides/core-concepts/services.md +1 -1
  11. package/wiki/guides/tutorials/building-a-crud-api.md +1 -1
  12. package/wiki/guides/tutorials/ecommerce-api.md +2 -2
  13. package/wiki/guides/tutorials/realtime-chat.md +6 -6
  14. package/wiki/guides/tutorials/testing.md +1 -1
  15. package/wiki/references/base/bootstrapping.md +0 -2
  16. package/wiki/references/base/components.md +2 -2
  17. package/wiki/references/base/controllers.md +0 -1
  18. package/wiki/references/base/datasources.md +1 -1
  19. package/wiki/references/base/dependency-injection.md +1 -1
  20. package/wiki/references/base/filter-system/quick-reference.md +0 -14
  21. package/wiki/references/base/middlewares.md +0 -8
  22. package/wiki/references/base/providers.md +0 -9
  23. package/wiki/references/base/services.md +0 -1
  24. package/wiki/references/components/authentication/api.md +444 -0
  25. package/wiki/references/components/authentication/errors.md +177 -0
  26. package/wiki/references/components/authentication/index.md +571 -0
  27. package/wiki/references/components/authentication/usage.md +781 -0
  28. package/wiki/references/components/health-check.md +292 -103
  29. package/wiki/references/components/index.md +14 -12
  30. package/wiki/references/components/mail/api.md +505 -0
  31. package/wiki/references/components/mail/errors.md +176 -0
  32. package/wiki/references/components/mail/index.md +535 -0
  33. package/wiki/references/components/mail/usage.md +404 -0
  34. package/wiki/references/components/request-tracker.md +229 -25
  35. package/wiki/references/components/socket-io/api.md +1051 -0
  36. package/wiki/references/components/socket-io/errors.md +119 -0
  37. package/wiki/references/components/socket-io/index.md +410 -0
  38. package/wiki/references/components/socket-io/usage.md +322 -0
  39. package/wiki/references/components/static-asset/api.md +261 -0
  40. package/wiki/references/components/static-asset/errors.md +89 -0
  41. package/wiki/references/components/static-asset/index.md +617 -0
  42. package/wiki/references/components/static-asset/usage.md +364 -0
  43. package/wiki/references/components/swagger.md +390 -110
  44. package/wiki/references/components/template/api-page.md +125 -0
  45. package/wiki/references/components/template/errors-page.md +100 -0
  46. package/wiki/references/components/template/index.md +104 -0
  47. package/wiki/references/components/template/setup-page.md +134 -0
  48. package/wiki/references/components/template/single-page.md +132 -0
  49. package/wiki/references/components/template/usage-page.md +127 -0
  50. package/wiki/references/components/websocket/api.md +508 -0
  51. package/wiki/references/components/websocket/errors.md +123 -0
  52. package/wiki/references/components/websocket/index.md +453 -0
  53. package/wiki/references/components/websocket/usage.md +475 -0
  54. package/wiki/references/helpers/cron/index.md +224 -0
  55. package/wiki/references/helpers/crypto/index.md +537 -0
  56. package/wiki/references/helpers/env/index.md +214 -0
  57. package/wiki/references/helpers/error/index.md +232 -0
  58. package/wiki/references/helpers/index.md +16 -15
  59. package/wiki/references/helpers/inversion/index.md +608 -0
  60. package/wiki/references/helpers/logger/index.md +600 -0
  61. package/wiki/references/helpers/network/api.md +986 -0
  62. package/wiki/references/helpers/network/index.md +620 -0
  63. package/wiki/references/helpers/queue/index.md +589 -0
  64. package/wiki/references/helpers/redis/index.md +495 -0
  65. package/wiki/references/helpers/socket-io/api.md +497 -0
  66. package/wiki/references/helpers/socket-io/index.md +513 -0
  67. package/wiki/references/helpers/storage/api.md +705 -0
  68. package/wiki/references/helpers/storage/index.md +583 -0
  69. package/wiki/references/helpers/template/index.md +66 -0
  70. package/wiki/references/helpers/template/single-page.md +126 -0
  71. package/wiki/references/helpers/testing/index.md +510 -0
  72. package/wiki/references/helpers/types/index.md +512 -0
  73. package/wiki/references/helpers/uid/index.md +272 -0
  74. package/wiki/references/helpers/websocket/api.md +736 -0
  75. package/wiki/references/helpers/websocket/index.md +574 -0
  76. package/wiki/references/helpers/worker-thread/index.md +470 -0
  77. package/wiki/references/quick-reference.md +3 -18
  78. package/wiki/references/utilities/jsx.md +1 -8
  79. package/wiki/references/utilities/statuses.md +0 -7
  80. package/wiki/references/components/authentication.md +0 -476
  81. package/wiki/references/components/mail.md +0 -687
  82. package/wiki/references/components/socket-io.md +0 -562
  83. package/wiki/references/components/static-asset.md +0 -1277
  84. package/wiki/references/helpers/cron.md +0 -108
  85. package/wiki/references/helpers/crypto.md +0 -132
  86. package/wiki/references/helpers/env.md +0 -83
  87. package/wiki/references/helpers/error.md +0 -97
  88. package/wiki/references/helpers/inversion.md +0 -176
  89. package/wiki/references/helpers/logger.md +0 -296
  90. package/wiki/references/helpers/network.md +0 -396
  91. package/wiki/references/helpers/queue.md +0 -150
  92. package/wiki/references/helpers/redis.md +0 -142
  93. package/wiki/references/helpers/socket-io.md +0 -932
  94. package/wiki/references/helpers/storage.md +0 -665
  95. package/wiki/references/helpers/testing.md +0 -133
  96. package/wiki/references/helpers/types.md +0 -167
  97. package/wiki/references/helpers/uid.md +0 -167
  98. package/wiki/references/helpers/worker-thread.md +0 -178
@@ -1,296 +0,0 @@
1
- # Logger Helper
2
-
3
- Powerful, flexible logging built on Winston - supports multiple transports, log levels, hierarchical scopes, and high-frequency logging for performance-critical applications.
4
-
5
- ## Quick Reference
6
-
7
- | Feature | Description |
8
- |---------|-------------|
9
- | **Factory Method** | `LoggerFactory.getLogger(['scope1', 'scope2'])` |
10
- | **Direct Access** | `Logger.get('scope')` |
11
- | **Method Scoping** | `logger.for('methodName').info('message')` |
12
- | **Log Levels** | `error`, `alert`, `emerg`, `warn`, `info`, `http`, `verbose`, `debug`, `silly` |
13
- | **Transports** | Console (default), DailyRotateFile, UDP/Dgram |
14
- | **Formats** | JSON (`json`), Pretty Text (`text`) |
15
- | **HF Logger** | Zero-allocation logging for HFT use cases |
16
-
17
- ### Common Methods
18
-
19
- ```typescript
20
- logger.info('message'); // Informational
21
- logger.error('message'); // Error
22
- logger.warn('message'); // Warning
23
- logger.debug('message'); // Debug (requires DEBUG=true)
24
- logger.for('methodName').info('message'); // Method-scoped logging
25
- ```
26
-
27
- ## Getting a Logger Instance
28
-
29
- ### Using LoggerFactory (Recommended)
30
-
31
- ```typescript
32
- import { LoggerFactory } from '@venizia/ignis-helpers';
33
-
34
- const logger = LoggerFactory.getLogger(['MyService']);
35
-
36
- logger.info('This is an informational message.');
37
- logger.error('This is an error message.');
38
- ```
39
-
40
- ### Using Logger.get() Directly
41
-
42
- ```typescript
43
- import { Logger } from '@venizia/ignis-helpers';
44
-
45
- const logger = Logger.get('MyService');
46
- logger.info('Direct logger access');
47
- ```
48
-
49
- ### Logger Caching
50
-
51
- Both methods use internal caching - the same scope always returns the same logger instance:
52
-
53
- ```typescript
54
- const logger1 = Logger.get('MyService');
55
- const logger2 = Logger.get('MyService');
56
- // logger1 === logger2 (same instance)
57
- ```
58
-
59
- ## Method-Scoped Logging with `.for()`
60
-
61
- The `.for()` method creates a sub-scoped logger for specific methods, making it easy to trace logs:
62
-
63
- ```typescript
64
- class UserService {
65
- private logger = LoggerFactory.getLogger(['UserService']);
66
-
67
- async createUser(data: CreateUserDto) {
68
- this.logger.for('createUser').info('Creating user: %j', data);
69
- // Output: [UserService-createUser] Creating user: {...}
70
-
71
- try {
72
- const user = await this.userRepo.create({ data });
73
- this.logger.for('createUser').info('User created: %s', user.id);
74
- return user;
75
- } catch (error) {
76
- this.logger.for('createUser').error('Failed to create user: %s', error);
77
- throw error;
78
- }
79
- }
80
- }
81
- ```
82
-
83
- ## Log Formats
84
-
85
- The logger supports two output formats controlled by `APP_ENV_LOGGER_FORMAT`:
86
-
87
- ### JSON Format
88
-
89
- ```bash
90
- APP_ENV_LOGGER_FORMAT=json
91
- ```
92
-
93
- Output:
94
- ```json
95
- {"level":"info","message":"[UserService] User created","timestamp":"2024-01-11T10:30:00.000Z","label":"app"}
96
- ```
97
-
98
- ### Pretty Text Format (Default)
99
-
100
- ```bash
101
- APP_ENV_LOGGER_FORMAT=text
102
- ```
103
-
104
- Output:
105
- ```
106
- 2024-01-11T10:30:00.000Z [app] info: [UserService] User created
107
- ```
108
-
109
- ## File Rotation Configuration
110
-
111
- Configure file rotation through environment variables or programmatically:
112
-
113
- ### Environment Variables
114
-
115
- | Variable | Default | Description |
116
- |----------|---------|-------------|
117
- | `APP_ENV_LOGGER_FILE_FREQUENCY` | `1h` | Rotation frequency |
118
- | `APP_ENV_LOGGER_FILE_MAX_SIZE` | `100m` | Max file size before rotation |
119
- | `APP_ENV_LOGGER_FILE_MAX_FILES` | `5d` | Retention period (days) |
120
- | `APP_ENV_LOGGER_FILE_DATE_PATTERN` | `YYYYMMDD_HH` | Date pattern in filename |
121
- | `APP_ENV_LOGGER_FOLDER_PATH` | `./` | Log files directory |
122
-
123
- ### Programmatic Configuration
124
-
125
- ```typescript
126
- import { defineCustomLogger, applicationLogFormatter } from '@venizia/ignis-helpers';
127
-
128
- const customLogger = defineCustomLogger({
129
- loggerFormatter: applicationLogFormatter,
130
- transports: {
131
- info: {
132
- file: {
133
- prefix: 'my-app',
134
- folder: './logs',
135
- frequency: '24h', // Rotate daily
136
- maxSize: '500m', // 500MB max
137
- maxFiles: '30d', // Keep 30 days
138
- datePattern: 'YYYYMMDD' // Daily pattern
139
- }
140
- },
141
- error: {
142
- file: {
143
- prefix: 'my-app-error',
144
- folder: './logs',
145
- maxFiles: '90d' // Keep error logs longer
146
- }
147
- }
148
- }
149
- });
150
- ```
151
-
152
- ## High-Frequency Logger (HfLogger)
153
-
154
- For performance-critical applications like HFT systems, use `HfLogger` which provides:
155
-
156
- - Zero allocation in hot path
157
- - Lock-free ring buffer (64K entries)
158
- - Sub-microsecond latency (~100-300ns)
159
- - Pre-encoded messages
160
- - Async background flushing
161
-
162
- ### Basic Usage
163
-
164
- ```typescript
165
- import { HfLogger, HfLogFlusher } from '@venizia/ignis-helpers';
166
-
167
- // At initialization time (once):
168
- const logger = HfLogger.get('OrderEngine');
169
- const MSG_ORDER_SENT = HfLogger.encodeMessage('Order sent');
170
- const MSG_ORDER_FILLED = HfLogger.encodeMessage('Order filled');
171
-
172
- // Start background flusher
173
- const flusher = new HfLogFlusher();
174
- flusher.start(100); // Flush every 100ms
175
-
176
- // In hot path (~100-300ns, zero allocation):
177
- logger.log('info', MSG_ORDER_SENT);
178
- logger.log('info', MSG_ORDER_FILLED);
179
- ```
180
-
181
- ### HfLogger API
182
-
183
- | Method | Description |
184
- |--------|-------------|
185
- | `HfLogger.get(scope)` | Get/create a cached logger instance |
186
- | `HfLogger.encodeMessage(msg)` | Pre-encode a message (cached) |
187
- | `logger.log(level, msgBytes)` | Log to ring buffer (zero allocation) |
188
-
189
- ### HfLogFlusher API
190
-
191
- | Method | Description |
192
- |--------|-------------|
193
- | `flusher.flush()` | Flush buffered entries to output |
194
- | `flusher.start(intervalMs)` | Start background flush loop |
195
-
196
- ### Performance Characteristics
197
-
198
- | Metric | Value |
199
- |--------|-------|
200
- | Log latency | ~100-300 nanoseconds |
201
- | Buffer size | 64K entries (16MB) |
202
- | Entry size | 256 bytes fixed |
203
- | Allocation | Zero in hot path |
204
-
205
- ## Environment Variables
206
-
207
- ### Core Configuration
208
-
209
- | Variable | Default | Description |
210
- |----------|---------|-------------|
211
- | `DEBUG` | `false` | Enable debug logging |
212
- | `APP_ENV_EXTRA_LOG_ENVS` | `` | Additional environments to enable debug |
213
- | `APP_ENV_LOGGER_FORMAT` | `text` | Output format (`json` or `text`) |
214
- | `APP_ENV_LOGGER_FOLDER_PATH` | `./` | Log files directory |
215
-
216
- ### UDP Transport
217
-
218
- | Variable | Description |
219
- |----------|-------------|
220
- | `APP_ENV_LOGGER_DGRAM_HOST` | UDP log aggregator host |
221
- | `APP_ENV_LOGGER_DGRAM_PORT` | UDP log aggregator port |
222
- | `APP_ENV_LOGGER_DGRAM_LABEL` | Label to identify log source |
223
- | `APP_ENV_LOGGER_DGRAM_LEVELS` | Comma-separated levels to send via UDP |
224
-
225
- ### Example `.env`
226
-
227
- ```bash
228
- # Core
229
- DEBUG=true
230
- APP_ENV_LOGGER_FORMAT=json
231
- APP_ENV_LOGGER_FOLDER_PATH=./app_data/logs
232
-
233
- # File rotation
234
- APP_ENV_LOGGER_FILE_FREQUENCY=24h
235
- APP_ENV_LOGGER_FILE_MAX_SIZE=500m
236
- APP_ENV_LOGGER_FILE_MAX_FILES=30d
237
-
238
- # UDP transport
239
- APP_ENV_LOGGER_DGRAM_HOST=127.0.0.1
240
- APP_ENV_LOGGER_DGRAM_PORT=5000
241
- APP_ENV_LOGGER_DGRAM_LABEL=my-app
242
- APP_ENV_LOGGER_DGRAM_LEVELS=error,warn,info
243
- ```
244
-
245
- ## Best Practices
246
-
247
- ### 1. Use Method-Scoped Logging
248
-
249
- ```typescript
250
- // Good - clear context
251
- this.logger.for('createOrder').info('Processing order: %s', orderId);
252
-
253
- // Less clear
254
- this.logger.info('[createOrder] Processing order: %s', orderId);
255
- ```
256
-
257
- ### 2. Pre-encode HfLogger Messages
258
-
259
- ```typescript
260
- // Good - pre-encoded at init
261
- const MSG_TICK = HfLogger.encodeMessage('Tick received');
262
- logger.log('debug', MSG_TICK);
263
-
264
- // Bad - encodes on every call
265
- logger.log('debug', HfLogger.encodeMessage('Tick received'));
266
- ```
267
-
268
- ### 3. Use Appropriate Logger for Use Case
269
-
270
- | Use Case | Logger |
271
- |----------|--------|
272
- | General application | `Logger` / `LoggerFactory` |
273
- | High-frequency trading | `HfLogger` |
274
- | Performance-critical paths | `HfLogger` |
275
- | Debug/development | `Logger` with `DEBUG=true` |
276
-
277
- ## See Also
278
-
279
- - **Related Concepts:**
280
- - [Services](/guides/core-concepts/services) - Logging in services
281
- - [Controllers](/guides/core-concepts/controllers) - Logging in controllers
282
-
283
- - **Other Helpers:**
284
- - [Helpers Index](./index) - All available helpers
285
- - [Error Helper](./error) - Error handling utilities
286
-
287
- - **References:**
288
- - [Request Tracker Component](/references/components/request-tracker) - Request logging
289
- - [Environment Variables](/references/configuration/environment-variables) - All configuration options
290
-
291
- - **External Resources:**
292
- - [Winston Documentation](https://github.com/winstonjs/winston) - Winston logging library
293
-
294
- - **Best Practices:**
295
- - [Troubleshooting Tips](/best-practices/troubleshooting-tips) - Using logs for debugging
296
- - [Performance Optimization](/best-practices/performance-optimization) - High-performance logging
@@ -1,396 +0,0 @@
1
- # Network Helper
2
-
3
- Comprehensive network communication utilities for HTTP, TCP, and UDP protocols with full TypeScript support and customizable options.
4
-
5
- ## Quick Reference
6
-
7
- | Helper | Protocol | Type | Use Case |
8
- |--------|----------|------|----------|
9
- | **AxiosNetworkRequest** | HTTP/HTTPS | Client | REST API calls (axios-based) |
10
- | **NodeFetchNetworkRequest** | HTTP/HTTPS | Client | REST API calls (native fetch) |
11
- | **NetworkTcpClient** | TCP/TLS | Client | Raw TCP connections |
12
- | **NetworkTcpServer** | TCP/TLS | Server | TCP server implementation |
13
- | **NetworkUdpClient** | UDP | Client | Datagram sockets |
14
-
15
- ### HTTP Methods
16
-
17
- | Method | Purpose |
18
- |--------|---------|
19
- | `send({ url, method: 'get' })` | GET request |
20
- | `send({ url, method: 'post', body })` | POST request |
21
- | `send({ url, method: 'put', body })` | PUT request |
22
- | `send({ url, method: 'delete' })` | DELETE request |
23
-
24
- ### TCP Operations
25
-
26
- | Class | Methods |
27
- |-------|---------|
28
- | **Client** | `connect()`, `emit({ payload })`, `disconnect()`, `forceReconnect()` |
29
- | **Server** | `broadcast({ message })`, `sendToClient({ id, message })` |
30
-
31
- ## HTTP Request
32
-
33
- The HTTP request helper provides a flexible and extensible framework for making HTTP requests, supporting both `axios` and the native Node.js `fetch` API.
34
-
35
- ### Configuration Interfaces
36
-
37
- ```typescript
38
- // Axios configuration
39
- interface IAxiosNetworkRequestOptions {
40
- name: string;
41
- networkOptions: Omit<AxiosRequestConfig, 'baseURL'> & {
42
- baseUrl?: string;
43
- };
44
- }
45
-
46
- // Node Fetch configuration
47
- interface INodeFetchNetworkRequestOptions {
48
- name: string;
49
- networkOptions: RequestInit & {
50
- baseUrl?: string;
51
- };
52
- }
53
- ```
54
-
55
- ### Using Axios
56
-
57
- ```typescript
58
- import { AxiosNetworkRequest } from '@venizia/ignis-helpers';
59
-
60
- class MyApiClient extends AxiosNetworkRequest {
61
- constructor() {
62
- super({
63
- name: 'MyApiClient',
64
- networkOptions: {
65
- baseUrl: 'https://api.example.com',
66
- timeout: 5000,
67
- headers: {
68
- 'X-Custom-Header': 'MyValue',
69
- 'Authorization': 'Bearer token',
70
- },
71
- // Full axios options available
72
- withCredentials: true,
73
- validateStatus: (status) => status < 500,
74
- },
75
- });
76
- }
77
-
78
- async getUsers() {
79
- const response = await this.getNetworkService().send({
80
- url: '/users',
81
- method: 'get',
82
- });
83
- return response.data;
84
- }
85
-
86
- async createUser(data: CreateUserDto) {
87
- const response = await this.getNetworkService().send({
88
- url: '/users',
89
- method: 'post',
90
- body: data,
91
- });
92
- return response.data;
93
- }
94
- }
95
- ```
96
-
97
- ### Using Node.js Fetch
98
-
99
- ```typescript
100
- import { NodeFetchNetworkRequest } from '@venizia/ignis-helpers';
101
-
102
- class MyApiClient extends NodeFetchNetworkRequest {
103
- constructor() {
104
- super({
105
- name: 'MyApiClient',
106
- networkOptions: {
107
- baseUrl: 'https://api.example.com',
108
- headers: {
109
- 'Content-Type': 'application/json',
110
- },
111
- // Full RequestInit options available
112
- credentials: 'include',
113
- mode: 'cors',
114
- },
115
- });
116
- }
117
-
118
- async getUsers() {
119
- const response = await this.getNetworkService().send({
120
- url: '/users',
121
- method: 'get',
122
- timeout: 5000, // Timeout support
123
- });
124
- return response.json();
125
- }
126
- }
127
- ```
128
-
129
- ### Request Options
130
-
131
- #### Axios Request Options
132
-
133
- ```typescript
134
- interface IAxiosRequestOptions {
135
- url: string;
136
- method?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options';
137
- params?: Record<string, any>; // Query parameters
138
- body?: any; // Request body
139
- headers?: Record<string, string>; // Additional headers
140
- rejectUnauthorized?: boolean; // SSL verification (default: false)
141
- // Plus all AxiosRequestConfig options
142
- }
143
- ```
144
-
145
- #### Node Fetch Request Options
146
-
147
- ```typescript
148
- interface INodeFetchRequestOptions {
149
- url: string;
150
- method?: string;
151
- params?: Record<string, any>; // Query parameters
152
- body?: any; // Request body
153
- headers?: Record<string, string>;
154
- timeout?: number; // Request timeout in ms
155
- // Plus all RequestInit options
156
- }
157
- ```
158
-
159
- ## TCP Socket
160
-
161
- The TCP Socket helpers provide robust TCP and TLS/SSL connection management with automatic reconnection.
162
-
163
- ### TCP Client
164
-
165
- ```typescript
166
- import { NetworkTcpClient } from '@venizia/ignis-helpers';
167
-
168
- const tcpClient = new NetworkTcpClient({
169
- identifier: 'my-tcp-client',
170
- options: {
171
- host: 'localhost',
172
- port: 8080,
173
- },
174
- reconnect: true, // Auto-reconnect on disconnect
175
- maxRetry: 5, // Max reconnection attempts
176
- encoding: 'utf8', // Data encoding
177
-
178
- onConnected: ({ client }) => {
179
- console.log('Connected to server');
180
- },
181
- onData: ({ identifier, message }) => {
182
- console.log('Received:', message.toString());
183
- },
184
- onClosed: ({ client }) => {
185
- console.log('Connection closed');
186
- },
187
- onError: (error) => {
188
- console.error('Connection error:', error);
189
- },
190
- });
191
-
192
- // Connect
193
- tcpClient.connect({ resetReconnectCounter: true });
194
-
195
- // Send data
196
- tcpClient.emit({ payload: 'Hello, Server!' });
197
- tcpClient.emit({ payload: Buffer.from([0x01, 0x02, 0x03]) });
198
-
199
- // Check connection
200
- if (tcpClient.isConnected()) {
201
- // ...
202
- }
203
-
204
- // Disconnect
205
- tcpClient.disconnect();
206
-
207
- // Force reconnect
208
- tcpClient.forceReconnect();
209
- ```
210
-
211
- ### TLS TCP Client
212
-
213
- ```typescript
214
- import { NetworkTlsTcpClient } from '@venizia/ignis-helpers';
215
-
216
- const tlsClient = new NetworkTlsTcpClient({
217
- identifier: 'secure-client',
218
- options: {
219
- host: 'secure.example.com',
220
- port: 443,
221
- rejectUnauthorized: true,
222
- // TLS options
223
- ca: fs.readFileSync('ca.crt'),
224
- cert: fs.readFileSync('client.crt'),
225
- key: fs.readFileSync('client.key'),
226
- },
227
- onData: ({ message }) => {
228
- console.log('Secure data:', message);
229
- },
230
- });
231
- ```
232
-
233
- ### TCP Server
234
-
235
- ```typescript
236
- import { NetworkTcpServer } from '@venizia/ignis-helpers';
237
-
238
- const tcpServer = new NetworkTcpServer({
239
- identifier: 'my-tcp-server',
240
- listenOptions: {
241
- port: 8080,
242
- host: '0.0.0.0',
243
- },
244
- authenticateOptions: {
245
- required: true,
246
- timeout: 5000,
247
- },
248
-
249
- onClientConnect: ({ id, socket }) => {
250
- console.log(`Client ${id} connected`);
251
- },
252
- onClientData: ({ id, data }) => {
253
- console.log(`Data from ${id}:`, data.toString());
254
- },
255
- onClientDisconnect: ({ id }) => {
256
- console.log(`Client ${id} disconnected`);
257
- },
258
- onAuthenticate: async ({ id, data }) => {
259
- // Return true to authenticate
260
- return data.toString() === 'secret-token';
261
- },
262
- });
263
-
264
- // Broadcast to all clients
265
- tcpServer.broadcast({ message: 'Hello everyone!' });
266
-
267
- // Send to specific client
268
- tcpServer.sendToClient({ clientId: 'client-123', message: 'Private message' });
269
-
270
- // Get connected clients
271
- const clients = tcpServer.getClients();
272
- ```
273
-
274
- ## UDP Socket
275
-
276
- The UDP Socket helper provides datagram socket communication with multicast support.
277
-
278
- ### UDP Client
279
-
280
- ```typescript
281
- import { NetworkUdpClient } from '@venizia/ignis-helpers';
282
-
283
- const udpClient = NetworkUdpClient.newInstance({
284
- identifier: 'my-udp-client',
285
- port: 8081,
286
- host: '0.0.0.0', // Bind address
287
- reuseAddr: true, // Allow address reuse
288
-
289
- // Multicast configuration
290
- multicastAddress: {
291
- groups: ['239.1.2.3'],
292
- interface: '0.0.0.0',
293
- },
294
-
295
- onConnected: ({ identifier, port }) => {
296
- console.log(`UDP socket bound to port ${port}`);
297
- },
298
- onData: ({ identifier, message, remoteInfo }) => {
299
- console.log(`From ${remoteInfo.address}:${remoteInfo.port}:`, message.toString());
300
- },
301
- onBind: async ({ socket, multicastAddress }) => {
302
- // Join multicast groups after binding
303
- if (multicastAddress?.groups) {
304
- for (const group of multicastAddress.groups) {
305
- socket.addMembership(group, multicastAddress.interface);
306
- }
307
- }
308
- },
309
- onError: ({ error }) => {
310
- console.error('UDP error:', error);
311
- },
312
- });
313
-
314
- // Start listening
315
- udpClient.connect();
316
-
317
- // Check status
318
- if (udpClient.isConnected()) {
319
- // ...
320
- }
321
-
322
- // Close
323
- udpClient.disconnect();
324
- ```
325
-
326
- ## Common Patterns
327
-
328
- ### Service with HTTP Client
329
-
330
- ```typescript
331
- import { AxiosNetworkRequest } from '@venizia/ignis-helpers';
332
-
333
- class PaymentGateway extends AxiosNetworkRequest {
334
- constructor() {
335
- super({
336
- name: 'PaymentGateway',
337
- networkOptions: {
338
- baseUrl: process.env.PAYMENT_API_URL,
339
- timeout: 30000,
340
- headers: {
341
- 'X-API-Key': process.env.PAYMENT_API_KEY,
342
- },
343
- },
344
- });
345
- }
346
-
347
- async charge(amount: number, currency: string) {
348
- const response = await this.getNetworkService().send({
349
- url: '/v1/charges',
350
- method: 'post',
351
- body: { amount, currency },
352
- });
353
-
354
- this.logger.for('charge').info('Payment processed: %s', response.data.id);
355
- return response.data;
356
- }
357
- }
358
- ```
359
-
360
- ### Real-time Data Feed (TCP)
361
-
362
- ```typescript
363
- import { NetworkTcpClient } from '@venizia/ignis-helpers';
364
-
365
- class MarketDataFeed extends NetworkTcpClient<TcpSocketConnectOpts, Socket> {
366
- constructor() {
367
- super({
368
- identifier: 'market-data',
369
- scope: 'MarketDataFeed',
370
- options: { host: 'feed.exchange.com', port: 9000 },
371
- reconnect: true,
372
- maxRetry: -1, // Infinite retries
373
- encoding: 'utf8',
374
- });
375
- }
376
-
377
- handleData(opts: { identifier: string; message: Buffer }) {
378
- const tick = JSON.parse(opts.message.toString());
379
- this.emit('tick', tick);
380
- }
381
- }
382
- ```
383
-
384
- ## See Also
385
-
386
- - **Related Concepts:**
387
- - [Services](/guides/core-concepts/services) - Network operations in services
388
-
389
- - **Other Helpers:**
390
- - [Helpers Index](./index) - All available helpers
391
- - [Queue Helper](./queue) - Message queuing
392
- - [Redis Helper](./redis) - Redis connections
393
-
394
- - **Best Practices:**
395
- - [Security Guidelines](/best-practices/security-guidelines) - Network security
396
- - [Performance Optimization](/best-practices/performance-optimization) - Connection pooling