-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.js
More file actions
445 lines (383 loc) · 8.72 KB
/
Copy pathdemo.js
File metadata and controls
445 lines (383 loc) · 8.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
/**
* RailJS Demo - Complete working example
* Shows modules communicating through events only
*/
// Import the Rail (adjust for your environment)
import { Rail } from './rail.js';
// OR for Node.js: const { Rail } = require('./rail.js');
// Create the main rail
const rail = new Rail({
name: 'demo-app',
debug: true,
});
// ===== AUTH MODULE =====
const authModule = {
name: 'auth',
users: new Map([
['demo@example.com', { password: 'demo123', id: 1, name: 'Demo User' }],
[
'admin@example.com',
{ password: 'admin456', id: 2, name: 'Admin User' },
],
]),
connect(rail) {
// Handle login attempts
rail.on(
'user.login',
(data) => {
console.log('🔐 Auth: Processing login attempt...');
const { email, password } = data;
const user = this.users.get(email);
// Simulate async validation
setTimeout(() => {
if (user && user.password === password) {
rail.emit('auth.success', {
token: `jwt-${Date.now()}`,
user: { id: user.id, email, name: user.name },
});
} else {
rail.emit('auth.failed', {
email,
error: 'Invalid email or password',
});
}
}, 100);
},
'auth'
);
// Handle logout
rail.on(
'user.logout',
(data) => {
console.log('🚪 Auth: Processing logout...');
rail.emit('auth.logout.success', { userId: data.userId });
},
'auth'
);
// Handle registration
rail.on(
'user.register',
(data) => {
console.log('📝 Auth: Processing registration...');
const { email, password, name } = data;
if (this.users.has(email)) {
rail.emit('auth.registration.failed', {
email,
error: 'Email already exists',
});
} else {
const newUser = {
id: this.users.size + 1,
password,
name,
};
this.users.set(email, newUser);
rail.emit('auth.registration.success', {
user: { id: newUser.id, email, name },
});
}
},
'auth'
);
},
};
// ===== DATABASE MODULE =====
const databaseModule = {
name: 'database',
sessions: new Map(),
loginHistory: [],
connect(rail) {
// Save successful login sessions
rail.on(
'auth.success',
(data) => {
console.log('💾 Database: Saving login session...');
const sessionId = `session-${Date.now()}`;
this.sessions.set(sessionId, {
userId: data.user.id,
token: data.token,
createdAt: new Date(),
lastActivity: new Date(),
});
this.loginHistory.push({
userId: data.user.id,
email: data.user.email,
loginTime: new Date(),
sessionId,
});
rail.emit('database.session.created', {
sessionId,
userId: data.user.id,
});
},
'database'
);
// Clean up sessions on logout
rail.on(
'auth.logout.success',
(data) => {
console.log('🗑️ Database: Cleaning up session...');
// Find and remove session
for (const [sessionId, session] of this.sessions) {
if (session.userId === data.userId) {
this.sessions.delete(sessionId);
rail.emit('database.session.removed', { sessionId });
break;
}
}
},
'database'
);
// Handle data queries
rail.on(
'data.get.sessions',
() => {
rail.emit('data.sessions', {
active: this.sessions.size,
history: this.loginHistory.slice(-5), // Last 5 logins
});
},
'database'
);
},
};
// ===== EMAIL MODULE =====
const emailModule = {
name: 'email',
sentEmails: [],
connect(rail) {
// Send welcome email on successful login
rail.on(
'auth.success',
(data) => {
console.log('📧 Email: Sending welcome email...');
const email = {
to: data.user.email,
subject: 'Welcome back!',
type: 'welcome',
sentAt: new Date(),
};
this.sentEmails.push(email);
rail.emit('email.sent', {
to: data.user.email,
type: 'welcome',
messageId: `msg-${Date.now()}`,
});
},
'email'
);
// Send registration confirmation
rail.on(
'auth.registration.success',
(data) => {
console.log('📧 Email: Sending registration confirmation...');
const email = {
to: data.user.email,
subject: 'Welcome to RailJS Demo!',
type: 'registration',
sentAt: new Date(),
};
this.sentEmails.push(email);
rail.emit('email.sent', {
to: data.user.email,
type: 'registration',
messageId: `msg-${Date.now()}`,
});
},
'email'
);
// Get email history
rail.on(
'email.get.history',
() => {
rail.emit('email.history', {
emails: this.sentEmails.slice(-10), // Last 10 emails
});
},
'email'
);
},
};
// ===== LOGGER MODULE =====
const loggerModule = {
name: 'logger',
logs: [],
connect(rail) {
// Log all authentication events
rail.on(
'auth.success',
(data) => {
this.log('LOGIN_SUCCESS', `User ${data.user.email} logged in`);
},
'logger'
);
rail.on(
'auth.failed',
(data) => {
this.log(
'LOGIN_FAILED',
`Failed login attempt for ${data.email}: ${data.error}`
);
},
'logger'
);
rail.on(
'auth.registration.success',
(data) => {
this.log(
'REGISTRATION_SUCCESS',
`New user registered: ${data.user.email}`
);
},
'logger'
);
// Log email events
rail.on(
'email.sent',
(data) => {
this.log('EMAIL_SENT', `${data.type} email sent to ${data.to}`);
},
'logger'
);
// Log system events
rail.on(
'rail.module.attached',
(data) => {
this.log('SYSTEM', `Module ${data.moduleName} attached`);
},
'logger'
);
rail.on(
'rail.module.detached',
(data) => {
this.log('SYSTEM', `Module ${data.moduleName} detached`);
},
'logger'
);
// Handle log queries
rail.on(
'logs.get',
(data) => {
const limit = data.limit || 20;
rail.emit('logs.data', {
logs: this.logs.slice(-limit),
});
},
'logger'
);
},
log(level, message) {
const entry = {
timestamp: new Date(),
level,
message,
id: this.logs.length + 1,
};
this.logs.push(entry);
console.log(`📝 Logger: [${level}] ${message}`);
},
};
// ===== NOTIFICATION MODULE =====
const notificationModule = {
name: 'notifications',
connect(rail) {
// Show success notifications
rail.on(
'auth.success',
(data) => {
this.notify('success', `Welcome back, ${data.user.name}!`);
},
'notifications'
);
rail.on(
'email.sent',
(data) => {
this.notify('info', `${data.type} email sent`);
},
'notifications'
);
// Show error notifications
rail.on(
'auth.failed',
(data) => {
this.notify('error', `Login failed: ${data.error}`);
},
'notifications'
);
},
notify(type, message) {
const notification = {
type,
message,
timestamp: new Date(),
id: Date.now(),
};
console.log(`🔔 Notification [${type.toUpperCase()}]: ${message}`);
rail.emit('notification.shown', notification);
},
};
// ===== ATTACH ALL MODULES =====
console.log('🚂 Starting RailJS Demo Application...\n');
rail.attach(authModule);
rail.attach(databaseModule);
rail.attach(emailModule);
rail.attach(loggerModule);
rail.attach(notificationModule);
console.log('\n' + '='.repeat(50));
console.log('🎯 DEMO: Testing successful login');
console.log('='.repeat(50));
rail.emit('user.login', {
email: 'demo@example.com',
password: 'demo123',
});
// Test failed login after a delay
setTimeout(() => {
console.log('\n' + '='.repeat(50));
console.log('🎯 DEMO: Testing failed login');
console.log('='.repeat(50));
rail.emit('user.login', {
email: 'wrong@example.com',
password: 'wrongpass',
});
}, 500);
// Test registration after another delay
setTimeout(() => {
console.log('\n' + '='.repeat(50));
console.log('🎯 DEMO: Testing user registration');
console.log('='.repeat(50));
rail.emit('user.register', {
email: 'newuser@example.com',
password: 'newpass123',
name: 'New User',
});
}, 1000);
// Test module detachment after everything
setTimeout(() => {
console.log('\n' + '='.repeat(50));
console.log('🎯 DEMO: Testing module detachment');
console.log('='.repeat(50));
console.log('Detaching email module...');
rail.detach('email');
console.log('\nTrying login without email module:');
rail.emit('user.login', {
email: 'demo@example.com',
password: 'demo123',
});
}, 1500);
// Show stats at the end
setTimeout(() => {
console.log('\n' + '='.repeat(50));
console.log('📊 FINAL STATS');
console.log('='.repeat(50));
const stats = rail.getStats();
console.log('Rail Stats:', stats);
console.log('Active Modules:', rail.getModules());
console.log('Event Listeners:', rail.getEvents());
// Get some data
rail.emit('data.get.sessions');
rail.emit('logs.get', { limit: 5 });
}, 2000);
// Export for testing
if (typeof module !== 'undefined' && module.exports) {
module.exports = { rail, authModule, databaseModule, emailModule };
}