Showing posts with label httprequest. Show all posts
Showing posts with label httprequest. Show all posts

Sunday, February 16, 2014

Using polymer-ajax to Load Configuration


With the first edition of Patterns in Polymer in the books, it is time to debunk everything. Well, maybe not quite everything, but I ought to keep an open mind on some of the assumptions that I made throughout so that version 1.1 of the book can be that much more solid.

The thing that sticks out the most in my mind as questionable is using <link> imports for configuration files. To be sure, there seem to be some good reasons to use them—in particular they make use of the platform. They also seem to avoid the overhead of dealing with the asynchronous nature of HttpRequest. Using <link> tags is a little messy, however. Deployment utilities do not seem to account for them and extra text content can creep in.

So it mostly works, but I am curious to see how hard HttpRequest configuration might be.

The superficial change will be that the <link> configuration:
      <hello-you>
        <link rel="import" href="hello-you.json">
        <p>And good-bye…</p>
      </hello-you>
Will change to something like:
      <hello-you conf="hello-you.json">
        <p>And good-bye…</p>
      </hello-you>
My main contention with HttpRequest based configuration is that it is a hassle. But this is Polymer, so how much of a hassle is it really? I can include an <polymer-ajax> element from the built-in Polymer elements. If I place it right in the template of my custom <hello-you> tag, I can even bind the conf attribute of <hello-you> to the url attribute of <polymer-ajax>:
<link rel="import" href="../../../packages/polymer_elements/polymer_ajax/polymer_ajax.html">
<polymer-element name="hello-you">
  <template>
    <polymer-ajax url="{{conf}}" handleAs="json"></polymer-ajax>
    <!-- ... -->
  </template>
  <script type="application/dart" src="hello_you.dart"></script>
</polymer-element>
I can also configure <polymer-ajax> to handle that resource as JSON, which I had to perform manually in my <link> approach. To listen and apply this configuration inside the backing class to <hello-you>, it is easiest to grab a reference to <polymer-ajax> and read its response attribute:
@CustomTag('hello-you')
class HelloYou extends PolymerElement {
  // ...
  @published String conf = 'packages/ajax_config/elements/hello-you.json';
  HelloYou.created(): super.created();

  ready() {
    super.ready();
    var ajax = shadowRoot.query('polymer-ajax');
    ajax.
      on['polymer-complete'].
      listen((_) {
        ajax.response.forEach((k, v)=> this[k] = v);
      });
  }
}
The polymer-complete event lets me know that a response has been received from the HttpRequest. I can then read the JSON parsed response directly from the <polymer-ajax> element's response attribute. Since the JSON response is a Map I can iterate over each key-value pair, updating the appropriate value (e.g. greeting, instructions, etc.) in <hello-you>.

And that works. If I use the specialized configuration by explicitly supplying a conf attribute to the <hello-you> Polymer, I get a specialized version of the Polymer:



But, if I remove that attribute and allow the Polymer to load the default configuration, I see:



So in the end, <polymer-ajax> does a pretty decent job of overcoming my objections to HttpRequest messiness. That said, I am not dealing with error conditions, which a <link> approach gives me for free. I am not even attempting to load default configuration and then specialized configuration at the same time here. While not something that <link> gives me for free, worries about load order are eliminated by the platform.

So I think that the <link> approach is still sound. The winning approach is not quite a clear cut as I had thought, however.


Day #1,028

Friday, December 6, 2013

Strategies for Polymer


After a pleasurable detour in Polymer.dart plumbing, I am ready to get on with original intent with this bit of Dart code: writing my custom <store-changes> element such that it will work with either <polymer-localstorage> or polymer-ajax>. I am not doing this because I think it is a good idea. Rather I am just curious what my code would look like if it can do either.

Currently, I am using the tags as follows:
    <store-changes>
      <!-- <polymer-localstorage name="store-changes" value="{{value}}"></polymer-localstorage> -->
      <polymer-ajax url="http://localhost:31337/widgets/change-history"
                    handleAs="json">
      </polymer-ajax>
      <!-- <polymer-xhr></polymer-xhr> -->
      <!-- changes will originate from elements here ... -->
    </store-changes>
And, in the Dart class that backs the <store-changes> custom element, I am similarly commenting out any code that works against localstorage:
@CustomTag('store-changes')
class StoreChangesElement extends PolymerElement {
  StoreChangesElement.created(): super.created();
  // ...
  void _fetchCurrent() {
    // if (store.value != null) record = store.value;

    var subscription;
    subscription = on['polymerresponse'].listen((e){
      // handle http response here....
    });
  }
  // ...
}
I would like either tag, if present, to work. The easiest way to accomplish that is via a common wrapper interface. Both the Ajax and localStorage data store strategies need to be able to fetch records and save records, given a Polymer element:
abstract class ChangeStore {
  PolymerElement el;
  ChangeStore(this.el);

  Future<Map> fetch();
  void save(Map record);
}
The Future return type on fetch() is somewhat premature, but I have already implemented it directly in <store-changes> and know perfectly well that it is asynchronous. So maybe not that premature.

Next up, I define my Ajax strategy as extending this abstract baseclass:
class AjaxStore extends ChangeStore {
  AjaxStore(el): super(el);
}
The fetch() method is the same code as yesterday, but with a Completer to give me the necessary Future:
class AjaxStore extends ChangeStore {
  Future<Map> fetch() {
    var subscription,
      completer = new Completer();

    subscription = el.on['polymerresponse'].listen((e){
      var res = e.detail['response'],
          data = (res != null && !res.isEmpty) ? res : null;
      completer.complete(data);
      subscription.cancel();
    });
    return completer.future;
  }
}
Since I do not care if the save is successful (so what if a little undo history is lost?), the save() method is particularly easy to implement:
class AjaxStore extends ChangeStore {
  // ...
  void save(rec) {
    el
      ..method = 'POST'
      ..xhrArgs = {'body': JSON.encode(rec)}
      ..go();
  }
}
With that, I have my Ajax strategy ready to roll. I place each strategy present inside a list of stores:
@CustomTag('store-changes')
class StoreChangesElement extends PolymerElement {
  // ...
  List<ChangeStore> stores = [];
  StoreChangesElement.created(): super.created();
  enteredView() {
    super.enteredView();
    addEventListener('change', storeChange);
    scheduleMicrotask(_attachStores);
    // ...
  }
  // ...
}
I keep bumping into the need to schedule a “microtask” as I have done here. Without it, Polymer has not had a chance to do its thing, leaving the code thinking that things like <polymer-ajax> and <polymer-localstorage> are unknown, basic HTML elements.

Attaching the stores is where I detect whether the <polymer-ajax> tag is present and, if so, adding the corresponding strategy to the list:
@CustomTag('store-changes')
class StoreChangesElement extends PolymerElement {
  List stores = [];
  StoreChangesElement.created(): super.created();
  // ...
  void _attachStores() {
    var polymer = children.firstWhere(
        (el) => el.localName == 'polymer-ajax'
      );
    if (polymer != null) stores.add(new AjaxStore(polymer));
  }
  // ...
}
Placing the storage strategies in a list makes them iterable. In other words, it is easy to call fetch() and save() on any strategies present (if any):
@CustomTag('store-changes')
class StoreChangesElement extends PolymerElement {
  Map record = {'history': []};
  List stores = [];
  // ...
  void _fetchCurrent() {
    stores.forEach((store) {
      store.fetch().then((_r) => record = _r);
    });
  }

  storeChange(e) {
    // build record from a change event, then ....
    stores.forEach((store)=> store.save(record));
  }
}
And that works.

After a quick and dirty implementing of the localStorage strategy, I am able to swap out <polymer-ajax> for <polymer-localstorage> in the web page and not miss a beat::
    <store-changes>
      <polymer-localstorage name="store-changes" value="{{value}}"></polymer-localstorage>
      <!-- <polymer-ajax url="http://localhost:31337/widgets/change-history" -->
      <!--               handleAs="json"> -->
      <!-- </polymer-ajax> -->
      <!-- changes will originate from elements here ... -->
    </store-changes>
And that works as well. In fact, since the strategies are iterable, I can have both <polymer-*> tags present and everything works just fine.

It took a few days of groundwork, but the actual implementation of this multi-strategy approach worked out quite nicely. I don't know that it rises to the level of an actual “pattern” for Patterns in Polymer. Maybe it is a basis pattern or something like that (which is, I suppose a pattern in the true sense of the term). I think I will hold off on this one before it makes an appearance in the book. For now, I am content to have a clean implementation.


Day #957

Thursday, December 5, 2013

Canceling Polymer Ajax Listeners (Dart)


Up today, a bit of cleanup on the <polymer-ajax> work from yesterday. My pull request was merged into the Dart version of the Polymer Elements project, so I can switch back to the real thing instead of my fork. I would also like to double check that I am using <polymer-ajax> effectively.

Switching back to the real project is easy. This is Dart, after all. I swap the path dependency that had pointed to my fork, replacing it with the GitHub repository of the real thing (the most recently published version does not work with Dart 1.0 yet, so I use the GitHub repo):
name: change_history
dependencies:
  polymer: any
  polymer_elements:
    git: https://github.com/ErikGrimes/polymer_elements
    # path: /home/chris/repos/polymer_elements
After a quick pub upgrade, I am ready to go, using the the most recent version of polymer_elements including my pull request. Yay Dart!

Next up, I sort through the code in an effort to identify some niceties of <polymer-ajax> that I might not be using effectively. In the web page itself, I am wrapping my <polymer-ajax> element as:
    <store-changes>
      <!-- <polymer-localstorage name="store-changes" value="{{value}}"></polymer-localstorage> -->
      <polymer-ajax url="http://localhost:31337/widgets/change-history"
                    handleAs="json">
      </polymer-ajax>
      <!-- changes will originate from elements here ... -->
    </store-changes>
The handleAs JSON means that I do not need to manually decode JSON responses back from <polymer-ajax>. Unfortunately, I still have to manually encode the JSON when storing change history:
@CustomTag('store-changes')
class StoreChangesElement extends PolymerElement {
  StoreChangesElement.created(): super.created();
  // ...
  get store => children.
    firstWhere((el) => el.localName == 'polymer-ajax');
  // ...  
  storeChange(e) {
    // ...
    store
      ..method = 'POST'
      ..xhrArgs = {'body': JSON.encode(record)}
      ..go();
  }
}
I am not too fussed by this. Before yesterday, I did not even think it was going to be possible to do encode the body of the Ajax request in JSON. I am a bit off the happy path here, so I am happy to do a little extra work.

That said, I can make use of the handleAs JSON when retrieving the records:
@CustomTag('store-changes')
class StoreChangesElement extends PolymerElement {
  Map record = {'history': []};

  StoreChangesElement.created(): super.created();

  enteredView() {
    super.enteredView();
    _fetchCurrent();
    addEventListener('change', storeChange);
  }
  void _fetchCurrent() {
    var subscription;

    subscription = on['polymerresponse'].listen((e){
      print(e.detail['response']);
      record = e.detail['response'];
      subscription.cancel();
    });
  }
The record needs to be a Map object. Without <polymer-ajax> decoding the response for me, I would have to manually convert that response each time. It might not seem like a huge win, but it is really is the little niceties in a project that make it a pleasure.

Of note in _fetchCurrent() is how I have to subscribe and cancel the listener. I cannot declare and assign subscription in the same statement because it will lead to errors like:
Internal error: 'http://localhost:8080/packages/change_history/store_changes.dart': Error: line 11 pos 9: initializer of 'subscription' may not refer to itself
    var subscription = on['polymerresponse'].listen((e){
        ^ 
I have no luck getting removeEventListener() to remove listeners when used in conjunction with addEventListener(), which is why I wind up using the on['polymerresponse'] stream instead. Happily, it works just fine. I am able to get the initial load and then cancel the subscription so that subsequent GET requests might be handled elsewhere.

That should do it for <polymer-ajax>. Tomorrow, I will explore strategies for swapping it and <polymer-localstorage>.


Day #956

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.

So I import the <polymer-xhr> tag definition:
    <!-- Load component(s) -->
    <link rel="import" href="/packages/change_history/change-sink.html">
    <link rel="import" href="/packages/change_history/store-changes.html">
    <link rel="import" href="/packages/polymer_elements/polymer_localstorage/polymer_localstorage.html">
    <link rel="import" href="/packages/polymer_elements/polymer_ajax/polymer_ajax.html">
    <link rel="import" href="/packages/polymer_elements/polymer_ajax/polymer_xhr.html">
Then, in the body of the page, I add <polymer-xhr> as a child to the <store-changes> element that I am trying to get working over Ajax:
    <store-changes>
      <!-- <polymer-localstorage name="store-changes" value="{{value}}"></polymer-localstorage> -->
      <!-- <polymer-ajax url="http://localhost:31337/widgets/change-history" -->
      <!--               handleAs="json"> -->
      <!-- </polymer-ajax> -->
      <polymer-xhr></polymer-xhr>
      <!-- changes will originate from elements here ... -->
    </store-changes>
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:
@CustomTag('store-changes')
class StoreChangesElement extends PolymerElement {
  StoreChangesElement.created(): super.created();
  // ...
  get store => children.
    firstWhere((el) => el.localName == 'polymer-xhr');
  storeChange(e) {
    // Convert the change event into an "update" record, then...
    store.
      request({
        'url': 'http://localhost:31337/widgets',
        'method': 'POST',
        'callback': (__res, __xhr){},
        'headers': {},
        'body': JSON.encode(update)
      });
    // ...
  }
}
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:
{"id":"change-history","current":"\n          <h1>
Change #1</h1>
\n        ","history":["\n          <h1>
Change #1</h1>
\n        "]}
And the server is happy to respond with:
HTTP/1.1 201 Created
server: Dart/1.0 (dart:io)
access-control-allow-origin: *
access-control-allow-headers: Content-Type, X-Requested-With
access-control-allow-methods: GET,DELETE,PUT
content-type: application/json; charset=utf-8
transfer-encoding: chunked
content-encoding: gzip
Yay!

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:
name: change_history
dependencies:
  polymer: any
  polymer_elements:
    path: /home/chris/repos/polymer_elements
A quick pub getIn my new copy of polymer_elements, I add an xhrArgs public attribute to <polymer-ajax> (mimicking the property of the same name in the JavaScript version of the element):
@CustomTag('polymer-ajax')
class PolymerAjax extends PolymerElement {
  // ...
  @published
  Map xhrArgs;
  // ...
  go() {
    var args = xhrArgs != null ? xhrArgs : {};
    // ...
  }
}
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:
@CustomTag('store-changes')
class StoreChangesElement extends PolymerElement {
  StoreChangesElement.created(): super.created();
  // ...
  get store => children.
    firstWhere((el) => el.localName == 'polymer-ajax');
  storeChange(e) {
    // Convert the change event into an "update" record, then...
    store
      ..method = 'POST'
      ..xhrArgs = {'body': JSON.encode(update)}
      ..go();
    // ..
  }
}
After switching back to the higher level <polymer-ajax> in my web page:
<store-changes>
      <!-- <polymer-localstorage name="store-changes" value="{{value}}"></polymer-localstorage> -->
      <polymer-ajax url="http://localhost:31337/widgets/change-history"
                    handleAs="json">
      </polymer-ajax>
      <!-- <polymer-xhr></polymer-xhr> -->
      <!-- changes will originate from elements here ... -->
    </store-changes>
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.


Day #955

Sunday, October 20, 2013

HTTP Requests in Angular.dart


I have a rough outline of things that I want to explore in Angular.dart. Angular.dart is, of course, the Dart port of AngularJS, the framework that's all the rage. Next on that list is routing, but that is yet to be implemented (it is part of the active milestone, so maybe someday soon). With routing off the table, I move onto the next item on the list: HTTP requests.

The JavaScript version of Angular has a very Dart-like feel to it, thanks to its promises and the $http service that is injected into controllers. So I do not expect too many surprises. That said, I am not quite sure how this will translate the class based approach to controllers that I liked so much last night...

To find out, I start by creating a REST-like backend. I already have one of these for dart-comics, which is the companion code repository for the Dart for Hipsters book. The backend uses a dirt-simple noSQL persistent store, dart dirty. I copy the server from dart-comics to my angular-calendar repository in which I am currently working. I change the resources in the server from “comics” to “appointments” (which means I may want to convert this simple server into a package some day soon).

Anything not in the /appointments URL-space will be served up from my repository's web subdirectory, making this a drop-in replacement for pub serve. After stopping the simple HTTP server built into Dart Pub, I start this server:
➜  angular-calendar git:(master) ✗ dart server.dart
Server started on port: 8000
...
A quick check reveals that my Angular day-view for appointments is still working:



Before I try to use an Angular HTTP service, I think I will try this in plain-old Dart. As I mentioned, AngularJS has a Dart-like feel already—perhaps the HTTP service normally used in Angular applications is not necessary.

In the controller class, I start by removing the default “Wake up” entry that I had been associating with the appointments list. I also create a constructor that will be responsible for loading appointments from my REST-like server:
class AppointmentCtrl {
  List appointments;
  // ...
  AppointmentCtrl() {
    _loadAppointments();
  }
  // ...
}
In the private _loadAppointments() method, I perform a simple HTTP request for the /appointments resource:
  _loadAppointments() {
    HttpRequest.
      getString('/appointments').
      then((responseText){
        appointments = JSON.decode(responseText);
      });
  }
When the response comes back, I decode the JSON and assign the results to the list of appointments. It does not get much simpler than that.

Of course, I am now left with no appointments in the application since my noSQL store is empty. To persist entries that I make, I need to update the add() method from last night to include an HTTP POST:
  void add() {
    var newAppt = fromText(newAppointmentText);
    appointments.add(newAppt);
    newAppointmentText = null;
    HttpRequest.
      request(
        '/appointments', 
        method: 'POST', 
        sendData: JSON.encode(newAppt)
      );
  }
And, just like that, I am able to add records that persist in the server after a page reload:



Pfft. That was pretty easy. I seriously doubt the service approach is going to improve on this much, but I will give it a go anyway.

Working from the top down, I start in the main() entry point for my application by adding a new “type” to my Angular module—the ServerCtrl:
main() {
  var module = new AngularModule()
    ..type(ServerCtrl)
    ..type(AppointmentCtrl);

  bootstrapAngular([module]);
}
(n.b. bootstrapAngular() will be changing to ngBootstrap() in the next release)

The order in which the “types” are added to the module does not seem to matter. What does matter is the declared type for the constructor parameters of the classes. For the ServerCtrl, I declare an Http instance variable to be passed to the constructor:
class ServerCtrl {
  Http _http;
  ServerCtrl(this._http);
  // ...
}
That alone seems to be sufficient to get Angular.dart to inject the correct thing, which is pretty cool. I may have to dig into the code to figure out how they do that. Regardless, once I have my Http instance set, I can use it. For example, I can create an init() method that can be called by the appointments controller to initialize the list of appointments that have been persisted on the server:
class ServerCtrl {
  Http _http;
  ServerCtrl(this._http);

  init(AppointmentCtrl cal) {
    _http(method: 'GET', url: '/appointments').
      then((HttpResponse res) {
        res.data.forEach((d) {
          cal.appointments.add(d);
        });
      });
  }
}
Calling the _http object like that is a little more verbose than the getString() method on HttpRequest, though I do get the automatic conversion of the JSON response in the data property. And, if life in AngularJS has taught me anything, this should prove to be more testable as well (but that's a question for tomorrow).

I am not quite done, because now I need to get the AppointmentCtrl instance to call this init() method in the server controller. This turns out to be pretty easy thanks to that declared type trick. In the AppointmentCtrl constructor, I declare that it takes one argument—an instance of ServerCtrl. With that, Angular.dart will inject the active instance of ServerCtrl into the constructor so that I can invoke the init() method:
class AppointmentCtrl {
  // ...
  AppointmentCtrl(ServerCtrl server) {
    server.init(this);
  }
  // ...
}
And that works! Starting from the main() entry point, Angular is able to create an instance of my server controller and inject it into the constructor of the appointment controller when it creates an instance of that class. The appointment controller then injects itself into the server's init() method to load the initial list of appointments.

That is a lot of injection and I am not completely convinced that it is an improvement from a code clarity point of view. But it is a definite improvement in separating concerns, which should lead to improved testing and maintainability. I will put that theory to the test tomorrow.


Day #910

Monday, December 24, 2012

Cannot Stub HttpRequest in Dart

‹prev | My Chain | next›

Up today, I hope to figure out how to test HttpRequest code in Dart. I began building a test suite for the first chapter in Dart for Hipsters yesterday, but that client-side code did little more than not crash.

The remainder of the code in Chapter One builds around HttpRequest code such as:
main() {
  load_comics();
}

load_comics() {
  var list_el = document.query('#comics-list')
    , req = new HttpRequest();

  req.open('get', '/comics', true);

  req.on.load.add((res) {
    var list = JSON.parse(req.responseText);
    list_el.innerHTML = graphic_novels_template(list);
    attach_delete_handlers(list_el);
  });

  req.send();
}
I will try to test the actual functionality later. For now. I start with a simple returnsNormally test:
    test('the app returns OK', (){
      expect(Main.main, returnsNormally);
    });
Unfortunately, that results in the following failure:
[main] the app returns OK. Expected: return normally but: threw <Error: NETWORK_ERR: XMLHttpRequest Exception 101>.
This particular error results from an HttpRequest attempt from a file:// page (the HTML page that holds the tests). In the Dart console I see a JavaScripty complaint:
XMLHttpRequest cannot load file:///comics. Cross origin requests are only supported for HTTP.
Unfortunately, I think I am stuck here. There is no way to redefine a method in Dart, so I have no hope of redefining open(). I might try to redefine the HttpRequest class so that it returns a real or fake HttpRequest object depending on a static variable setting. Unfortunately, this kind of thing will not work:
class MockHttpRequest implements HttpRequest {}
class RealHttpRequest  {
  factory RealHttpRequest() => new HttpRequest();
}

class HttpRequest {
  factory HttpRequest() {
    return new RealHttpRequest();
  }
}
This turns out to be a good way to generate a stack overflow (RealHttpRequest return an instance of HttpRequest, which returns an instance of RealHttpRequest).

My real problem is that I absolutely must stick with creating an instance of HttpRequest using the form:
req = new HttpRequest();
Were this real-world code, I could use some form of dependency injection to supply an alternate HttpRequest object. I do this sort of thing in HipsterSync in the Hipster MVC library.

What I would really like is some way to intercept or stub all network connections in Dart. But this seems a ways off at this time. So I find myself stuck with this particular bit of code. I will mull this over a bit, but I may have to either leave this bit of code untested or I may have to resort to some kind of Frankenstein-like code sample assembly in the book. Neither option is particularly pleasant, but I do not see many alternatives.


Day #609