Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-3-5-sonnet-20241022· AnthropicHugging Face LMArena Human Preference 140K

Create a typescript nodejs bet system example, with redis connection, queues, etc

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with gpt-4o-mini-2024-07-18’s answer.
  1. User

    Create a typescript nodejs bet system example, with redis connection, queues, etc

  2. Claude Assistant

    Here's an example of a TypeScript Node.js betting system with Redis, queues, and basic functionality:

    First, let's set up the project structure:

    betting-system/
    ├── src/
    │   ├── config/
    │   │   └── redis.ts
    │   ├── models/
    │   │   ├── Bet.ts
    │   │   └── User.ts
    │   ├── services/
    │   │   ├── BetService.ts
    │   │   └── QueueService.ts
    │   ├── controllers/
    │   │   └── BetController.ts
    │   ├── routes/
    │   │   └── betRoutes.ts
    │   └── app.ts
    ├── package.json
    └── tsconfig.json
    

    First, install the required dependencies:

    npm init -y
    npm install express redis bull typescript @types/express @types/node @types/redis dotenv
    

    Here's the implementation of each file:

    1. src/config/redis.ts:
    import Redis from 'redis';
    import { promisify } from 'util';
    
    const redisClient = Redis.createClient({
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT || '6379'),
    });
    
    redisClient.on('error', (error) => {
      console.error('Redis Error:', error);
    });
    
    export const getAsync = promisify(redisClient.get).bind(redisClient);
    export const setAsync = promisify(redisClient.set).bind(redisClient);
    
    export default redisClient;
    
    1. src/models/Bet.ts:
    export interface Bet {
      id: string;
      userId: string;
      amount: number;
      odds: number;
      status: 'PENDING' | 'WON' | 'LOST';
      createdAt: Date;
      settledAt?: Date;
    }
    
    1. src/models/User.ts:
    export interface User {
      id: string;
      balance: number;
      username: string;
    }
    
    1. src/services/QueueService.ts:
    import Queue from 'bull';
    import { Bet } from '../models/Bet';
    
    export class QueueService {
      private betProcessingQueue: Queue.Queue;
    
      constructor() {
        this.betProcessingQueue = new Queue('bet-processing', {
          redis: {
            host: process.env.REDIS_HOST || 'localhost',
            port: parseInt(process.env.REDIS_PORT || '6379'),
          },
        });
    
        this.setupQueueHandlers();
      }
    
      private setupQueueHandlers() {
        this.betProcessingQueue.process(async (job) => {
          const bet: Bet = job.data;
          // Simulate bet processing
          await this.processBet(bet);
        });
      }
    
      private async processBet(bet: Bet): Promise<void> {
        // Simulate random outcome
        const won = Math.random() > 0.5;
        
        bet.status = won ? 'WON' : 'LOST';
        bet.settledAt = new Date();
    
        // Update bet in database/cache
        // Update user balance
        console.log(`Bet ${bet.id} processed: ${bet.status}`);
      }
    
      public async addBetToQueue(bet: Bet): Promise<void> {
        await this.betProcessingQueue.add(bet);
      }
    }
    
    export const queueService = new QueueService();
    
    1. src/services/BetService.ts:
    import { v4 as uuidv4 } from 'uuid';
    import { Bet } from '../models/Bet';
    import { queueService } from './QueueService';
    import { getAsync, setAsync } from '../config/redis';
    
    export class BetService {
      async createBet(userId: string, amount: number, odds: number): Promise<Bet> {
        // Validate user balance, odds, etc.
    
        const bet: Bet = {
          id: uuidv4(),
          userId,
          amount,
          odds,
          status: 'PENDING',
          createdAt: new Date(),
        };
    
        // Store bet in Redis
        await setAsync(`bet:${bet.id}`, JSON.stringify(bet));
    
        // Add to processing queue
        await queueService.addBetToQueue(bet);
    
        return bet;
      }
    
      async getBet(betId: string): Promise<Bet | null> {
        const betData = await getAsync(`bet:${betId}`);
        return betData ? JSON.parse(betData) : null;
      }
    }
    
    export const betService = new BetService();
    
    1. src/controllers/BetController.ts:
    import { Request, Response } from 'express';
    import { betService } from '../services/BetService';
    
    export class BetController {
      async createBet(req: Request, res: Response) {
        try {
          const { userId, amount, odds } = req.body;
          const bet = await betService.createBet(userId, amount, odds);
          res.json(bet);
        } catch (error) {
          res.status(500).json({ error: 'Failed to create bet' });
        }
      }
    
      async getBet(req: Request, res: Response) {
        try {
          const { betId } = req.params;
          const bet = await betService.getBet(betId);
          
          if (!bet) {
            return res.status(404).json({ error: 'Bet not found' });
          }
    
          res.json(bet);
        } catch (error) {
          res.status(500).json({ error: 'Failed to get bet' });
        }
      }
    }
    
    export const betController = new BetController();
    
    1. src/routes/betRoutes.ts:
    import { Router } from 'express';
    import { betController } from '../controllers/BetController';
    
    const router = Router();
    
    router.post('/bets', betController.createBet);
    router.get('/bets/:betId', betController.getBet);
    
    export default router;
    
    1. src/app.ts:
    import express from 'express';
    import dotenv from 'dotenv';
    import betRoutes from './routes/betRoutes';
    
    dotenv.config();
    
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    app.use(express.json());
    app.use('/api', betRoutes);
    
    app.listen(PORT, () => {
      console.log(`Server running on port ${PORT}`);
    });
    
    1. tsconfig.json:
    {
      "compilerOptions": {
        "target": "es2018",
        "module": "commonjs",
        "outDir": "./dist",
        "rootDir": "./src",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules"]
    }
    

    This example implements a basic betting system with the following features:

    1. Redis connection for caching bet data
    2. Bull queue for processing bets asynchronously
    3. Basic API endpoints for creating and retrieving bets
    4. TypeScript interfaces for type safety
    5. Service layer for business logic
    6. Controller layer for handling HTTP requests
    7. Basic error handling

    To use this system:

    1. Make sure Redis is running on your machine
    2. Create a .env file with your configuration
    3. Run npm run build to compile TypeScript
    4. Run npm start to start the server

    You can then create a bet using:

    curl -X POST http://localhost:3000/api/bets \
      -H "Content-Type: application/json" \
      -d '{"userId": "user123", "amount": 100, "odds": 2.0}'
    

    And retrieve a bet using:

    curl http://localhost:3000/api/bets/{betId}
    

    This is a basic implementation that you can extend with:

    • User authentication
    • Database integration (e.g., PostgreSQL)
    • More sophisticated bet processing logic
    • Websocket notifications for bet status updates
    • Rate limiting
    • Input validation
    • Testing
    • Error logging
    • Monitoring and metrics

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.