/ examples / js / databases / redis-example.ts
redis-example.ts
 1  /**
 2   * Redis Database Example
 3   */
 4  
 5  import { createMemoryRedis } from '../../../src/praisonai-ts/src';
 6  
 7  async function main() {
 8    // Use in-memory Redis for this example
 9    const redis = createMemoryRedis();
10    await redis.connect();
11  
12    console.log('Connected to Redis');
13  
14    // Basic get/set
15    await redis.set('user:123', { name: 'John', role: 'admin' });
16    const user = await redis.get('user:123');
17    console.log('User:', user);
18  
19    // Set with TTL
20    await redis.set('session:abc', { token: 'xyz' }, 60);
21    const ttl = await redis.ttl('session:abc');
22    console.log('Session TTL:', ttl, 'seconds');
23  
24    // Hash operations
25    await redis.hset('profile:123', 'email', 'john@example.com');
26    await redis.hset('profile:123', 'phone', '555-1234');
27    const profile = await redis.hgetall('profile:123');
28    console.log('Profile:', profile);
29  
30    // List operations
31    await redis.rpush('queue:tasks', { id: 1, type: 'process' });
32    await redis.rpush('queue:tasks', { id: 2, type: 'notify' });
33    const tasks = await redis.lrange('queue:tasks', 0, -1);
34    console.log('Tasks:', tasks);
35  
36    // Pub/Sub (memory only)
37    await redis.subscribe('events', (message) => {
38      console.log('Received event:', message);
39    });
40    await redis.publish('events', JSON.stringify({ type: 'user_joined' }));
41  
42    // Cleanup
43    await redis.disconnect();
44    console.log('Done!');
45  }
46  
47  main().catch(console.error);