@adaas/a-utils 0.1.14 → 0.1.16
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 +92 -18
- package/dist/index.d.mts +335 -71
- package/dist/index.d.ts +335 -71
- package/dist/index.js +491 -210
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +489 -210
- package/dist/index.mjs.map +1 -1
- package/examples/{channel-examples.ts → A-Channel-examples.ts} +15 -15
- package/examples/{command-examples.ts → A-Command-examples.ts} +47 -45
- package/examples/A-Logger-examples.ts +308 -0
- package/examples/config.ts +1 -1
- package/package.json +26 -7
- package/src/index.ts +3 -1
- package/src/lib/A-Channel/A-Channel.component.ts +84 -17
- package/src/lib/A-Channel/A-Channel.error.ts +5 -5
- package/src/lib/A-Channel/A-ChannelRequest.context.ts +1 -1
- package/src/lib/A-Channel/README.md +24 -24
- package/src/lib/A-Command/A-Command.constants.ts +49 -13
- package/src/lib/A-Command/A-Command.entity.ts +21 -15
- package/src/lib/A-Command/A-Command.types.ts +2 -35
- package/src/lib/A-Config/A-Config.container.ts +3 -3
- package/src/lib/A-Config/components/ConfigReader.component.ts +4 -6
- package/src/lib/A-Logger/A-Logger.component.ts +369 -130
- package/src/lib/A-Logger/A-Logger.constants.ts +69 -0
- package/src/lib/A-Logger/A-Logger.env.ts +27 -0
- package/src/lib/A-Logger/A-Logger.types.ts +3 -0
- package/src/lib/A-Logger/README.md +383 -0
- package/src/lib/A-Manifest/A-Manifest.types.ts +1 -2
- package/src/lib/A-Memory/A-Memory.context.ts +1 -1
- package/tests/A-Channel.test.ts +14 -14
- package/tests/A-Command.test.ts +26 -26
- package/tests/A-Logger.test.ts +520 -0
- package/tests/A-Memory.test.ts +5 -5
- package/tests/A-Polyfill.test.ts +3 -2
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import { A_Channel } from '../src/lib/A-Channel/A-Channel.component';
|
|
9
9
|
import { A_ChannelFeatures } from '../src/lib/A-Channel/A-Channel.constants';
|
|
10
|
-
import {
|
|
10
|
+
import { A_ChannelRequest } from '../src/lib/A-Channel/A-ChannelRequest.context';
|
|
11
11
|
import { A_Component, A_Context, A_Feature, A_Inject } from '@adaas/a-concept';
|
|
12
12
|
|
|
13
13
|
// Example 1: Basic Channel Usage
|
|
@@ -57,7 +57,7 @@ class HttpProcessor extends A_Component {
|
|
|
57
57
|
|
|
58
58
|
@A_Feature.Extend({ scope: [HttpChannel] })
|
|
59
59
|
async [A_ChannelFeatures.onBeforeRequest](
|
|
60
|
-
@A_Inject(
|
|
60
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<HttpRequest>
|
|
61
61
|
) {
|
|
62
62
|
const { method, url } = context.params;
|
|
63
63
|
console.log(`Preparing ${method} request to ${url}`);
|
|
@@ -70,7 +70,7 @@ class HttpProcessor extends A_Component {
|
|
|
70
70
|
|
|
71
71
|
@A_Feature.Extend({ scope: [HttpChannel] })
|
|
72
72
|
async [A_ChannelFeatures.onRequest](
|
|
73
|
-
@A_Inject(
|
|
73
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<HttpRequest, HttpResponse>
|
|
74
74
|
) {
|
|
75
75
|
const { method, url, headers, body } = context.params;
|
|
76
76
|
|
|
@@ -99,7 +99,7 @@ class HttpProcessor extends A_Component {
|
|
|
99
99
|
|
|
100
100
|
@A_Feature.Extend({ scope: [HttpChannel] })
|
|
101
101
|
async [A_ChannelFeatures.onAfterRequest](
|
|
102
|
-
@A_Inject(
|
|
102
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<HttpRequest, HttpResponse>
|
|
103
103
|
) {
|
|
104
104
|
const response = context.data;
|
|
105
105
|
console.log(`Request completed with status: ${response?.status}`);
|
|
@@ -107,7 +107,7 @@ class HttpProcessor extends A_Component {
|
|
|
107
107
|
|
|
108
108
|
@A_Feature.Extend({ scope: [HttpChannel] })
|
|
109
109
|
async [A_ChannelFeatures.onError](
|
|
110
|
-
@A_Inject(
|
|
110
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<HttpRequest>
|
|
111
111
|
) {
|
|
112
112
|
console.error(`HTTP request failed for ${context.params.method} ${context.params.url}`);
|
|
113
113
|
}
|
|
@@ -159,7 +159,7 @@ class EventBroadcaster extends A_Component {
|
|
|
159
159
|
|
|
160
160
|
@A_Feature.Extend({ scope: [EventChannel] })
|
|
161
161
|
async [A_ChannelFeatures.onSend](
|
|
162
|
-
@A_Inject(
|
|
162
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<EventMessage>
|
|
163
163
|
) {
|
|
164
164
|
const { eventType, payload, recipients, priority = 'normal' } = context.params;
|
|
165
165
|
|
|
@@ -177,7 +177,7 @@ class EventBroadcaster extends A_Component {
|
|
|
177
177
|
|
|
178
178
|
@A_Feature.Extend({ scope: [EventChannel] })
|
|
179
179
|
async [A_ChannelFeatures.onError](
|
|
180
|
-
@A_Inject(
|
|
180
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<EventMessage>
|
|
181
181
|
) {
|
|
182
182
|
console.error(`Failed to broadcast event: ${context.params.eventType}`);
|
|
183
183
|
}
|
|
@@ -254,7 +254,7 @@ class DatabaseProcessor extends A_Component {
|
|
|
254
254
|
|
|
255
255
|
@A_Feature.Extend({ scope: [DatabaseChannel] })
|
|
256
256
|
async [A_ChannelFeatures.onConnect]() {
|
|
257
|
-
const channel = A_Context.scope(this).resolve(DatabaseChannel)
|
|
257
|
+
const channel = A_Context.scope(this).resolve(DatabaseChannel)!;
|
|
258
258
|
|
|
259
259
|
// Initialize connection pool
|
|
260
260
|
for (let i = 0; i < 5; i++) {
|
|
@@ -269,9 +269,9 @@ class DatabaseProcessor extends A_Component {
|
|
|
269
269
|
|
|
270
270
|
@A_Feature.Extend({ scope: [DatabaseChannel] })
|
|
271
271
|
async [A_ChannelFeatures.onBeforeRequest](
|
|
272
|
-
@A_Inject(
|
|
272
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<DatabaseQuery>
|
|
273
273
|
) {
|
|
274
|
-
const channel = A_Context.scope(this).resolve(DatabaseChannel)
|
|
274
|
+
const channel = A_Context.scope(this).resolve(DatabaseChannel)!;
|
|
275
275
|
const { operation, table } = context.params;
|
|
276
276
|
|
|
277
277
|
console.log(`Executing ${operation} on table ${table}`);
|
|
@@ -292,7 +292,7 @@ class DatabaseProcessor extends A_Component {
|
|
|
292
292
|
|
|
293
293
|
@A_Feature.Extend({ scope: [DatabaseChannel] })
|
|
294
294
|
async [A_ChannelFeatures.onRequest](
|
|
295
|
-
@A_Inject(
|
|
295
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<DatabaseQuery, DatabaseResult>
|
|
296
296
|
) {
|
|
297
297
|
const { operation, table, where, data, limit } = context.params;
|
|
298
298
|
const startTime = Date.now();
|
|
@@ -343,7 +343,7 @@ class DatabaseProcessor extends A_Component {
|
|
|
343
343
|
|
|
344
344
|
@A_Feature.Extend({ scope: [DatabaseChannel] })
|
|
345
345
|
async [A_ChannelFeatures.onAfterRequest](
|
|
346
|
-
@A_Inject(
|
|
346
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<DatabaseQuery, DatabaseResult>
|
|
347
347
|
) {
|
|
348
348
|
// Release connection
|
|
349
349
|
const connection = (context as any)._connection;
|
|
@@ -358,7 +358,7 @@ class DatabaseProcessor extends A_Component {
|
|
|
358
358
|
|
|
359
359
|
@A_Feature.Extend({ scope: [DatabaseChannel] })
|
|
360
360
|
async [A_ChannelFeatures.onError](
|
|
361
|
-
@A_Inject(
|
|
361
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest<DatabaseQuery>
|
|
362
362
|
) {
|
|
363
363
|
// Release connection on error
|
|
364
364
|
const connection = (context as any)._connection;
|
|
@@ -421,7 +421,7 @@ class RobustProcessor extends A_Component {
|
|
|
421
421
|
|
|
422
422
|
@A_Feature.Extend({ scope: [RobustChannel] })
|
|
423
423
|
async [A_ChannelFeatures.onRequest](
|
|
424
|
-
@A_Inject(
|
|
424
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest
|
|
425
425
|
) {
|
|
426
426
|
const { operation, shouldFail } = context.params;
|
|
427
427
|
|
|
@@ -439,7 +439,7 @@ class RobustProcessor extends A_Component {
|
|
|
439
439
|
|
|
440
440
|
@A_Feature.Extend({ scope: [RobustChannel] })
|
|
441
441
|
async [A_ChannelFeatures.onError](
|
|
442
|
-
@A_Inject(
|
|
442
|
+
@A_Inject(A_ChannelRequest) context: A_ChannelRequest
|
|
443
443
|
) {
|
|
444
444
|
const requestId = JSON.stringify(context.params);
|
|
445
445
|
const currentRetries = this.retryCount.get(requestId) || 0;
|
|
@@ -6,14 +6,14 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { A_Command } from '../src/lib/A-Command/A-Command.entity';
|
|
9
|
-
import {
|
|
9
|
+
import { A_CommandFeatures } from '../src/lib/A-Command/A-Command.constants';
|
|
10
10
|
import { A_Memory } from '../src/lib/A-Memory/A-Memory.context';
|
|
11
|
-
import { A_Component, A_Context, A_Feature, A_Inject, A_Error } from '@adaas/a-concept';
|
|
11
|
+
import { A_Component, A_Context, A_Feature, A_Inject, A_Error, A_Dependency } from '@adaas/a-concept';
|
|
12
12
|
|
|
13
13
|
// Example 1: Basic Command Usage
|
|
14
14
|
async function basicCommandExample() {
|
|
15
15
|
console.log('\n=== Basic Command Example ===');
|
|
16
|
-
|
|
16
|
+
|
|
17
17
|
const command = new A_Command({
|
|
18
18
|
action: 'greet',
|
|
19
19
|
name: 'World'
|
|
@@ -22,8 +22,8 @@ async function basicCommandExample() {
|
|
|
22
22
|
A_Context.root.register(command);
|
|
23
23
|
|
|
24
24
|
// Add event listeners
|
|
25
|
-
command.on(
|
|
26
|
-
command.on(
|
|
25
|
+
command.on(A_CommandFeatures.onInit, () => console.log('Command initializing...'));
|
|
26
|
+
command.on(A_CommandFeatures.onComplete, () => console.log('Command completed!'));
|
|
27
27
|
|
|
28
28
|
await command.execute();
|
|
29
29
|
|
|
@@ -45,38 +45,38 @@ interface UserCreateResult {
|
|
|
45
45
|
profileCreated: boolean;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
class CreateUserCommand extends A_Command<UserCreateParams, UserCreateResult> {}
|
|
48
|
+
class CreateUserCommand extends A_Command<UserCreateParams, UserCreateResult> { }
|
|
49
49
|
|
|
50
50
|
class UserCreationService extends A_Component {
|
|
51
|
-
|
|
51
|
+
|
|
52
52
|
@A_Feature.Extend({ scope: [CreateUserCommand] })
|
|
53
|
-
async [
|
|
53
|
+
async [A_CommandFeatures.onExecute](
|
|
54
54
|
@A_Inject(A_Memory) memory: A_Memory<UserCreateResult>
|
|
55
55
|
) {
|
|
56
|
-
const command = A_Context.scope(this).resolve(CreateUserCommand)
|
|
56
|
+
const command = A_Context.scope(this).resolve(CreateUserCommand)!;
|
|
57
57
|
const { name, email, role } = command.params;
|
|
58
|
-
|
|
58
|
+
|
|
59
59
|
console.log(`Creating user: ${name} (${email}) with role: ${role}`);
|
|
60
|
-
|
|
60
|
+
|
|
61
61
|
// Simulate user creation
|
|
62
62
|
const userId = `user_${Date.now()}`;
|
|
63
63
|
const createdAt = new Date().toISOString();
|
|
64
|
-
|
|
64
|
+
|
|
65
65
|
// Store results in memory
|
|
66
66
|
await memory.set('userId', userId);
|
|
67
67
|
await memory.set('createdAt', createdAt);
|
|
68
68
|
await memory.set('profileCreated', true);
|
|
69
|
-
|
|
69
|
+
|
|
70
70
|
console.log(`User created with ID: ${userId}`);
|
|
71
71
|
}
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
async function typedCommandExample() {
|
|
75
75
|
console.log('\n=== Typed Command with Custom Logic Example ===');
|
|
76
|
-
|
|
76
|
+
|
|
77
77
|
A_Context.reset();
|
|
78
78
|
A_Context.root.register(UserCreationService);
|
|
79
|
-
|
|
79
|
+
|
|
80
80
|
const command = new CreateUserCommand({
|
|
81
81
|
name: 'John Doe',
|
|
82
82
|
email: 'john@example.com',
|
|
@@ -92,10 +92,10 @@ async function typedCommandExample() {
|
|
|
92
92
|
// Example 3: Command Serialization and Persistence
|
|
93
93
|
async function serializationExample() {
|
|
94
94
|
console.log('\n=== Command Serialization Example ===');
|
|
95
|
-
|
|
95
|
+
|
|
96
96
|
A_Context.reset();
|
|
97
97
|
A_Context.root.register(UserCreationService);
|
|
98
|
-
|
|
98
|
+
|
|
99
99
|
// Create and execute original command
|
|
100
100
|
const originalCommand = new CreateUserCommand({
|
|
101
101
|
name: 'Jane Smith',
|
|
@@ -116,7 +116,7 @@ async function serializationExample() {
|
|
|
116
116
|
|
|
117
117
|
// Restore command from serialized data
|
|
118
118
|
const restoredCommand = new CreateUserCommand(parsedData);
|
|
119
|
-
|
|
119
|
+
|
|
120
120
|
console.log('Command restored from serialization:');
|
|
121
121
|
console.log(`- Status: ${restoredCommand.status}`);
|
|
122
122
|
console.log(`- Duration: ${restoredCommand.duration}ms`);
|
|
@@ -125,16 +125,16 @@ async function serializationExample() {
|
|
|
125
125
|
}
|
|
126
126
|
|
|
127
127
|
// Example 4: Error Handling
|
|
128
|
-
class FailingCommand extends A_Command<{ shouldFail: boolean }, { success: boolean }> {}
|
|
128
|
+
class FailingCommand extends A_Command<{ shouldFail: boolean }, { success: boolean }> { }
|
|
129
129
|
|
|
130
130
|
class FailingService extends A_Component {
|
|
131
|
-
|
|
131
|
+
|
|
132
132
|
@A_Feature.Extend({ scope: [FailingCommand] })
|
|
133
|
-
async [
|
|
133
|
+
async [A_CommandFeatures.onExecute](
|
|
134
134
|
@A_Inject(A_Memory) memory: A_Memory<{ success: boolean }>
|
|
135
135
|
) {
|
|
136
|
-
const command = A_Context.scope(this).resolve(FailingCommand)
|
|
137
|
-
|
|
136
|
+
const command = A_Context.scope(this).resolve(FailingCommand)!;
|
|
137
|
+
|
|
138
138
|
if (command.params.shouldFail) {
|
|
139
139
|
// Add error to memory
|
|
140
140
|
await memory.error(new A_Error({
|
|
@@ -142,33 +142,33 @@ class FailingService extends A_Component {
|
|
|
142
142
|
message: 'This command was designed to fail',
|
|
143
143
|
code: 'INTENTIONAL_FAIL'
|
|
144
144
|
}));
|
|
145
|
-
|
|
145
|
+
|
|
146
146
|
throw new Error('Command failed as requested');
|
|
147
147
|
}
|
|
148
|
-
|
|
148
|
+
|
|
149
149
|
await memory.set('success', true);
|
|
150
150
|
}
|
|
151
151
|
}
|
|
152
152
|
|
|
153
153
|
async function errorHandlingExample() {
|
|
154
154
|
console.log('\n=== Error Handling Example ===');
|
|
155
|
-
|
|
155
|
+
|
|
156
156
|
A_Context.reset();
|
|
157
157
|
A_Context.root.register(FailingService);
|
|
158
|
-
|
|
158
|
+
|
|
159
159
|
// Test successful command
|
|
160
160
|
const successCommand = new FailingCommand({ shouldFail: false });
|
|
161
161
|
A_Context.root.register(successCommand);
|
|
162
162
|
await successCommand.execute();
|
|
163
|
-
|
|
163
|
+
|
|
164
164
|
console.log(`Success command - Status: ${successCommand.status}`);
|
|
165
165
|
console.log(`Success command - Result:`, successCommand.result);
|
|
166
|
-
|
|
166
|
+
|
|
167
167
|
// Test failing command
|
|
168
168
|
const failCommand = new FailingCommand({ shouldFail: true });
|
|
169
169
|
A_Context.root.register(failCommand);
|
|
170
170
|
await failCommand.execute();
|
|
171
|
-
|
|
171
|
+
|
|
172
172
|
console.log(`Fail command - Status: ${failCommand.status}`);
|
|
173
173
|
console.log(`Fail command - Is Failed: ${failCommand.isFailed}`);
|
|
174
174
|
console.log(`Fail command - Errors:`, Array.from(failCommand.errors?.values() || []));
|
|
@@ -181,30 +181,32 @@ class FileProcessCommand extends A_Command<
|
|
|
181
181
|
{ filePath: string; operation: string },
|
|
182
182
|
{ outputPath: string; size: number },
|
|
183
183
|
FileProcessEvents
|
|
184
|
-
> {}
|
|
184
|
+
> { }
|
|
185
185
|
|
|
186
186
|
class FileProcessor extends A_Component {
|
|
187
|
-
|
|
187
|
+
|
|
188
188
|
@A_Feature.Extend({ scope: [FileProcessCommand] })
|
|
189
|
-
async [
|
|
190
|
-
@A_Inject(A_Memory) memory: A_Memory<{ outputPath: string; size: number }
|
|
189
|
+
async [A_CommandFeatures.onExecute](
|
|
190
|
+
@A_Inject(A_Memory) memory: A_Memory<{ outputPath: string; size: number }>,
|
|
191
|
+
|
|
192
|
+
@A_Dependency.Required()
|
|
193
|
+
@A_Inject(FileProcessCommand) command: FileProcessCommand
|
|
191
194
|
) {
|
|
192
|
-
const command = A_Context.scope(this).resolve(FileProcessCommand);
|
|
193
195
|
const { filePath, operation } = command.params;
|
|
194
|
-
|
|
196
|
+
|
|
195
197
|
// Emit custom events during processing
|
|
196
198
|
command.emit('validation-started');
|
|
197
199
|
console.log(`Validating file: ${filePath}`);
|
|
198
200
|
await new Promise(resolve => setTimeout(resolve, 100));
|
|
199
|
-
|
|
201
|
+
|
|
200
202
|
command.emit('processing');
|
|
201
203
|
console.log(`Processing file with operation: ${operation}`);
|
|
202
204
|
await new Promise(resolve => setTimeout(resolve, 200));
|
|
203
|
-
|
|
205
|
+
|
|
204
206
|
command.emit('cleanup');
|
|
205
207
|
console.log('Cleaning up temporary files');
|
|
206
208
|
await new Promise(resolve => setTimeout(resolve, 50));
|
|
207
|
-
|
|
209
|
+
|
|
208
210
|
await memory.set('outputPath', `processed_${filePath}`);
|
|
209
211
|
await memory.set('size', 1024);
|
|
210
212
|
}
|
|
@@ -212,10 +214,10 @@ class FileProcessor extends A_Component {
|
|
|
212
214
|
|
|
213
215
|
async function customEventsExample() {
|
|
214
216
|
console.log('\n=== Custom Events Example ===');
|
|
215
|
-
|
|
217
|
+
|
|
216
218
|
A_Context.reset();
|
|
217
219
|
A_Context.root.register(FileProcessor);
|
|
218
|
-
|
|
220
|
+
|
|
219
221
|
const command = new FileProcessCommand({
|
|
220
222
|
filePath: 'document.pdf',
|
|
221
223
|
operation: 'compress'
|
|
@@ -225,9 +227,9 @@ async function customEventsExample() {
|
|
|
225
227
|
command.on('validation-started', () => console.log('📋 Validation phase started'));
|
|
226
228
|
command.on('processing', () => console.log('⚙️ Processing phase started'));
|
|
227
229
|
command.on('cleanup', () => console.log('🧹 Cleanup phase started'));
|
|
228
|
-
|
|
230
|
+
|
|
229
231
|
// Subscribe to lifecycle events
|
|
230
|
-
command.on('
|
|
232
|
+
command.on('onComplete', () => console.log('✅ File processing completed'));
|
|
231
233
|
|
|
232
234
|
A_Context.root.register(command);
|
|
233
235
|
await command.execute();
|
|
@@ -238,14 +240,14 @@ async function customEventsExample() {
|
|
|
238
240
|
// Run all examples
|
|
239
241
|
async function runAllExamples() {
|
|
240
242
|
console.log('🚀 Running A-Command Examples\n');
|
|
241
|
-
|
|
243
|
+
|
|
242
244
|
try {
|
|
243
245
|
await basicCommandExample();
|
|
244
246
|
await typedCommandExample();
|
|
245
247
|
await serializationExample();
|
|
246
248
|
await errorHandlingExample();
|
|
247
249
|
await customEventsExample();
|
|
248
|
-
|
|
250
|
+
|
|
249
251
|
console.log('\n✅ All examples completed successfully!');
|
|
250
252
|
} catch (error) {
|
|
251
253
|
console.error('\n❌ Example failed:', error);
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A-Logger Component Examples
|
|
3
|
+
*
|
|
4
|
+
* This file demonstrates various usage patterns and features of the A_Logger component.
|
|
5
|
+
* These examples show the logging capabilities without complex dependency injection.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { A_Scope, A_Error } from "@adaas/a-concept";
|
|
9
|
+
import { A_Logger } from "../src/lib/A-Logger/A-Logger.component";
|
|
10
|
+
|
|
11
|
+
// =============================================
|
|
12
|
+
// Basic Logging Examples
|
|
13
|
+
// =============================================
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Example 1: Basic Logger Usage
|
|
17
|
+
*/
|
|
18
|
+
function basicLogging() {
|
|
19
|
+
console.log('\n=== Example 1: Basic Logger Usage ===\n');
|
|
20
|
+
|
|
21
|
+
const scope = new A_Scope({ name: 'API-Service' });
|
|
22
|
+
const logger = new A_Logger(scope);
|
|
23
|
+
|
|
24
|
+
// Different log types
|
|
25
|
+
logger.log('Logger initialized successfully');
|
|
26
|
+
logger.log('green', 'This is a success message');
|
|
27
|
+
logger.log('blue', 'This is an info message');
|
|
28
|
+
logger.warning('This is a warning message');
|
|
29
|
+
logger.error('This is an error message');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Example 2: Scope Length Alignment Demonstration
|
|
34
|
+
*/
|
|
35
|
+
function scopeLengthDemo() {
|
|
36
|
+
console.log('\n=== Example 2: Scope Length Alignment ===\n');
|
|
37
|
+
|
|
38
|
+
const scopes = [
|
|
39
|
+
{ name: 'DB' },
|
|
40
|
+
{ name: 'Authentication' },
|
|
41
|
+
{ name: 'WebSocketManager' },
|
|
42
|
+
{ name: 'A' },
|
|
43
|
+
{ name: 'VeryLongServiceNameExample' }
|
|
44
|
+
];
|
|
45
|
+
|
|
46
|
+
scopes.forEach(scopeConfig => {
|
|
47
|
+
const scope = new A_Scope(scopeConfig);
|
|
48
|
+
const logger = new A_Logger(scope);
|
|
49
|
+
logger.log('green', `Message from ${scopeConfig.name}`);
|
|
50
|
+
logger.warning('Warning message to show alignment');
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Example 3: Object and Data Logging
|
|
56
|
+
*/
|
|
57
|
+
function objectLogging() {
|
|
58
|
+
console.log('\n=== Example 3: Object and Data Logging ===\n');
|
|
59
|
+
|
|
60
|
+
const scope = new A_Scope({ name: 'DataLogger' });
|
|
61
|
+
const logger = new A_Logger(scope);
|
|
62
|
+
|
|
63
|
+
// Simple object
|
|
64
|
+
const userObject = {
|
|
65
|
+
id: 1,
|
|
66
|
+
name: 'John Doe',
|
|
67
|
+
email: 'john@example.com',
|
|
68
|
+
preferences: {
|
|
69
|
+
theme: 'dark',
|
|
70
|
+
notifications: true
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
logger.log('blue', 'User object:', userObject);
|
|
74
|
+
|
|
75
|
+
// Array logging
|
|
76
|
+
const dataArray = [
|
|
77
|
+
{ id: 1, name: 'Item 1' },
|
|
78
|
+
{ id: 2, name: 'Item 2' },
|
|
79
|
+
{ id: 3, name: 'Item 3' }
|
|
80
|
+
];
|
|
81
|
+
logger.log('magenta', 'Data array:', dataArray);
|
|
82
|
+
|
|
83
|
+
// Multi-argument logging
|
|
84
|
+
logger.log('green',
|
|
85
|
+
'Processing complete:',
|
|
86
|
+
'Records processed:', 150,
|
|
87
|
+
'Errors:', 2,
|
|
88
|
+
'Success rate:', '98.7%'
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Example 4: Error Logging
|
|
94
|
+
*/
|
|
95
|
+
function errorLogging() {
|
|
96
|
+
console.log('\n=== Example 4: Error Logging ===\n');
|
|
97
|
+
|
|
98
|
+
const scope = new A_Scope({ name: 'ErrorHandler' });
|
|
99
|
+
const logger = new A_Logger(scope);
|
|
100
|
+
|
|
101
|
+
// Standard JavaScript Error
|
|
102
|
+
try {
|
|
103
|
+
throw new Error('Database connection timeout');
|
|
104
|
+
} catch (error) {
|
|
105
|
+
logger.error('Database error occurred:', error);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Simple A_Error
|
|
109
|
+
const validationError = new A_Error('User input validation failed');
|
|
110
|
+
logger.error('Validation error:', validationError);
|
|
111
|
+
|
|
112
|
+
// Error with context
|
|
113
|
+
const operationContext = {
|
|
114
|
+
userId: 'user-12345',
|
|
115
|
+
operation: 'profile-update',
|
|
116
|
+
timestamp: new Date().toISOString(),
|
|
117
|
+
requestId: 'req-abc123'
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
try {
|
|
121
|
+
throw new Error('Profile update failed: Invalid user permissions');
|
|
122
|
+
} catch (error) {
|
|
123
|
+
logger.error(
|
|
124
|
+
'Operation failed with context:',
|
|
125
|
+
error,
|
|
126
|
+
'Context:', operationContext,
|
|
127
|
+
'Additional info:', 'User may need admin privileges'
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Example 5: Different Colors and Formatting
|
|
134
|
+
*/
|
|
135
|
+
function colorDemo() {
|
|
136
|
+
console.log('\n=== Example 5: Color Demonstration ===\n');
|
|
137
|
+
|
|
138
|
+
const scope = new A_Scope({ name: 'ColorDemo' });
|
|
139
|
+
const logger = new A_Logger(scope);
|
|
140
|
+
|
|
141
|
+
// All available colors
|
|
142
|
+
const colors = ['green', 'blue', 'red', 'yellow', 'gray', 'magenta', 'cyan', 'white', 'pink'] as const;
|
|
143
|
+
|
|
144
|
+
colors.forEach(color => {
|
|
145
|
+
logger.log(color, `This is a ${color} colored message`);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Example 6: Performance Logging Simulation
|
|
151
|
+
*/
|
|
152
|
+
async function performanceLogging() {
|
|
153
|
+
console.log('\n=== Example 6: Performance Logging ===\n');
|
|
154
|
+
|
|
155
|
+
const scope = new A_Scope({ name: 'PerformanceMonitor' });
|
|
156
|
+
const logger = new A_Logger(scope);
|
|
157
|
+
|
|
158
|
+
const operations = ['Database Query', 'API Call', 'File Processing', 'Data Validation'];
|
|
159
|
+
|
|
160
|
+
for (const operation of operations) {
|
|
161
|
+
const startTime = Date.now();
|
|
162
|
+
|
|
163
|
+
// Simulate work with random delay
|
|
164
|
+
await new Promise(resolve => setTimeout(resolve, Math.random() * 200 + 50));
|
|
165
|
+
|
|
166
|
+
const duration = Date.now() - startTime;
|
|
167
|
+
const status = duration < 100 ? 'green' : duration < 150 ? 'yellow' : 'red';
|
|
168
|
+
|
|
169
|
+
logger.log(status, `${operation} completed:`, {
|
|
170
|
+
operation,
|
|
171
|
+
duration: `${duration}ms`,
|
|
172
|
+
status: duration < 100 ? 'fast' : duration < 150 ? 'normal' : 'slow',
|
|
173
|
+
timestamp: new Date().toISOString()
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Example 7: Real-world Service Logging
|
|
180
|
+
*/
|
|
181
|
+
async function serviceLogging() {
|
|
182
|
+
console.log('\n=== Example 7: Service Logging Simulation ===\n');
|
|
183
|
+
|
|
184
|
+
// Create different service loggers
|
|
185
|
+
const services = {
|
|
186
|
+
api: new A_Logger(new A_Scope({ name: 'API-Gateway' })),
|
|
187
|
+
auth: new A_Logger(new A_Scope({ name: 'Auth' })),
|
|
188
|
+
db: new A_Logger(new A_Scope({ name: 'DatabasePool' })),
|
|
189
|
+
cache: new A_Logger(new A_Scope({ name: 'Redis-Cache' }))
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
// Simulate user registration flow
|
|
193
|
+
const userId = 'user-' + Math.random().toString(36).substr(2, 9);
|
|
194
|
+
|
|
195
|
+
services.api.log('green', 'Registration request received:', {
|
|
196
|
+
endpoint: '/api/auth/register',
|
|
197
|
+
userId,
|
|
198
|
+
timestamp: new Date().toISOString()
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
services.auth.log('blue', 'Validating user credentials...');
|
|
202
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
203
|
+
services.auth.log('green', 'Credentials validated successfully');
|
|
204
|
+
|
|
205
|
+
services.db.log('blue', 'Creating user record...');
|
|
206
|
+
await new Promise(resolve => setTimeout(resolve, 100));
|
|
207
|
+
services.db.log('green', 'User record created:', { userId, table: 'users' });
|
|
208
|
+
|
|
209
|
+
services.cache.log('blue', 'Caching user session...');
|
|
210
|
+
await new Promise(resolve => setTimeout(resolve, 30));
|
|
211
|
+
services.cache.log('green', 'Session cached:', { userId, ttl: 3600 });
|
|
212
|
+
|
|
213
|
+
services.api.log('green', 'Registration completed successfully:', {
|
|
214
|
+
userId,
|
|
215
|
+
totalTime: '180ms',
|
|
216
|
+
status: 'success'
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Example 8: Complex Object Logging
|
|
222
|
+
*/
|
|
223
|
+
function complexObjectLogging() {
|
|
224
|
+
console.log('\n=== Example 8: Complex Object Logging ===\n');
|
|
225
|
+
|
|
226
|
+
const scope = new A_Scope({ name: 'ComplexLogger' });
|
|
227
|
+
const logger = new A_Logger(scope);
|
|
228
|
+
|
|
229
|
+
const complexObject = {
|
|
230
|
+
request: {
|
|
231
|
+
method: 'POST',
|
|
232
|
+
url: '/api/users',
|
|
233
|
+
headers: {
|
|
234
|
+
'Content-Type': 'application/json',
|
|
235
|
+
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
|
|
236
|
+
'User-Agent': 'Mozilla/5.0 (compatible; ADAAS-Client/1.0)'
|
|
237
|
+
},
|
|
238
|
+
body: {
|
|
239
|
+
name: 'Jane Smith',
|
|
240
|
+
email: 'jane@example.com',
|
|
241
|
+
metadata: {
|
|
242
|
+
source: 'web-form',
|
|
243
|
+
campaign: 'summer-2024'
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
response: {
|
|
248
|
+
status: 201,
|
|
249
|
+
data: {
|
|
250
|
+
id: 'user-12345',
|
|
251
|
+
created: '2024-10-29T10:30:00Z'
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
timing: {
|
|
255
|
+
start: 1698574200000,
|
|
256
|
+
end: 1698574200250,
|
|
257
|
+
duration: 250
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
logger.log('blue', 'API Request Complete:', complexObject);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// =============================================
|
|
265
|
+
// Main Execution
|
|
266
|
+
// =============================================
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Run all examples
|
|
270
|
+
*/
|
|
271
|
+
async function runAllExamples() {
|
|
272
|
+
console.log('🚀 A-Logger Component Examples');
|
|
273
|
+
console.log('==============================\n');
|
|
274
|
+
|
|
275
|
+
try {
|
|
276
|
+
basicLogging();
|
|
277
|
+
scopeLengthDemo();
|
|
278
|
+
objectLogging();
|
|
279
|
+
errorLogging();
|
|
280
|
+
colorDemo();
|
|
281
|
+
await performanceLogging();
|
|
282
|
+
await serviceLogging();
|
|
283
|
+
complexObjectLogging();
|
|
284
|
+
|
|
285
|
+
console.log('\n✅ All examples completed successfully!');
|
|
286
|
+
|
|
287
|
+
} catch (error) {
|
|
288
|
+
console.error('\n❌ Example execution failed:', error);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// Export functions for individual testing
|
|
293
|
+
export {
|
|
294
|
+
basicLogging,
|
|
295
|
+
scopeLengthDemo,
|
|
296
|
+
objectLogging,
|
|
297
|
+
errorLogging,
|
|
298
|
+
colorDemo,
|
|
299
|
+
performanceLogging,
|
|
300
|
+
serviceLogging,
|
|
301
|
+
complexObjectLogging,
|
|
302
|
+
runAllExamples
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
// Run examples if this file is executed directly
|
|
306
|
+
if (require.main === module) {
|
|
307
|
+
runAllExamples();
|
|
308
|
+
}
|
package/examples/config.ts
CHANGED
|
@@ -26,7 +26,7 @@ import { A_Polyfill } from "@adaas/a-utils/lib/A-Polyfill/A-Polyfill.component";
|
|
|
26
26
|
await concept.start();
|
|
27
27
|
|
|
28
28
|
|
|
29
|
-
const config = service1.scope.resolve<A_Config<['ADAAS_SSO_LOCATION']>>(A_Config)
|
|
29
|
+
const config = service1.scope.resolve<A_Config<['ADAAS_SSO_LOCATION']>>(A_Config)!;
|
|
30
30
|
|
|
31
31
|
console.log('config: ', config.get('ADAAS_SSO_LOCATION'))
|
|
32
32
|
|