Create correlation id instance
const{createCorrelationId}=require(`@vizydrop/correlation-id`);constcorrelationId=createCorrelationId();Integrate with @vizydrop/logger
const{createLogger}=require(`@vizydrop/logger`);constlogger=createLogger({correlationId: {enabled: true,getCorrelationId: ()=>correlationId.correlator.getId(),emptyValue: `nocorrelation`,},});Register middleware. Support koa and express
// koaapp.use(correlationId.koaMiddleware);// expressapp.use(correlationId.expressMiddleware);Enhance request so each request will contain correlation id http header.
constrequest=require(`request`);constcorrelatedRequest=correlationId.enhanceRequest(request);correlatedRequest.get(`http://anotherservice:10020/data`);Enhance http proxy so each proxied request will contain correlation id http header.
consthttpProxy=require(`http-proxy`);constproxy=httpProxy.createProxyServer({target: `http://anotherservice:10020/`});correlationId.enhanceHttpProxy(proxy);Run jobs. Jobs usually do not go through express/koa middleware so correlation id should be generated manually.
functionjobTask(){}functionrunJob(){correlationId.correlator.withId(correlator.generateDefaultId(),()=>{jobTask();});}Custom settings can be passed as an object to createCorrelationId function.
generateDefaultId- function that should return new correlation id. By defaultuuidis used.namespaceName- namespace for cls hook. Default value iscorrelation-id-namespacehttpHeaderParamName- name of http header that contains correlation id value. Default value isx-correlationid
expressMiddleware- express middleware that runs next middlewares in scope of correlation id async hookkoaMiddleware- koa middleware that runs next middlewares in scope of correlation id async hookenhanceHttpRequest- takes request and return new request instance that adds correlation id header by defaultenhanceHttpProxy- register additional listener that adds correlation id header by defaultcorrelator.getId()- returns current correlation idcorrelator.withId(id, fn)- run function and all subsequent function with specified correlation idcorrelator.bindEmitter()- see https://github.com/jeff-lewis/cls-hooked#namespacebindemitteremittercorrelator.bind()- see https://github.com/jeff-lewis/cls-hooked#namespacebindemitteremittercorrelator.generateId()- generates new correlation id
- does not work well with
bluebird.promisifyAll. Alternative solution is to explicitly promisify using native promise
constredis=require(`redis`);constutil=require(`util`);constclient=redis.createClient();client.setAsync=util.promisify(client.set).bind(client);client.getAsync=util.promisify(client.get).bind(client);- does not work well with
mongoosecallbacks. Alternative solution is to use promisified functions.
constmongoose=require(`mongooose`);mongoose.Promise=global.Promise;EntityModel.find({name: `name`}).then((value)=>{// do something});