Wednesday, December 4, 2013

Posting JSON Payload with Polymer-Ajax (Dart)

I was somewhat bummed to discover that Polymer's <polymer-ajax> does not support JSON HTTP request bodies—at least in the Dart version. But after a bit of digging, it seems that there is a <polymer-xhr> that seems to support arbitrary body data (in both Dart and JavaScript). So tonight, I explore this element in the hopes that I can use it to get the higher-level <polymer-ajax> to also support arbitrary HTTP payload content.

With that, I am ready to make my changes to the class that is backing <store-changes>. Instead of setting <polymer-ajax> parameters and then invoking go(), I just need to invoke request() on <polymer-xhr> with the necessary options. And, since this is a low-level call, there are a lot of options:

And that turns out to just work™. When I make changes to the the contained <div contenteditable> element, change events propagate to the custom Polymer, <store-changes> which sends JSON encoded HTTP requests to the server:

So the question then becomes, can I get <polymer-ajax> to support arbitrary HTTP bodies? To answer that question, I fork the polymer elements (Dart), and clone it locally. Then I point my application to this local copy of my fork by making the necessary change in pubspec.yaml:

If present, this Map will serve as the default values for the arguments sent to the underlying <polymer-xhr>. I already know that, if there is body key in that xhrArgs then I can POST whatever I want via <polymer-xhr>, so I supply just that in my <store-changes> element:

It works! When I make changes in the wrapped <div contenteditable>, my <store-changes> Polymer sees the change and saves a history record over XHR. Only this time, it does it with <polymer-ajax> and mercifully fewer arguments.

There are a few other benefits to be reaped in <polymer-ajax>. I will likely try to reap them tomorrow.