HTML and CSS Reference
In-Depth Information
Listing 14.10 JSON request to create message
{ "topic": "message",
"data": {
"user": "cjno",
"message": "Listening to the new 1349 album"
The outer “topic” property describes what kind of event to create, in this
example a new message, whereas the outer “data” property holds the actual data.
The client was made this way so it could post different types of client-side events
to the same server resource. For instance, when someone joins the chat, the client
might send JSON like Listing 14.11.
Listing 14.11 JSON request to join the chat room
{ "topic": "userEnter",
"data": {
"user": "cjno"
If the backend is ever extended to support several chat rooms, the message
might also include which room the user entered. Reading the Request Body
The first thing post needs to do is retrieve the request body, which contains
the URL encoded JSON string. As a request comes in, the request object will
emit “data” events, passing chunks of the request body. When all chunks have
arrived, the request object emits a “end” event. The equivalent of our observ-
able from Chapter 11, The Observer Pattern, that powers Node's events is the
events.EventEmitter interface.
In tests, we will stub the request object, which needs to be an EventEmit-
ter so we can trigger the “data” and “end” events we are interested in testing. We
can then emit a couple of chunks from the test, and assert that the joined string is
passed to JSON.parse . To verify that the entire body is passed to JSON.parse ,
we can stub it using the stub function from Chapter 12, Abstracting Browser Differ-
ences: Ajax. Save Listing 14.12 in deps/stub.js .
Search WWH ::

Custom Search