Tuesday, August 10, 2010

Faye Extensions 101: Client-Side Extensions

‹prev | My Chain | next›

Didn't think I would, but tonight, I would like to make sure that I can write client-side faye extensions. Last night I figured out that preventing subscriptions on the server side sends a message back to the client. That message is ignored by the client. Tonight I would like to write a cient-side extension to do something with that error message.

From yesterday, and tcpdump, I know that subscription denial messages include successful and message attributes:
...
0x00e0: 3576 222c 2263 6861 6e6e 656c 223a 222f 5v","channel":"/
0x00f0: 6d65 7461 2f73 7562 7363 7269 6265 222c meta/subscribe",
0x0100: 2265 7272 6f72 223a 2257 696c 6463 6172 "error":"Wildcar
0x0110: 6420 7375 6273 6372 6970 7469 6f6e 7320 d.subscriptions.
0x0120: 6e6f 7420 616c 6c6f 7765 6422 2c22 7375 not.allowed","su
0x0130: 6363 6573 7366 756c 223a 6661 6c73 657d ccessful":false}
...
Armed with that knowledge, I write myself a faye client, this time for the browser:
<script type="text/javascript" src="http://localhost:8000/faye.js"></script>
<script type="text/javascript">
var client = new Faye.Client('http://localhost:8000/faye');

var message_exceptions = {
incoming: function(message, callback) {
if (!message.successful) {
throw message.error;
}
console.debug(message);
callback(message);
}
}

client.addExtension(message_exceptions);
</script>
If the successful attribute indicates that the subscription was not successful, then my new extension throws an exception—with the error message sent back on the error attribute.

Trying this out in the browser, I find:



Wow. That worked the first time out.

But wait, I know what that error on line 13 is—it is the error that I throw. Why am I seeing that output on line 15? Thankfully, I can expand that object in Chrome's Javascript Console:



Ah, that is just the initial channel handshake. So it really does just work. My faye extension—all of three lines of code—will throw an error when any message from the server is unsuccessful.


Day #191

No comments:

Post a Comment