HTML and CSS Reference
In-Depth Information
Now that we have an array to store messages in, we can retrieve ids from the
array's length instead of keeping a dedicated counter around. The id adds one
to the length to make it 1-based rather than 0-based. The reason for this is that
getMessagesSince is supposed to retrieve all messages added after some id.
Using 0-based ids we'd have to call this method with -1 to get all messages, rather
than the slightly more natural looking 0. It's just a matter of preference, you may
disagree with me.
Running the tests confirms that all the previous tests are still passing. As ids
are now directly related to the length of the messages array, retrieval is trivial as
Listing 14.43 shows.
Listing 14.43 Fetching messages
getMessagesSince: function (id, callback) {
callback(null, this.messages.slice(id));
}
And just like that, all the tests, including the one test for getMessagesSince ,
pass. getMessagesSince helped us properly implement addMessage , and the
best case situation is now covered. However, there are a few more cases to fix for it
to work reliably.
It should yield an empty array if the messages array does not exist.
It should yield an empty array if no relevant messages exist.
It could possibly not throw exceptions if no callback is provided.
The test cases for addMessage and getMessagesSince should be
refactored to share setup methods.
Testing and implementing these additional cases is left as an exercise.
14.3.4.2 Making addMessage Asynchronous
The addMessage method, although callback-based, is still a synchronous inter-
face. This is not necessarily a problem, but there is a possibility that someone
using the interface spins off some heavy lifting in the callback, inadvertently caus-
ing addMessage to block. To alleviate the problem we can utilize Node's pro-
cess.nextTick(callback) method, which calls its callback on the next pass
of the event loop. First, Listing 14.44 tests for the desired behavior.
 
Search WWH ::




Custom Search