Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
var app = function(request) {
  return function(responder) {
    var w = responder(200, headers);

    event.readSomething(function(contents) {
      w.write(JSON.stringify(contents));
      w.close();
    });
  };
}


var middleware = header_middleware(app, function play_with_headers(res) {
  res.headers['last-modified'] = new Date();
});


var header_middleware(app,adjuster) {
  return function(request) {
    var r = app(requrest);

    if (typeof r == "function") {
      // Async
      return function(responder) {
        var appResponderProxy = function(status_, headers_) {
          var x = {status: status_, headers: headers_};
          adjuster(x);

          // Return the writer to the app after adjusting headers
          return responder(x.status,x.headers)
        };

        // Call the app async callback with our proxy responder fn
        return r(appResponderProxy);
      };
    } else {
      adjuster(r);
      return r;
    }
  }
}

var body_middleware(app,adjuster) {
  return funciton(request) {
    var r = app(request);

    if (typeof r == "function") {
      return funciton(responder) {
        var appResponderProxy = function(s,h) {
          var w = responder(s,h),
              w_proxy = Object.create({}, w);

          w_proxy.write = function(chunk) {
            return w.write(adjuster(chunk));
          }

          // Return the proxy object to the app
          return w_proxy;
        };

        // Call the app async callback with our proxy responder fn
        return r(appResponderProxy);
      }
    }
    else {
      // Might more efficent ways of handling this but it should work
      r.body = r.body.map(adjuster);
      return r;
    }
  }
}