Last active
January 13, 2020 05:20
-
-
Save endeepak/8d108b8bda7c0e7febdf2a6e4be4d695 to your computer and use it in GitHub Desktop.
NodeJS Request Log Tracing : SQS Consumer Wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cls = require('cls-hooked'); | |
const generate = require('nanoid/generate'); | |
const alphaNumeric = '0123456789abcdefghijklmnopqrstuvwxyz'; | |
const requestTracingNamespace = cls.createNamespace('request-tracing'); | |
//.. middleware: https://gist.github.com/endeepak/4b8a07abfdf07964ea85d9cde44e02b9 | |
const trace = async (tracingId, method) => { | |
requestTracingNamespace.run(async () => { | |
setTracingId(tracingId || generate(alphaNumeric, 10)); | |
await method(); | |
}); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { Consumer } = require('sqs-consumer'); | |
const { EventEmitter } = require('events'); | |
const requestTracing = require('request-tracing'); | |
// Wrapper around sqs-consumer library available in npm | |
class AdvancedSqsConsumer extends EventEmitter { | |
constructor(options, sqs) { | |
super(); | |
const extendedOptions = Object.assign({}, options, { | |
handleMessage: this._createAdvancedHandleMessage(options.handleMessage) | |
}); | |
this.consumer = Consumer.create(extendedOptions, sqs); | |
// ... | |
} | |
_createAdvancedHandleMessage(basichandleMessage) { | |
return async (message) => { | |
const tracingId = this._getTracingId(message); | |
await requestTracing.trace(tracingId, async () => { // Trace method implementation shown in request-tracing-trace-method.js below | |
// ... | |
return await basichandleMessage(message); | |
}); | |
}; | |
} | |
_getTracingId(message) { | |
// Error handling code omitted for berwity | |
const messageAttributes = JSON.parse(message.Body).MessageAttributes || {}; | |
const tracingIdAttribute = messageAttributes['X-Tracing-Id'] || {}; | |
return tracingIdAttribute['Value']; | |
} | |
start() { | |
this.consumer.start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment