UNPKG

@urql/exchange-auth

Version:

An exchange for managing authentication and token refresh in urql

3 lines (2 loc) 1.89 kB
Object.defineProperty(exports,"__esModule",{value:!0});var e=require("wonka"),t=require("@urql/core"),n=(e,n)=>t.makeOperation(e.kind,e,{...e.context,authAttempt:n});exports.authExchange=function(r){return({client:o,forward:a})=>{var c,i=new Set,u=e.makeSubject(),s=e.makeSubject(),h=new Map;function p(){c=void 0;var e=h;h=new Map,e.forEach(u.next)}function d(e){c=void 0;var n=h;h=new Map,n.forEach((n=>{s.next(t.makeErrorResult(n,e))}))}var f=null;return l=>{function x(){c=Promise.resolve().then((()=>r({mutate(n,r,a){var c=o.createRequestOperation("mutation",t.createRequest(n,r),a);return e.toPromise(e.take(1)(e.filter((e=>e.operation.key===c.key&&c.context._instance===e.operation.context._instance))(e.onStart((()=>{var e=m(c);i.add(e.context._instance),u.next(e)}))(A))))},appendHeaders(e,n){var r="function"==typeof e.context.fetchOptions?e.context.fetchOptions():e.context.fetchOptions||{};return t.makeOperation(e.kind,e,{...e.context,fetchOptions:{...r,headers:{...r.headers,...n}}})}}))).then((e=>{e&&(f=e),p()})).catch((e=>{d(e)}))}function k(e){h.set(e.key,n(e,!0)),f&&!c&&(c=f.refreshAuth().then(p).catch(d))}function m(e){return f?f.addAuthToOperation(e):e}x();var v=e.filter(Boolean)(e.map((e=>"teardown"===e.kind?(h.delete(e.key),e):e.context._instance&&i.has(e.context._instance)?e:e.context.authAttempt?m(e):c||!f?(c||x(),h.has(e.key)||h.set(e.key,n(e,!1)),null):function(e){return!e.context.authAttempt&&f&&f.willAuthError&&f.willAuthError(e)}(e)?(k(e),null):m(n(e,!1))))(e.merge([u.source,l]))),A=a(v);return e.merge([s.source,e.filter((e=>!i.has(e.operation.context._instance)&&e.error&&function(e){return f&&f.didAuthError&&f.didAuthError(e.error,e.operation)}(e)&&!e.operation.context.authAttempt?(k(e.operation),!1):(i.has(e.operation.context._instance)&&i.delete(e.operation.context._instance),!0)))(A)])}}}; //# sourceMappingURL=urql-exchange-auth.min.js.map