Chat best practices

I’d like to add basic chat functionality to my app. I’d appreciate any feedback regarding best practices for:

  1. Retrieve a list of all currently logged in users to build an available contact directory.
  2. Track when a user drops out of a chat.
  3. Notify a user when another user initiates a chat

I can’t speak to ‘best practices’ but I’ve had success doing something like the following:

Retrieve a list of all currently logged in users to build an available contact directory.
Track when a user drops out of a chat.

The user-status package is handy for this. I use this on Acrofever to show a list of online users with something like the following publication:

Meteor.publish("userStatus", function() {
  return Meteor.users.find({ "status.online": true }, { fields: { ... } });
});

You can subscribe to that publication to get a list of online contacts.

To track when a user drops out of a chat (ie. goes offline), you could observe changes on a cursor for that user, for example:

var observer = Meteor.users.find({_id: userIdToWatch, 'status.online': true}).observeChanges({
	removed: function(id, document) {
		// user has gone offline, do stuff

		// stop this observer if you want
		observer.stop();
	}
});

Notify a user when another user initiates a chat

Again, you could observe changes on your chat collection for this. As an example:

Chat.find({}).observeChanges({
	added: function(id, document) {
		alert('Your friend says hi');
		//do stuff
	}
});

I don’t know about best practices but one way you could approach it is to research what other chat apps do.

Here’s a well-known Meteor-based one:

For a more heavy-weight dive, XMPP is a protocol just for chat. Ejabberd is a well-known Erlang implementation:

Thanks, searching for user status on atmosphere returned 4 packages that are very informing.

Rocket Chat also looks interesting. I’ll have to play around with it. Anyone integrate Rocket Chat into their app?

On the UI-side, using flexbox for the chat message layout saved me tons of time.

1 Like