In my restify server I have a route that I want to add a filter to. The way this would work in Express (this does work in Express) is the response.on would add my handler as the callback. Then before the response is returned to the requestor my handler would be called. This is not the behavior I am seeing in Restify. My guess is I am not registering my handler to the event machine properly.

restifyServer.get({ path: "/api/v1/readings", version: ["1.0.0"]}, Reading.getReadings);

I add a handler:

function zipkinTracing(request, response, next){
  // handle the callback request and record the trace
  var trace = zipkin.getTraceFromRequest(request, "ids-api", {address: config.externalIP, port: 80});

  if (trace){
    zipkin.sendAnnotationReceive(trace);
    zipkin.sendAnnotation(trace, 'request.headers',JSON.stringify(request.headers));
    trace.parentSpanId = trace.spanId;
    zipkin.sendAnnotation(trace, 'http.uri', request.url);

    var queryObj = urlLib.parse(request.url, true).query;
    Object.keys(queryObj).forEach( function(key){
      zipkin.sendAnnotation(trace, key, queryObj[key]);
    });
    request.zipkinTrace = trace;
  }

  response.on('after', function(request, response, route, error){
     var t = request.zipkinTrace;
     if (t) {
       zipkin.sendAnnotation(t, 'http.response.code',response.code);
       zipkin.sendAnnotationSend(t);
    }
  });

  return next();
}

Now my routes look like this:

restifyServer.use(zipkinTracing);
restifyServer.get({ path: "/api/v1/readings", version: ["1.0.0"]}, Reading.getReadings);

The problem is the response.on('after', is never fired. What am I doing wrong here?

Reading.getReadings looks like this:

makeHttpQuery(request, response, function(error, message) {
   ....
   response.send(message['data']['data']);
   return next();
}
有帮助吗?

解决方案

I was able to resolve this issue. In order to create a true filter I registered the handler function to the response.on('finish', handler) as you would do in Express. The alternate solution would be to place

restifyServer.on('after',  function(request, response){
  var t = request.zipkinTrace;
  if (t) {
    zipkin.sendAnnotation(t, 'http.response.code',response.code);
    zipkin.sendAnnotationSend(t);
  }
});

after the route to be filtered. I prefer the response.on('finish', handler). Any other solutions or interesting ways to create a filter for requests and responses?

其他提示

You can also add multiple handlers to the request. One handler will finish and pass on the the next one, much like a filter.

See: http://restify.com/#routing

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top