@venizia/ignis-docs 0.0.4 → 0.0.5

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,6 +1,6 @@
1
1
  # Network Helper
2
2
 
3
- Comprehensive network communication utilities for HTTP, TCP, and UDP protocols.
3
+ Comprehensive network communication utilities for HTTP, TCP, and UDP protocols with full TypeScript support and customizable options.
4
4
 
5
5
  ## Quick Reference
6
6
 
@@ -16,30 +16,46 @@ Comprehensive network communication utilities for HTTP, TCP, and UDP protocols.
16
16
 
17
17
  | Method | Purpose |
18
18
  |--------|---------|
19
- | `get({ url })` | GET request |
20
- | `post({ url, data })` | POST request |
21
- | `put({ url, data })` | PUT request |
22
- | `delete({ url })` | DELETE request |
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
23
 
24
24
  ### TCP Operations
25
25
 
26
26
  | Class | Methods |
27
27
  |-------|---------|
28
- | **Client** | `connect()`, `emit({ payload })`, `disconnect()` |
28
+ | **Client** | `connect()`, `emit({ payload })`, `disconnect()`, `forceReconnect()` |
29
29
  | **Server** | `broadcast({ message })`, `sendToClient({ id, message })` |
30
30
 
31
31
  ## HTTP Request
32
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 as underlying clients.
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
34
 
35
- ### Creating an HTTP Client
35
+ ### Configuration Interfaces
36
36
 
37
- You can create a new HTTP client instance by extending either `AxiosNetworkRequest` or `NodeFetchNetworkRequest`.
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
+ ```
38
54
 
39
- **Using Axios:**
55
+ ### Using Axios
40
56
 
41
57
  ```typescript
42
- import { AxiosNetworkRequest } from '@venizia/ignis';
58
+ import { AxiosNetworkRequest } from '@venizia/ignis-helpers';
43
59
 
44
60
  class MyApiClient extends AxiosNetworkRequest {
45
61
  constructor() {
@@ -50,22 +66,38 @@ class MyApiClient extends AxiosNetworkRequest {
50
66
  timeout: 5000,
51
67
  headers: {
52
68
  'X-Custom-Header': 'MyValue',
69
+ 'Authorization': 'Bearer token',
53
70
  },
71
+ // Full axios options available
72
+ withCredentials: true,
73
+ validateStatus: (status) => status < 500,
54
74
  },
55
75
  });
56
76
  }
57
77
 
58
78
  async getUsers() {
59
- const response = await this.getNetworkService().get({ url: '/users' });
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
+ });
60
92
  return response.data;
61
93
  }
62
94
  }
63
95
  ```
64
96
 
65
- **Using Node.js Fetch:**
97
+ ### Using Node.js Fetch
66
98
 
67
99
  ```typescript
68
- import { NodeFetchNetworkRequest } from '@venizia/ignis';
100
+ import { NodeFetchNetworkRequest } from '@venizia/ignis-helpers';
69
101
 
70
102
  class MyApiClient extends NodeFetchNetworkRequest {
71
103
  constructor() {
@@ -73,73 +105,280 @@ class MyApiClient extends NodeFetchNetworkRequest {
73
105
  name: 'MyApiClient',
74
106
  networkOptions: {
75
107
  baseUrl: 'https://api.example.com',
76
- timeout: 5000,
108
+ headers: {
109
+ 'Content-Type': 'application/json',
110
+ },
111
+ // Full RequestInit options available
112
+ credentials: 'include',
113
+ mode: 'cors',
77
114
  },
78
115
  });
79
116
  }
80
117
 
81
118
  async getUsers() {
82
- const response = await this.getNetworkService().get({ url: '/users' });
119
+ const response = await this.getNetworkService().send({
120
+ url: '/users',
121
+ method: 'get',
122
+ timeout: 5000, // Timeout support
123
+ });
83
124
  return response.json();
84
125
  }
85
126
  }
86
127
  ```
87
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
+
88
159
  ## TCP Socket
89
160
 
90
- The TCP Socket helpers provide a robust way to create and manage TCP and TLS/SSL connections.
161
+ The TCP Socket helpers provide robust TCP and TLS/SSL connection management with automatic reconnection.
91
162
 
92
163
  ### TCP Client
93
164
 
94
165
  ```typescript
95
- import { NetworkTcpClient } from '@venizia/ignis';
166
+ import { NetworkTcpClient } from '@venizia/ignis-helpers';
96
167
 
97
168
  const tcpClient = new NetworkTcpClient({
98
169
  identifier: 'my-tcp-client',
99
- options: { host: 'localhost', port: 8080 },
100
- reconnect: true,
101
- onData: ({ message }) => {
102
- console.log('Received data:', message.toString());
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);
103
189
  },
104
190
  });
105
191
 
192
+ // Connect
106
193
  tcpClient.connect({ resetReconnectCounter: true });
194
+
195
+ // Send data
107
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
+ });
108
231
  ```
109
232
 
110
233
  ### TCP Server
111
234
 
112
235
  ```typescript
113
- import { NetworkTcpServer } from '@venizia/ignis';
236
+ import { NetworkTcpServer } from '@venizia/ignis-helpers';
114
237
 
115
238
  const tcpServer = new NetworkTcpServer({
116
239
  identifier: 'my-tcp-server',
117
- listenOptions: { port: 8080 },
118
- authenticateOptions: { required: false },
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
+ },
119
252
  onClientData: ({ id, data }) => {
120
- console.log(`Received data from client ${id}:`, data.toString());
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';
121
261
  },
122
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();
123
272
  ```
124
273
 
125
274
  ## UDP Socket
126
275
 
127
- The UDP Socket helper provides a way to create and manage UDP datagram sockets.
276
+ The UDP Socket helper provides datagram socket communication with multicast support.
128
277
 
129
278
  ### UDP Client
130
279
 
131
280
  ```typescript
132
- import { NetworkUdpClient } from '@venizia/ignis';
281
+ import { NetworkUdpClient } from '@venizia/ignis-helpers';
133
282
 
134
- const udpClient = new NetworkUdpClient({
283
+ const udpClient = NetworkUdpClient.newInstance({
135
284
  identifier: 'my-udp-client',
136
285
  port: 8081,
137
- onData: ({ message, remoteInfo }) => {
138
- console.log(`Received message from ${remoteInfo.address}:${remoteInfo.port}:`, message.toString());
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);
139
311
  },
140
312
  });
141
313
 
314
+ // Start listening
142
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
+ }
143
382
  ```
144
383
 
145
384
  ## See Also
@@ -149,6 +388,9 @@ udpClient.connect();
149
388
 
150
389
  - **Other Helpers:**
151
390
  - [Helpers Index](./index) - All available helpers
391
+ - [Queue Helper](./queue) - Message queuing
392
+ - [Redis Helper](./redis) - Redis connections
152
393
 
153
394
  - **Best Practices:**
154
395
  - [Security Guidelines](/best-practices/security-guidelines) - Network security
396
+ - [Performance Optimization](/best-practices/performance-optimization) - Connection pooling