Skip to content

Commit

Permalink
Create queue.js
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Jul 21, 2024
1 parent 7d57bd7 commit d8b0f43
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions messaging/queue.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { Message } from './message';
import { RedisClient } from 'redis';

class MessageQueue {
constructor(redisUrl) {
this.redisClient = new RedisClient(redisUrl);
this.queueName = 'cosmia:messages';
}

async enqueue(message) {
// Add a message to the queue
await this.redisClient.lpush(this.queueName, message.toJSON());
}

async dequeue() {
// Retrieve and remove the next message from the queue
const messageJSON = await this.redisClient.rpop(this.queueName);
if (messageJSON) {
return new Message(messageJSON);
}
return null;
}

async size() {
// Return the number of messages in the queue
return await this.redisClient.llen(this.queueName);
}

async peek() {
// Return the next message in the queue without removing it
const messageJSON = await this.redisClient.lindex(this.queueName, 0);
if (messageJSON) {
return new Message(messageJSON);
}
return null;
}
}

export default MessageQueue;

0 comments on commit d8b0f43

Please sign in to comment.