In my last blog post, Persisting with Redis, I described the long overdue ah-ha moment of figuring out the incredibleness of async callbacks meant and how it can do wonders for you and your program.

Recap: Node.js runs on asynchronous calls meaning that it will continue functioning until an event is met.// do i really want to explain this?

I left off with having Redis push messages into a ‘history’ list and then to print the history to newly connected users so that they would know what is going on when the enter the chat. While this great, it meant that people were going to get the history from the dawn of my chat to most recent and this would be useless and annoying. New users just need to get the gist of what is going on, so that they can engage themselves. So my new task was to print only 10 messages on connection.

Luckily for me, a Redis expert, Itamar Haber, happened to read my last blog and helped me out with printing out only 10 messages. It only required a couple of tweaks.

On the index.js file where the history prints, we had:

    client.lrange('history', 0, 9, function(err, history){

This did the trick! Rather than all of the printing out everything, it only printed out 10 messages.

newlrangeCode But it printed out the first 10 messages that I had pushed not the last. This means that the new user would get the beginning first messages ever written, which isn't too helpful to someone trying to jump into the conversation! Luckily there is an easy fix. On the index.html:

In my for loop, I am starting at 0 and moving up through all the messages until the last one. Well, we just want to reverse it! Instead, we want to start with the last message, and move down to the first one (and then only print 10). So I just need to change my for loop to reflect that:

Now I felt that I had a much better understanding of how things were working within my chat and decided to tackle three new problems:

  1. Create and display usernames.
  2. Create rooms that people could talk in.

Create and display Usernames

Creating and displaying usernames seemed like a reasonable goal, as it was more or less a replication of creating persisting and displaying the history.

First, we have to think about when we want to do:

  1. When a new user joins we want to emit the name to all the sockets so everyone currently in the chat gets the new users name.
  2. We want the new user to get a list of the current users
  3. We want the new users name to be logged into the username history list, so they are included as a current user when someone new joins.

So this will have to be on connection, just after they have joined (and we have received the new users name.)

comments powered by Disqus