Advertisement
Guest User

Untitled

a guest
Jun 19th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.98 KB | None | 0 0
  1. const correlator = require(`@samples/correlation-id`);
  2.  
  3. function rebindOnFinished(container) {
  4. if (container.__onFinished) {
  5. // __onFinished is used by package (on-finished) that are used by koa itself (Application.handleRequest)
  6. // and morgan to run tasks once response ended
  7. // lib creates 1 field to store all on finish listeners in queue
  8. container.__onFinished = correlator.bind(container.__onFinished);
  9. }
  10. }
  11.  
  12. async function correlationIdMiddleware(ctx, next) {
  13. correlator.bindEmitter(ctx.req);
  14. correlator.bindEmitter(ctx.res);
  15. correlator.bindEmitter(ctx.req.socket);
  16. await new Promise((resolve, reject) => {
  17. correlator.withId(() => {
  18. rebindOnFinished(ctx.res);
  19.  
  20. const correlationId = correlator.getId();
  21. ctx.set(`x-correlation-id`, correlationId);
  22. next().then(resolve).catch(reject);
  23. }, ctx.request.get(`x-correlation-id`));
  24. });
  25. }
  26.  
  27. module.exports = {correlationIdMiddleware};
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement