UNPKG

@iamnnort/request

Version:

Request handler for Node.js - Fast - Interactive - Simple

2 lines 7.63 kB
var x=Object.defineProperty;var n=(r,e)=>x(r,"name",{value:e,configurable:!0});import T from"pino";import{HttpMessageBuilder as f,HttpMessageFormatter as E,HttpStatuses as w}from"@iamnnort/config/http";import{HttpMethods as j,HttpStatuses as A}from"@iamnnort/config/http";var c=(function(r){return r.FATAL="fatal",r.ERROR="error",r.WARN="warn",r.INFO="info",r.DEBUG="debug",r.TRACE="trace",r})({});var p=class{static{n(this,"Logger")}logger;config;constructor(e={}){this.config={name:"",level:c.INFO,...e};let t=new E;this.logger=T({name:this.config.name,level:this.config.level,timestamp:!1},t.makeLogStream())}trace(e){this.logger.trace(e)}debug(e){this.logger.debug(e)}info(e){this.logger.info(e)}warn(e){this.logger.warn(e)}error(e){this.logger.error(e)}fatal(e){this.logger.fatal(e)}logRequest(e){let t=new f({request:e}),s=t.makeMethodText().makeUrlText().build(),o={},i=t.makeRequestDataObj();Object.keys(i).length>0&&(o.request=i),this.logger.debug(o,s)}logResponse(e,t){let s=new f({response:e,duration:t});s.makeMethodText().makeUrlText().makeStatusText();let o={},i=s.makeRequestDataObj();if(Object.keys(i).length>0&&(o.request=i),[c.TRACE,c.DEBUG].includes(this.config.level)){let g=s.makeResponseDataObj();Object.keys(g).length>0&&(o.response=g)}let a=s.makeDurationText().build();this.logger.info(o,a)}logError(e,t,s){let o=new f({request:e,error:t,duration:s});o.makeMethodText().makeUrlText().makeStatusText();let i={},a=o.makeRequestDataObj();if(Object.keys(a).length>0&&(i.request=a),[c.TRACE,c.DEBUG].includes(this.config.level)){let m=o.makeResponseDataObj();Object.keys(m).length>0&&(i.response=m)}let g=o.makeDurationText().build();o.makeStatus()>=w.INTERNAL_SERVER_ERROR?this.logger.error(i,g):this.logger.warn(i,g)}makeResponse(e){return new f({response:e}).makeResponse()}makeErrorResponse(e){return new f({error:e}).makeResponse()}};import{stringify as y}from"qs";var C=(function(r){return r.INDICES="indices",r.BRACKETS="brackets",r.REPEAT="repeat",r.COMMA="comma",r})({});var d=class{static{n(this,"Serializer")}config;constructor(e={}){this.config={arrayFormat:C.BRACKETS,...e}}getConfig(){return{serialize:n(e=>y(e,{arrayFormat:this.config.arrayFormat,skipNulls:!0}),"serialize")}}};import{createHmac as D}from"crypto";var b=class{static{n(this,"Signer")}config;constructor(e={}){this.config={secretKey:"",header:"x-signature",...e}}sign(e){let t=Math.floor(Date.now()/1e3),s=`${t}.${e}`,o=D("sha256",this.config.secretKey).update(s,"utf8").digest("hex");return`t=${t},v1=${o}`}getConfig(e){return this.config.secretKey?{[this.config.header]:this.sign(e?JSON.stringify(e):"")}:{}}};import M from"axios";import{HttpMethods as h}from"@iamnnort/config/http";import{stringify as S}from"qs";import{HttpMethods as P}from"@iamnnort/config/http";var k=class{static{n(this,"RequestBuilder")}baseRequestConfig;requestConfig;config;signer;serializer;constructor(e){this.baseRequestConfig=e.baseRequestConfig,this.requestConfig=e.requestConfig,this.config={timeout:e.requestConfig.timeout||e.baseRequestConfig.timeout,responseType:e.requestConfig.responseType||e.baseRequestConfig.responseType,headers:{Accept:"application/json","Content-Type":"application/json",...e.baseRequestConfig.headers,...e.requestConfig.headers}},this.signer=new b(this.baseRequestConfig.signer),this.serializer=new d(this.baseRequestConfig.serializer)}makeContentType(){return this.requestConfig.multipart?(this.config={...this.config,headers:{...this.config.headers,"Content-Type":"multipart/form-data"}},this):this.requestConfig.urlencoded?(this.config={...this.config,headers:{...this.config.headers,"Content-Type":"application/x-www-form-urlencoded"}},this):this.requestConfig.xml?(this.config={...this.config,headers:{...this.config.headers,"Content-Type":"text/xml"}},this):this}makeAuth(){let e=this.requestConfig.auth||this.baseRequestConfig.auth;if(e)return this.config={...this.config,auth:e},this;let t=this.requestConfig.bearerToken||this.baseRequestConfig.bearerToken;if(t)return this.config={...this.config,headers:{...this.config.headers,Authorization:`Bearer ${t}`}},this;let s=this.requestConfig.apiKey||this.baseRequestConfig.apiKey;return s?(this.config={...this.config,headers:{...this.config.headers,"x-api-key":s}},this):this}makeUrl(){let e=this.requestConfig.baseUrlMap||this.baseRequestConfig.baseUrlMap,t=this.requestConfig.baseUrlName||this.baseRequestConfig.baseUrlName,s=[e&&t?e[t]:this.baseRequestConfig.baseUrl,this.baseRequestConfig.url,...this.baseRequestConfig.urlParts||[],this.requestConfig.baseUrl,this.requestConfig.url,...this.requestConfig.urlParts||[]].map(u=>u?.toString()),i=s.some(u=>u?.includes("https"))?"https":"http",a=s.filter(u=>u).map(u=>u?.replace(/^(https?:\/\/|\/)?(.*?)(\/?)$/,"$2")),g=`${i}://${a.join("/")}`;return this.config={...this.config,url:g},this}makeMethod(){return this.config={...this.config,method:this.requestConfig.method},this}makeData(){return this.requestConfig.method===P.GET?this:this.requestConfig.urlencoded?(this.config={...this.config,data:S(this.requestConfig.data)},this):(this.config={...this.config,data:this.requestConfig.data},this)}makeParams(){return this.config={...this.config,params:this.requestConfig.params},this}makeSignature(){return this.config={...this.config,headers:{...this.config.headers,...this.signer.getConfig(this.config.data)}},this}makeSerializer(){return this.config={...this.config,paramsSerializer:this.serializer.getConfig()},this}build(){return this.config}};var q=class{static{n(this,"RequestDataSource")}baseRequestConfig;logger;constructor(e){this.baseRequestConfig=e,this.logger=new p(this.baseRequestConfig.logger)}common(e,t={}){let o=new k({baseRequestConfig:this.baseRequestConfig,requestConfig:e}).makeContentType().makeAuth().makeUrl().makeMethod().makeParams().makeData().makeSignature().makeSerializer().build();this.logger.logRequest(o);let i=Date.now();return M.request(o).then(a=>(this.logger.logResponse(a,Date.now()-i),t.raw?this.logger.makeResponse(a):a.data)).catch(a=>{if(this.logger.logError(o,a,Date.now()-i),t.raw)return this.logger.makeErrorResponse(a);throw a.response?.data||a.response||new Error(a.message)})}async*bulkCommon(e,t={}){let{page:s,pageSize:o,bulkSize:i,...a}=e.params||{},g={page:s||1,pageSize:o||30},u=i?g.page-1+i:null,m={total:0,currentPage:0,lastPage:0,from:0,to:0,pageSize:0};do{let l=await this.common({...e,params:{...g,...a}});if(m=l.pagination,!l.data?.length)return;t.raw?yield l:yield l.data,g.page+=1}while(m.currentPage!==m.lastPage&&m.currentPage!==u);m.currentPage!==m.lastPage&&t.bulkCallback&&await t.bulkCallback(g.page)}search(e={}){return this.common({...e,method:h.GET})}bulkSearch(e={}){return this.bulkCommon({...e,method:h.GET})}async searchOne(e={}){return((await this.common({...e,method:h.GET,params:{pageSize:1,extended:!0,strict:!0,...e.params}})).data||[])[0]}get(e,t={}){return this.common({...t,method:h.GET,url:e})}create(e){return this.common({...e,method:h.POST})}bulkCreate(e){return this.common({...e,method:h.POST,url:"/bulk",data:{bulk:e.data}})}update(e,t){return this.common({...t,method:h.PUT,url:e})}bulkUpdate(e){return this.common({...e,method:h.PUT,url:"/bulk",data:{bulk:e.data}})}remove(e,t={}){return this.common({...t,method:h.DELETE,url:e})}bulkRemove(e={}){return this.common({...e,method:h.DELETE,url:"/bulk"})}};var R=class{static{n(this,"RequestHelper")}static sleep(e){return new Promise(t=>{setTimeout(t,e*1e3)})}};export{j as HttpMethods,A as HttpStatuses,p as Logger,c as LoggerLevels,q as RequestDataSource,R as RequestHelper,d as Serializer,C as SerializerArrayFormats,b as Signer}; //# sourceMappingURL=index.mjs.map