This module is for keeping those very common, none business logic related util methods.
Note
Since it seems bitbucket branch tag doesn't work for npm install, so we use master branch.
Memo
/* * Basically this function done the wrap job for Node.js async lib -> 'parallel' kinds API, more details can refer here: * http://www.sebastianseilund.com/nodejs-async-in-practice * * gprc hasn't support 'Promise' yet, and the api also cannot be promisified, so I fall back to async, sad! * */staticfuncWrapperForAsync(func){if(!func||typeoffunc!=='function'){thrownewError('Parameter must be a function.');}return(callback)=>{func.call(arguments,(err,res)=>{if(err){returncallback(err);}returncallback(null,res);});};}/* * Service id format: * serviceTag+pid+localIp:port */staticgenerateServiceId(serviceTag,pid,port){if(!serviceTag||typeofserviceTag!=='string'||serviceTag.trim().length===0){thrownewError('Invalid service tag provided.');}if(!Number.isInteger(pid)||!Number.isInteger(port)||pid<0||port<0){thrownewError('Invalid pid or port number provided.');}returnthis.getLocalIp().spread((address,family)=>{returnserviceTag+'+'+pid+'+'+address+':'+port;});}staticregisterToConsul(consulAgent,serviceTag,pid,port,checks){Promise.join(this.getLocalIp(),this.generateServiceId(serviceTag,pid,port),(ipInfo,serviceId)=>{const_registerToConsul=()=>{returnconsulAgent.agent.service.register({name: serviceId,id: serviceId,tags: [serviceTag,require('os').hostname()],address: ipInfo[0],port: port,checks: checks}).catch((err)=>{returnPromise.reject(err);});};setTimeout(()=>{retry(_registerToConsul,{interval: 100,max_tries: 65535});},Math.random()*1000);});}staticqueryServiceByTag(consulAgent,serviceTagArr){returnconsulAgent.catalog.service.list().then((res)=>{constserviceGroupedByTag=serviceTagArr.reduce((acc,curr)=>{acc[curr]=[];returnacc;},{});returnObject.keys(res).reduce((acc,curr)=>{constintersection=res[curr].filter((item)=>{returnserviceTagArr.indexOf(item)!==-1;});if(intersection.length){acc[intersection[0]].push(curr);}returnacc;},serviceGroupedByTag);});}staticgetLocalIp(){returnPromise.promisify(require('dns').lookup,{multiArgs: true})(require('os').hostname());}