Skip to content

Instantly share code, notes, and snippets.

@damiancipolat
Created August 18, 2022 03:14
Show Gist options
  • Save damiancipolat/141a5e571a8ea601dec6381ac1219738 to your computer and use it in GitHub Desktop.
Save damiancipolat/141a5e571a8ea601dec6381ac1219738 to your computer and use it in GitHub Desktop.
A hapi js distributed tracing plugin
const cls = require('cls-hooked');
const { v4: uuidV4 } = require('uuid');
// generate a unique value for namespace
const name = 'settle-context';
const nsId = `${name}:${uuidV4()}`;
const ns = cls.createNamespace(nsId);
const correlationIdKey = 'x-correlation-id';
const getCorrelationId = () => ns.get(correlationIdKey);
const register = async (server) => {
server.ext('onRequest', (request, h) => {
const clsCtx = ns.createContext();
ns.enter(clsCtx);
const requestId = request.headers[correlationIdKey.toLowerCase()] || uuidV4();
console.log('xxxxx',requestId);
ns.set(correlationIdKey, requestId);
return h.continue;
});
}
const plugin = {
name,
once: true,
register
};
export default {
plugin,
getCorrelationId
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment