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