UNPKG

@interopio/gateway

Version:

[![npm version](https://img.shields.io/npm/v/@interopio/gateway.svg)](https://www.npmjs.com/package/@interopio/gateway)

3 lines (2 loc) 2.71 kB
async function c(e){e.bodyUsed||await e.blob()}var p=new Set([200,201,202]);function b({user:e,password:t}){let i=`${e}:${t}`;return typeof process<"u"?Buffer.from(i).toString("base64"):globalThis.btoa(i)}var S="rest";async function w(e,{logger:t,fetch:i,headers:r,timeout:d}){t.enabledFor("debug")&&t.debug(`sending initial GET to do auth dance. url: ${e}`);try{let n=await i(e,f(d,r));if(n.ok){if(t.info("initial GET request completed successfully."),t.enabledFor("debug")){let o=n.headers.getSetCookie();o.length>0&&t.enabledFor("debug")&&t.debug(`will set following cookies: ${o}`)}}else t.warn(`initial GET request did not completed successfully. Status: ${n.status}`)}catch(n){throw t.warn("error executing initial GET request",n),n}}async function y(e,t){if(!h(e)&&e!==!1){let i=new t.URL(t.endpoint);e?.path&&(i.pathname=e.path),await w(i,t)}t.logger.info("rest publisher started")}function m({logger:e}){e.info("rest publisher stopped")}function f(e,t,i){return i?{method:"POST",redirect:"manual",credentials:"include",signal:AbortSignal.timeout(e),headers:t,body:JSON.stringify(i)}:{method:"GET",redirect:"follow",credentials:"include",signal:AbortSignal.timeout(e),headers:t}}async function g(e,t,{endpoint:i,headers:r,timeout:d,fetch:n,logger:o}){let u=f(d,r,e);try{let s=await n(i,u);if(s.redirected){o.info("Redirect detected will do GET to allow auth dance and re-POST"),await c(s);let a=await n(i,f(d,r));await c(a),a.ok?s=await n(i,u):o.error(`GET failed with status: ${a.status} headers: ${JSON.stringify(a.headers)}`)}await c(s),t.prev=t.now,t.now=p.has(s.status),t.prev&&!t.now?o.error(`Unable to publish metrics. status ${s.status} headers: ${JSON.stringify(s.headers)} msg: ${JSON.stringify(e)}`):t.now&&!t.prev&&o.info("Publishing metrics.")}catch(s){let a=t.now;t.prev=t.now,t.now=!1,a&&o.error(`Unable to publish metrics. msg ${JSON.stringify(e)}`,s)}}function h(e){return e!==void 0&&e&&e.user!==void 0}async function C(e,t){let i=e.endpoint,r=e.timeout??1e3,d=e.Headers??globalThis.Headers??Headers,n=new d(e.headers);n.has("Content-Type")||n.set("Content-Type","application/json"),n.has("User-Agent")||n.set("User-Agent",e["user-agent"]??"metrics-rest/0.2.x"),h(e.authentication)&&!n.has("Authorization")&&n.set("Authorization",`Basic ${b(e.authentication)}`);let o=e.fetch??globalThis.fetch??fetch,u=e.URL??globalThis.URL??URL,s={prev:!1,now:!0},a={endpoint:i,headers:n,timeout:r,fetch:o,URL:u,logger:t};return async l=>{switch(t.enabledFor("debug")&&t.debug(`handling publish request: ${JSON.stringify(l)}`),l){case"start":{await y(e.authentication,a);break}case"stop":{m(a);break}default:{await g(l,s,a);break}}}}export{C as create,S as name}; //# sourceMappingURL=rest.js.map