Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a property to an object (or at least similar outcome)

Tags:

dart

First, the context of what I'm doing. I am running an HttpServer which is handling HttpRequests.

    HttpServer.bind(ADDRESS, PORT).then((HttpServer server) {
      listenSubscription = server.listen(onRequest);
    });

    void onRequest(HttpRequest request) {
      //handle request here
    }

I'd like to add some logging to all this, and due to the asynchronous nature of it all, want to add some identifying marker to the requests (so I can match up the request receipts with the responses, fer example). The code inside of onRequest() calls a bunch of other functions to do different things (handle GET vs POST requests, etc.), so simply generating an id at the top is a cumbersome solution as I'd have to pass it around through all those other function calls. I am, however, already passing around the HttpRequest object, so I thought it would be nice to throw an id field on it, just like you would in Javascript, except that Dart doesn't work that way.

Thoughts then went to subclassing the HttpRequest class, but converting the HttpRequest object the onRequest() method receives seemed like much more trouble and overhead than my needs required.

So I ask, is there any idiomatic Dart way attach some data to an existing object? If there isn't something idiomatic, what is the simplest (both in code and runtime complexity) way you can think of to accomplish this?

like image 801
Michael Fenwick Avatar asked Sep 11 '14 02:09

Michael Fenwick


1 Answers

Well, there's an Expando, but I don't know the performance implications.

Something like:

// somewhere top level. Create this once.
final loggingId = new Expando();
...
// inside of onRequest
loggingId[request] = generateId();
...
// later inside log()
print(loggingId[request]);

Expandos are like weak-reference maps, from my understanding.

like image 96
Seth Ladd Avatar answered Sep 28 '22 02:09

Seth Ladd