UNPKG

@iamnnort/request

Version:

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

2 lines 8.93 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }var x=Object.defineProperty;var n=(r,e)=>x(r,"name",{value:e,configurable:!0});var _pino = require('pino'); var _pino2 = _interopRequireDefault(_pino);var _http = require('@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")}constructor(e={}){this.config={name:"",level:c.INFO,...e};let t=new _http.HttpMessageFormatter;this.logger=_pino2.default.call(void 0, {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 (0, _http.HttpMessageBuilder)({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 (0, _http.HttpMessageBuilder)({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 (0, _http.HttpMessageBuilder)({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()>=_http.HttpStatuses.INTERNAL_SERVER_ERROR?this.logger.error(i,g):this.logger.warn(i,g)}makeResponse(e){return new (0, _http.HttpMessageBuilder)({response:e}).makeResponse()}makeErrorResponse(e){return new (0, _http.HttpMessageBuilder)({error:e}).makeResponse()}};var _qs = require('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")}constructor(e={}){this.config={arrayFormat:C.BRACKETS,...e}}getConfig(){return{serialize:n(e=>_qs.stringify.call(void 0, e,{arrayFormat:this.config.arrayFormat,skipNulls:!0}),"serialize")}}};var _crypto = require('crypto');var b=class{static{n(this,"Signer")}constructor(e={}){this.config={secretKey:"",header:"x-signature",...e}}sign(e){let t=Math.floor(Date.now()/1e3),s=`${t}.${e}`,o=_crypto.createHmac.call(void 0, "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):"")}:{}}};var _axios = require('axios'); var _axios2 = _interopRequireDefault(_axios);var k=class{static{n(this,"RequestBuilder")}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=>_optionalChain([u, 'optionalAccess', _ => _.toString, 'call', _2 => _2()])),i=s.some(u=>_optionalChain([u, 'optionalAccess', _3 => _3.includes, 'call', _4 => _4("https")]))?"https":"http",a=s.filter(u=>u).map(u=>_optionalChain([u, 'optionalAccess', _5 => _5.replace, 'call', _6 => _6(/^(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===_http.HttpMethods.GET?this:this.requestConfig.urlencoded?(this.config={...this.config,data:_qs.stringify.call(void 0, 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")}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 _axios2.default.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 _optionalChain([a, 'access', _7 => _7.response, 'optionalAccess', _8 => _8.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,!_optionalChain([l, 'access', _9 => _9.data, 'optionalAccess', _10 => _10.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:_http.HttpMethods.GET})}bulkSearch(e={}){return this.bulkCommon({...e,method:_http.HttpMethods.GET})}async searchOne(e={}){return((await this.common({...e,method:_http.HttpMethods.GET,params:{pageSize:1,extended:!0,strict:!0,...e.params}})).data||[])[0]}get(e,t={}){return this.common({...t,method:_http.HttpMethods.GET,url:e})}create(e){return this.common({...e,method:_http.HttpMethods.POST})}bulkCreate(e){return this.common({...e,method:_http.HttpMethods.POST,url:"/bulk",data:{bulk:e.data}})}update(e,t){return this.common({...t,method:_http.HttpMethods.PUT,url:e})}bulkUpdate(e){return this.common({...e,method:_http.HttpMethods.PUT,url:"/bulk",data:{bulk:e.data}})}remove(e,t={}){return this.common({...t,method:_http.HttpMethods.DELETE,url:e})}bulkRemove(e={}){return this.common({...e,method:_http.HttpMethods.DELETE,url:"/bulk"})}};var R=class{static{n(this,"RequestHelper")}static sleep(e){return new Promise(t=>{setTimeout(t,e*1e3)})}};exports.HttpMethods = _http.HttpMethods; exports.HttpStatuses = _http.HttpStatuses; exports.Logger = p; exports.LoggerLevels = c; exports.RequestDataSource = q; exports.RequestHelper = R; exports.Serializer = d; exports.SerializerArrayFormats = C; exports.Signer = b; //# sourceMappingURL=index.js.map