I'm trying a simple to build a simple chat server. The main objective, for now, is to send the message from one client to another client, without saving into the DB, consuming less memory.
I'm using Meteor 1.4.1
. So far I'm able to send and receive the messages with help of pub-sub data loading service.
// Collection declaration
if(Meteor.isServer){
export const Messages = new Meteor.Collection("messages",{connection: null});
}
// Publish function
Meteor.publish('messages', function(rid) {
if (!this.userId) {
return this.ready();
}
let finderHandle = Messages.find({
$or: [
{username: Meteor.users.findOne({_id: this.userId}).username},
{rid: Meteor.users.findOne({_id: this.userId}).username}
]
})
finderHandle.observeChanges({
added: (_id, record) => {
this.added( 'messages',_id, record )
},
changed: (_id, record) => {
this.changed( 'messages', _id, record)
},
removed: (_id, record) => {
this.removed( 'messages',_id, record)
}
});
this.onStop(() => {
console.log("disconnected")
// finderHandle.close(); // Giving an Error: finderHandle.close() function not found.
})
this.ready();
});
The Problem here is, It is keeping all the messages in memory, It should only work as mediator When one client subscribe it should deliver the message and after that, it should be released from the memory. Presently, on subscribe I'm getting all the previous messages as well.
The thing which I'm missing here is onStop
function, I'm not sure how this can be achieved. Please point me in the right direction.
Thanks in advance, Comments will also be appreciated.
UPDATE
from @CodeChimp, I've updated the collection query as below:
return Messages.find({
rid: Meteor.users.findOne({_id: this.userId}).username,
ls: {$exists: false}
},{
sort: {ts: -1}
})
where rid
is the recipient username, and ls
is last seen if it doesn't exist, only those records will be sent to the recepient client only.