Creating a simple betting system using TypeScript, Node.js, and Redis involves several components. Below is a basic example that demonstrates how to set up a betting system with a Redis connection and a queue for processing bets.
Prerequisites
- Node.js: Make sure you have Node.js installed on your machine.
- Redis: You need to have Redis installed and running. You can use Docker to run Redis easily.
- TypeScript: You should have TypeScript installed globally or as a project dependency.
Project Setup
-
Initialize a new Node.js project:
mkdir betting-system
cd betting-system
npm init -y
-
Install required packages:
npm install express ioredis bull @types/express typescript ts-node
-
Initialize TypeScript:
npx tsc --init
-
Create the following directory structure:
betting-system/
├── src/
│ ├── index.ts
│ ├── betController.ts
│ ├── betQueue.ts
├── tsconfig.json
└── package.json
Code Implementation
1. src/index.ts
This file will set up the Express server and connect to Redis.
import express from 'express';
import { BetQueue } from './betQueue';
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
const betQueue = new BetQueue();
// Endpoint to place a bet
app.post('/bet', async (req, res) => {
const { userId, amount, gameId } = req.body;
if (!userId || !amount || !gameId) {
return res.status(400).json({ error: 'Missing required fields' });
}
// Add the bet to the queue
await betQueue.addBet({ userId, amount, gameId });
res.status(201).json({ message: 'Bet placed successfully' });
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
2. src/betQueue.ts
This file will handle the Redis connection and the Bull queue for processing bets.
import { Queue, Worker } from 'bull';
import Redis from 'ioredis';
interface Bet {
userId: string;
amount: number;
gameId: string;
}
export class BetQueue {
private queue: Queue<Bet>;
private redisClient: Redis.Redis;
constructor() {
this.redisClient = new Redis();
this.queue = new Queue<Bet>('betQueue', { redis: { host: 'localhost', port: 6379 } });
// Process bets from the queue
this.processBets();
}
async addBet(bet: Bet) {
await this.queue.add(bet);
}
private processBets() {
const worker = new Worker<Bet>('betQueue', async (job) => {
const { userId, amount, gameId } = job.data;
// Simulate processing the bet (e.g., saving to a database)
console.log(`Processing bet for user ${userId}: Amount ${amount} on game ${gameId}`);
// Simulate a delay
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log(`Bet processed for user ${userId}`);
});
worker.on('completed', (job) => {
console.log(`Job completed: ${job.id}`);
});
worker.on('failed', (job, err) => {
console.error(`Job failed: ${job.id} with error: ${err.message}`);
});
}
}
Running the Application
-
Start Redis: If you are using Docker, you can run Redis with the following command:
docker run -p 6379:6379 -d redis
-
Run the TypeScript application:
npx ts-node src/index.ts
-
Test the API: You can use a tool like Postman or curl to test the API. Here’s an example of how to place a bet using curl:
curl -X POST http://localhost:3000/bet -H "Content-Type: application/json" -d '{"userId": "user1", "amount": 100, "gameId": "game1"}'
Conclusion
This is a basic example of a betting system using TypeScript, Node.js, and Redis with Bull for job processing. You can expand this system by adding features like user authentication, database integration, and more complex betting logic.