New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

graphql-hooks

Package Overview
Dependencies
Maintainers
9
Versions
89
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

graphql-hooks - npm Package Compare versions

Comparing version 6.0.3 to 6.0.4

8

dist/graphql-hooks.js

@@ -818,2 +818,5 @@ (function (global, factory) {

case actionTypes.RESET_STATE:
if (state.loading) {
return state;
}
return action.initialState;

@@ -995,3 +998,6 @@ case actionTypes.LOADING:

return () => {
client.mutationsEmitter.off(Events.DATA_INVALIDATED, dataInvalidatedCallback);
client.mutationsEmitter.off(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
client.mutationsEmitter.off(Events.DATA_UPDATED, dataUpdatedCallback);

@@ -998,0 +1004,0 @@ };

2

dist/graphql-hooks.min.js

@@ -1,1 +0,1 @@

!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("events")):"function"==typeof define&&define.amd?define(["exports","react","events"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GraphQLHooks={},e.React,e.EventEmitter)}(this,(function(e,t,r){"use strict";function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(t),i=o(r);const s=n.default.createContext(null);s.displayName="ClientContext";var a=function(e){return"undefined"!=typeof File&&e instanceof File||"undefined"!=typeof Blob&&e instanceof Blob||e instanceof class{constructor({uri:e,name:t,type:r}){this.uri=e,this.name=t,this.type=r}}};const u=e=>a(e)||null!==e&&"object"==typeof e&&"function"==typeof e.pipe||null!==e&&"object"==typeof e&&"function"==typeof e.stream;function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,o=Array(t);t>r;r++)o[r]=e[r];return o}function l(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return c(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var o=0;return function(){return e.length>o?{done:!1,value:e[o++]}:{done:!0}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var f=function(){function e(e){var t=this;0===e.length&&e.push((function(e,t){return t()}));for(var r,o=function(){var e,o=r.value;if("function"!=typeof o)throw Error("GraphQLClient Middleware: middleware has to be of type `function`");t.run=(e=t.run,function(r,n){e(r,(function(){o.call(t,r,n.bind.call(n,null,r))}))})},n=l(e);!(r=n()).done;)o()}return e.prototype.run=function(e,t){t.apply(this,e)},e}();var h=(e=>(e.DATA_INVALIDATED="DATA_INVALIDATED",e.DATA_UPDATED="DATA_UPDATED",e))(h||{}),p=Object.defineProperty,d=Object.defineProperties,y=Object.getOwnPropertyDescriptors,b=Object.getOwnPropertySymbols,E=Object.prototype.hasOwnProperty,m=Object.prototype.propertyIsEnumerable,g=(e,t,r)=>t in e?p(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,v=(e,t)=>{for(var r in t||(t={}))E.call(t,r)&&g(e,r,t[r]);if(b)for(var r of b(t))m.call(t,r)&&g(e,r,t[r]);return e};class O{constructor(e){if(!e)throw Error("GraphQLClient: config is required as first parameter");this.fullWsTransport=e.fullWsTransport,this.subscriptionClient="function"==typeof e.subscriptionClient?e.subscriptionClient():e.subscriptionClient,this.verifyConfig(e),this.cache=e.cache,this.headers=e.headers||{},this.ssrMode=e.ssrMode,this.ssrPromises=[],this.url=e.url,this.fetch=e.fetch||("undefined"!=typeof fetch&&fetch?fetch.bind(void 0):void 0),this.fetchOptions=e.fetchOptions||{},this.FormData=e.FormData||("undefined"!=typeof FormData?FormData:void 0),this.logErrors=void 0===e.logErrors||e.logErrors,this.onError=e.onError,this.useGETForQueries=!0===e.useGETForQueries,this.middleware=new f(e.middleware||[]),this.mutationsEmitter=new i.default}verifyConfig(e){if(!e.url){if(!this.fullWsTransport)throw Error("GraphQLClient: config.url is required");if(!this.subscriptionClient)throw Error("GraphQLClient: subscriptionClient is required")}if(e.fetch&&"function"!=typeof e.fetch)throw Error("GraphQLClient: config.fetch must be a function");if(("undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement||e.ssrMode)&&!e.fetch&&"function"!=typeof fetch)throw Error("GraphQLClient: fetch must be polyfilled or passed in new GraphQLClient({ fetch })");if(e.ssrMode&&!e.cache)throw Error("GraphQLClient: config.cache is required when in ssrMode")}setHeader(e,t){return this.headers[e]=t,this}setHeaders(e){return this.headers=e,this}removeHeader(e){return delete this.headers[e],this}logErrorResult({result:e,operation:t}){console.error("GraphQL Hooks Error"),console.groupCollapsed("---\x3e Full Error Details"),console.groupCollapsed("Operation:"),console.log(t),console.groupEnd();const r=e.error;r&&(r.fetchError&&(console.groupCollapsed("FETCH ERROR:"),console.log(r.fetchError),console.groupEnd()),r.httpError&&(console.groupCollapsed("HTTP ERROR:"),console.log(r.httpError),console.groupEnd()),r.graphQLErrors&&r.graphQLErrors.length>0&&(console.groupCollapsed("GRAPHQL ERROR:"),r.graphQLErrors.forEach((e=>console.log(e))),console.groupEnd())),console.groupEnd()}generateResult({fetchError:e,httpError:t,graphQLErrors:r,data:o}){return!!(r&&r.length>0||e||t)?{data:o,error:{fetchError:e,httpError:t,graphQLErrors:r}}:{data:o}}getCacheKey(e,t={}){return{operation:e,fetchOptions:v(v({},this.fetchOptions),t.fetchOptionsOverrides)}}getCache(e){const t=this.cache?this.cache.get(e):null;if(t)return t}saveCache(e,t){this.cache&&this.cache.set(e,t)}removeCache(e){var t;null==(t=this.cache)||t.delete(e)}getFetchOptions(e,t={}){const r=v(v({method:"POST",headers:v({},this.headers)},this.fetchOptions),t);if("GET"===r.method)return r;const{clone:o,files:n}=function(e,t="",r=a){const o=new Map,n=new Map;return{clone:function e(t,i,s){let a=t;if(r(t)){a=null;const e=o.get(t);e?e.push(i):o.set(t,[i])}else{const r=Array.isArray(t)||"undefined"!=typeof FileList&&t instanceof FileList,o=t&&t.constructor===Object;if(r||o){const o=n.has(t);if(o?a=n.get(t):(a=r?[]:{},n.set(t,a)),!s.has(t)){const n=i?i+".":"",u=new Set(s).add(t);if(r){let r=0;for(const i of t){const t=e(i,n+r++,u);o||a.push(t)}}else for(const r in t){const i=e(t[r],n+r,u);o||(a[r]=i)}}}}return a}(e,t,new Set),files:o}}(e,"",u),i=JSON.stringify(o);if(n.size){if(!this.FormData)throw Error("GraphQLClient: FormData must be polyfilled or passed in new GraphQLClient({ FormData })");const e=new this.FormData;e.append("operations",i);const t={};let o=0;n.forEach((e=>{t[++o]=e})),e.append("map",JSON.stringify(t)),o=0,n.forEach(((t,r)=>{e.append(""+ ++o,r,r.name)})),r.body=e}else r.headers["Content-Type"]="application/json",r.body=i;return r}request(e,t){const r=[],o=e=>r.push(e);return new Promise(((n,i)=>this.middleware.run({operation:e,client:this,addResponseHook:o,resolve:n,reject:i},(({operation:e})=>{const o=e=>{return r.length>0?(t=r,e=>t.reduce(((e,t)=>e.then(t)),Promise.resolve(e)))(e):e;var t};return this.fullWsTransport?this.requestViaWS(e).then(o).then(n).catch(i):this.url?this.requestViaHttp(e,t).then(o).then(n).catch(i):void i(Error("GraphQLClient: config.url is required"))}))))}requestViaHttp(e,t={}){let r=this.url;const o=this.getFetchOptions(e,t.fetchOptionsOverrides);if("GET"===o.method){r=r+"?"+Object.entries(e).filter((([,e])=>!!e)).map((([e,t])=>("variables"!==e&&"extensions"!==e||(t=JSON.stringify(t)),`${e}=${encodeURIComponent(t)}`))).join("&")}return this.fetch(r,o).then((e=>e.ok?e.json().then((({errors:r,data:o})=>this.generateResult({graphQLErrors:r,data:"function"==typeof t.responseReducer&&t.responseReducer(o,e)||o}))):e.text().then((t=>{const{status:r,statusText:o}=e;return this.generateResult({httpError:{status:r,statusText:o,body:t}})})))).catch((e=>this.generateResult({fetchError:e}))).then((t=>(t.error&&(this.logErrors&&this.logErrorResult({result:t,operation:e}),this.onError&&this.onError({result:t,operation:e})),t)))}requestViaWS(e){return new Promise(((t,r)=>{let o;try{const n=this.createSubscription(e).subscribe({next:e=>{o=e},error:r,complete:()=>{n.unsubscribe(),t(o)}})}catch(e){r(e)}}))}createSubscription(e){if(!this.subscriptionClient)throw Error("No SubscriptionClient! Please set in the constructor.");return"function"==typeof this.subscriptionClient.subscribe?{subscribe:t=>({unsubscribe:this.subscriptionClient.subscribe(e,t)})}:this.subscriptionClient.request(e)}invalidateQuery(e){const t="string"==typeof e?{query:e}:e,r=this.getCacheKey(t);this.cache&&r&&(this.removeCache(r),this.request(t).then((e=>{this.mutationsEmitter.emit(h.DATA_INVALIDATED,e)})).catch((e=>console.error(e))))}setQueryData(e,t){const r=this.getCacheKey("string"==typeof e?{query:e}:e);if(this.cache&&r){const e=this.cache.get(r),i=(o=v({},e),n={data:t(e.data||null)},d(o,y(n)));this.saveCache(r,i),this.mutationsEmitter.emit(h.DATA_UPDATED,i)}var o,n}}class C{constructor(e){this.fetchError=e.fetchError,this.httpError=e.httpError,this.graphQLErrors=e.graphQLErrors}}var w=Object.defineProperty,D=Object.getOwnPropertySymbols,A=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable,T=(e,t,r)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var L=Object.prototype.hasOwnProperty;function S(e,t,r){for(r of e.keys())if(P(r,t))return r}function P(e,t){var r,o,n;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return""+e==""+t;if(r===Array){if((o=e.length)===t.length)for(;o--&&P(e[o],t[o]););return-1===o}if(r===Set){if(e.size!==t.size)return!1;for(o of e){if((n=o)&&"object"==typeof n&&!(n=S(t,n)))return!1;if(!t.has(n))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(o of e){if((n=o[0])&&"object"==typeof n&&!(n=S(t,n)))return!1;if(!P(o[1],t.get(n)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((o=e.byteLength)===t.byteLength)for(;o--&&e.getInt8(o)===t.getInt8(o););return-1===o}if(ArrayBuffer.isView(e)){if((o=e.byteLength)===t.byteLength)for(;o--&&e[o]===t[o];);return-1===o}if(!r||"object"==typeof e){for(r in o=0,e){if(L.call(e,r)&&++o&&!L.call(t,r))return!1;if(!(r in t)||!P(e[r],t[r]))return!1}return Object.keys(t).length===o}}return e!=e&&t!=t}var Q=Object.defineProperty,q=Object.defineProperties,R=Object.getOwnPropertyDescriptors,M=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,x=(e,t,r)=>t in e?Q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t)=>{for(var r in t||(t={}))G.call(t,r)&&x(e,r,t[r]);if(M)for(var r of M(t))I.call(t,r)&&x(e,r,t[r]);return e},F=(e,t)=>q(e,R(t));const N="RESET_STATE",H="LOADING",_="CACHE_HIT",U="REQUEST_RESULT";function V(e,t){switch(t.type){case N:return t.initialState;case H:return e.error?F(k({},t.initialState),{data:e.data,loading:!0}):e.loading?e:F(k({},e),{loading:!0});case _:return e.cacheHit&&!t.resetState?e:F(k({},t.result),{cacheHit:!0,loading:!1});case U:return F(k({},t.result),{data:e.data&&t.result.data&&t.updateData?t.updateData(e.data,t.result.data):t.result.data,cacheHit:!1,loading:!1});default:return e}}function K(e,t={}){if("string"!=typeof e)throw Error("Your query must be a string. If you are using the `gql` template literal from graphql-tag, remove it from your query.");const r=n.default.useContext(s),o=t.client||r;if(null==o)throw Error("A client must be provided in order to use the useClientRequest hook.");const i=n.default.useRef(!0),a=n.default.useRef(null),u={query:e,variables:t.variables,operationName:t.operationName,persisted:t.persisted};(t.persisted||o.useGETForQueries&&!t.isMutation)&&(t.fetchOptionsOverrides=F(k({},t.fetchOptionsOverrides),{method:"GET"}));const c=o.getCacheKey(u,t),l=t.isMutation||t.isManual||t.skip,f=!t.skipCache&&o.cache&&c?o.cache.get(c):null,p=F(k({},f),{cacheHit:!!f,loading:!l&&!f}),[d,y]=n.default.useReducer(V,p),b=JSON.stringify(c);n.default.useEffect((()=>{t.updateData||y({type:N,initialState:p})}),[b]),n.default.useEffect((()=>(i.current=!0,()=>{i.current=!1})),[]);const E=function(e,t){const r=n.default.useRef();return P(t,r.current)||(r.current=t),n.default.useCallback(e,r.current)}((r=>{const n=k(k({},t),r),s=F(k({},u),{variables:n.variables,operationName:n.operationName});if(!i.current)return Promise.resolve({error:{fetchError:Error("fetchData should not be called after hook unmounted")},loading:!1,cacheHit:!1});const c=o.getCacheKey(s,n);a.current=c;const l=n.skipCache?null:o.getCache(c);return l?(y({type:_,result:l,resetState:b!==JSON.stringify(d.cacheKey)}),Promise.resolve(l)):(y({type:H,initialState:p}),o.request(s,n).then((r=>{if(n.updateData&&"function"!=typeof n.updateData)throw Error("options.updateData must be a function");const u=k({},r);if(n.useCache&&(u.useCache=!0,u.cacheKey=c,o.ssrMode)){const e={error:u.error,data:n.updateData?n.updateData(d.data,u.data):u.data};o.saveCache(c,e)}if(i.current&&c===a.current&&y({type:U,updateData:n.updateData,result:u}),t.isMutation&&o.mutationsEmitter.emit(e,F(k({},s),{mutation:e,result:u})),!(null==r?void 0:r.error)&&n.onSuccess){if("function"!=typeof n.onSuccess)throw Error("options.onSuccess must be a function");n.onSuccess(r,s.variables)}return r})))}),[o,t,u]);n.default.useEffect((()=>{d.useCache&&!o.ssrMode&&o.saveCache(d.cacheKey,d)}),[o,d]);return n.default.useEffect((()=>{const e=(e,t)=>{y({type:t,result:e})},t=t=>e(t,U),r=t=>e(t,_);return o.mutationsEmitter.on(h.DATA_INVALIDATED,t),o.mutationsEmitter.on(h.DATA_UPDATED,r),()=>{o.mutationsEmitter.off(h.DATA_INVALIDATED,t),o.mutationsEmitter.off(h.DATA_UPDATED,r)}}),[]),[E,d,(e={})=>y({type:N,initialState:k(k({},p),e)})]}var J=Object.defineProperty,W=Object.defineProperties,z=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertySymbols,$=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,X=(e,t,r)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Z=(e,t)=>{for(var r in t||(t={}))$.call(t,r)&&X(e,r,t[r]);if(B)for(var r of B(t))Y.call(t,r)&&X(e,r,t[r]);return e};const ee={useCache:!0,skip:!1,throwErrors:!1};var te=Object.defineProperty,re=Object.getOwnPropertySymbols,oe=Object.prototype.hasOwnProperty,ne=Object.prototype.propertyIsEnumerable,ie=(e,t,r)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var se=Object.defineProperty,ae=Object.getOwnPropertySymbols,ue=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable,le=(e,t,r)=>t in e?se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;e.ClientContext=s,e.GraphQLClient=O,e.LocalGraphQLClient=class extends O{constructor(e){if(super(((e,t)=>{for(var r in t||(t={}))A.call(t,r)&&T(e,r,t[r]);if(D)for(var r of D(t))j.call(t,r)&&T(e,r,t[r]);return e})({url:""},e)),this.localQueries=e.localQueries,this.requestDelayMs=e.requestDelayMs||0,!this.localQueries)throw Error("LocalGraphQLClient: `localQueries` object required in the constructor options")}verifyConfig(){}request(e){if(!this.localQueries[e.query])throw Error("LocalGraphQLClient: no query match for: "+e.query);return(t=this.requestDelayMs,new Promise((e=>{setTimeout(e,t)}))).then((()=>Promise.resolve(this.localQueries[e.query](e.variables,e.operationName)))).then((e=>e instanceof C?{error:e}:{data:e}));var t}},e.LocalGraphQLError=C,e.useClientRequest=K,e.useManualQuery=(e,t={})=>K(e,((e,t)=>{for(var r in t||(t={}))ue.call(t,r)&&le(e,r,t[r]);if(ae)for(var r of ae(t))ce.call(t,r)&&le(e,r,t[r]);return e})({useCache:!0,isManual:!0},t)),e.useMutation=(e,t={})=>K(e,((e,t)=>{for(var r in t||(t={}))oe.call(t,r)&&ie(e,r,t[r]);if(re)for(var r of re(t))ne.call(t,r)&&ie(e,r,t[r]);return e})({isMutation:!0},t)),e.useQuery=function(e,t={}){const r=Z(Z({},ee),t),o=n.default.useContext(s),i=t.client||o,[a,u]=n.default.useState(!1),[c,l]=K(e,r);if(!i)throw Error("useQuery() requires a client to be passed in the options or as a context value");if(i.ssrMode&&!1!==t.ssr&&!a&&!t.skipCache&&!t.skip){if(!l.data&&!l.error){const e=c();i.ssrPromises.push(e)}u(!0)}const f=JSON.stringify(r);n.default.useEffect((()=>{r.skip||c()}),[e,f]),n.default.useEffect((()=>{if(l.error&&r.throwErrors)throw l.error}),[l.error,r.throwErrors]);const h=n.default.useCallback(((e={})=>c(Z({skipCache:!0,updateData:(e,t)=>t},e))),[c]);return n.default.useEffect((function(){const e=(o={},(Array.isArray(r=t.refetchAfterMutations)?r:[r]).forEach((function(e){if(null!=e){var t=typeof e;"string"===t?o[e]={}:"object"===t&&(o[e.mutation]={filter:e.filter})}})),o);var r,o;const n=Object.keys(e),s=({mutation:t,variables:r})=>{const{filter:o}=e[t];(!o||r&&o(r))&&h()};return n.forEach((e=>{i.mutationsEmitter.on(e,s)})),()=>{n.forEach((e=>{i.mutationsEmitter.removeListener(e,s)}))}}),[t.refetchAfterMutations,h,i.mutationsEmitter]),p=Z({},l),W(p,z({refetch:h}));var p},e.useQueryClient=function(){return t.useContext(s)},e.useSubscription=function(e,r){const o=t.useRef(r);o.current=r;const n=t.useContext(s),i=e.client||n;if(!i)throw Error("useSubscription() requires a client to be passed in the options or as a context value");const a={query:e.query,variables:e.variables};t.useEffect((()=>{const e=i.createSubscription(a).subscribe({next:e=>{o.current(e)},error:e=>{o.current({errors:e})},complete:()=>{e.unsubscribe()}});return()=>{e.unsubscribe()}}),[])},Object.defineProperty(e,"__esModule",{value:!0})}));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("events")):"function"==typeof define&&define.amd?define(["exports","react","events"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GraphQLHooks={},e.React,e.EventEmitter)}(this,(function(e,t,r){"use strict";function o(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=o(t),i=o(r);const s=n.default.createContext(null);s.displayName="ClientContext";var a=function(e){return"undefined"!=typeof File&&e instanceof File||"undefined"!=typeof Blob&&e instanceof Blob||e instanceof class{constructor({uri:e,name:t,type:r}){this.uri=e,this.name=t,this.type=r}}};const u=e=>a(e)||null!==e&&"object"==typeof e&&"function"==typeof e.pipe||null!==e&&"object"==typeof e&&"function"==typeof e.stream;function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,o=Array(t);t>r;r++)o[r]=e[r];return o}function l(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(r)return(r=r.call(e)).next.bind(r);if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return c(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?c(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var o=0;return function(){return e.length>o?{done:!1,value:e[o++]}:{done:!0}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var f=function(){function e(e){var t=this;0===e.length&&e.push((function(e,t){return t()}));for(var r,o=function(){var e,o=r.value;if("function"!=typeof o)throw Error("GraphQLClient Middleware: middleware has to be of type `function`");t.run=(e=t.run,function(r,n){e(r,(function(){o.call(t,r,n.bind.call(n,null,r))}))})},n=l(e);!(r=n()).done;)o()}return e.prototype.run=function(e,t){t.apply(this,e)},e}();var h=(e=>(e.DATA_INVALIDATED="DATA_INVALIDATED",e.DATA_UPDATED="DATA_UPDATED",e))(h||{}),p=Object.defineProperty,d=Object.defineProperties,y=Object.getOwnPropertyDescriptors,b=Object.getOwnPropertySymbols,E=Object.prototype.hasOwnProperty,m=Object.prototype.propertyIsEnumerable,g=(e,t,r)=>t in e?p(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,v=(e,t)=>{for(var r in t||(t={}))E.call(t,r)&&g(e,r,t[r]);if(b)for(var r of b(t))m.call(t,r)&&g(e,r,t[r]);return e};class O{constructor(e){if(!e)throw Error("GraphQLClient: config is required as first parameter");this.fullWsTransport=e.fullWsTransport,this.subscriptionClient="function"==typeof e.subscriptionClient?e.subscriptionClient():e.subscriptionClient,this.verifyConfig(e),this.cache=e.cache,this.headers=e.headers||{},this.ssrMode=e.ssrMode,this.ssrPromises=[],this.url=e.url,this.fetch=e.fetch||("undefined"!=typeof fetch&&fetch?fetch.bind(void 0):void 0),this.fetchOptions=e.fetchOptions||{},this.FormData=e.FormData||("undefined"!=typeof FormData?FormData:void 0),this.logErrors=void 0===e.logErrors||e.logErrors,this.onError=e.onError,this.useGETForQueries=!0===e.useGETForQueries,this.middleware=new f(e.middleware||[]),this.mutationsEmitter=new i.default}verifyConfig(e){if(!e.url){if(!this.fullWsTransport)throw Error("GraphQLClient: config.url is required");if(!this.subscriptionClient)throw Error("GraphQLClient: subscriptionClient is required")}if(e.fetch&&"function"!=typeof e.fetch)throw Error("GraphQLClient: config.fetch must be a function");if(("undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement||e.ssrMode)&&!e.fetch&&"function"!=typeof fetch)throw Error("GraphQLClient: fetch must be polyfilled or passed in new GraphQLClient({ fetch })");if(e.ssrMode&&!e.cache)throw Error("GraphQLClient: config.cache is required when in ssrMode")}setHeader(e,t){return this.headers[e]=t,this}setHeaders(e){return this.headers=e,this}removeHeader(e){return delete this.headers[e],this}logErrorResult({result:e,operation:t}){console.error("GraphQL Hooks Error"),console.groupCollapsed("---\x3e Full Error Details"),console.groupCollapsed("Operation:"),console.log(t),console.groupEnd();const r=e.error;r&&(r.fetchError&&(console.groupCollapsed("FETCH ERROR:"),console.log(r.fetchError),console.groupEnd()),r.httpError&&(console.groupCollapsed("HTTP ERROR:"),console.log(r.httpError),console.groupEnd()),r.graphQLErrors&&r.graphQLErrors.length>0&&(console.groupCollapsed("GRAPHQL ERROR:"),r.graphQLErrors.forEach((e=>console.log(e))),console.groupEnd())),console.groupEnd()}generateResult({fetchError:e,httpError:t,graphQLErrors:r,data:o}){return!!(r&&r.length>0||e||t)?{data:o,error:{fetchError:e,httpError:t,graphQLErrors:r}}:{data:o}}getCacheKey(e,t={}){return{operation:e,fetchOptions:v(v({},this.fetchOptions),t.fetchOptionsOverrides)}}getCache(e){const t=this.cache?this.cache.get(e):null;if(t)return t}saveCache(e,t){this.cache&&this.cache.set(e,t)}removeCache(e){var t;null==(t=this.cache)||t.delete(e)}getFetchOptions(e,t={}){const r=v(v({method:"POST",headers:v({},this.headers)},this.fetchOptions),t);if("GET"===r.method)return r;const{clone:o,files:n}=function(e,t="",r=a){const o=new Map,n=new Map;return{clone:function e(t,i,s){let a=t;if(r(t)){a=null;const e=o.get(t);e?e.push(i):o.set(t,[i])}else{const r=Array.isArray(t)||"undefined"!=typeof FileList&&t instanceof FileList,o=t&&t.constructor===Object;if(r||o){const o=n.has(t);if(o?a=n.get(t):(a=r?[]:{},n.set(t,a)),!s.has(t)){const n=i?i+".":"",u=new Set(s).add(t);if(r){let r=0;for(const i of t){const t=e(i,n+r++,u);o||a.push(t)}}else for(const r in t){const i=e(t[r],n+r,u);o||(a[r]=i)}}}}return a}(e,t,new Set),files:o}}(e,"",u),i=JSON.stringify(o);if(n.size){if(!this.FormData)throw Error("GraphQLClient: FormData must be polyfilled or passed in new GraphQLClient({ FormData })");const e=new this.FormData;e.append("operations",i);const t={};let o=0;n.forEach((e=>{t[++o]=e})),e.append("map",JSON.stringify(t)),o=0,n.forEach(((t,r)=>{e.append(""+ ++o,r,r.name)})),r.body=e}else r.headers["Content-Type"]="application/json",r.body=i;return r}request(e,t){const r=[],o=e=>r.push(e);return new Promise(((n,i)=>this.middleware.run({operation:e,client:this,addResponseHook:o,resolve:n,reject:i},(({operation:e})=>{const o=e=>{return r.length>0?(t=r,e=>t.reduce(((e,t)=>e.then(t)),Promise.resolve(e)))(e):e;var t};return this.fullWsTransport?this.requestViaWS(e).then(o).then(n).catch(i):this.url?this.requestViaHttp(e,t).then(o).then(n).catch(i):void i(Error("GraphQLClient: config.url is required"))}))))}requestViaHttp(e,t={}){let r=this.url;const o=this.getFetchOptions(e,t.fetchOptionsOverrides);if("GET"===o.method){r=r+"?"+Object.entries(e).filter((([,e])=>!!e)).map((([e,t])=>("variables"!==e&&"extensions"!==e||(t=JSON.stringify(t)),`${e}=${encodeURIComponent(t)}`))).join("&")}return this.fetch(r,o).then((e=>e.ok?e.json().then((({errors:r,data:o})=>this.generateResult({graphQLErrors:r,data:"function"==typeof t.responseReducer&&t.responseReducer(o,e)||o}))):e.text().then((t=>{const{status:r,statusText:o}=e;return this.generateResult({httpError:{status:r,statusText:o,body:t}})})))).catch((e=>this.generateResult({fetchError:e}))).then((t=>(t.error&&(this.logErrors&&this.logErrorResult({result:t,operation:e}),this.onError&&this.onError({result:t,operation:e})),t)))}requestViaWS(e){return new Promise(((t,r)=>{let o;try{const n=this.createSubscription(e).subscribe({next:e=>{o=e},error:r,complete:()=>{n.unsubscribe(),t(o)}})}catch(e){r(e)}}))}createSubscription(e){if(!this.subscriptionClient)throw Error("No SubscriptionClient! Please set in the constructor.");return"function"==typeof this.subscriptionClient.subscribe?{subscribe:t=>({unsubscribe:this.subscriptionClient.subscribe(e,t)})}:this.subscriptionClient.request(e)}invalidateQuery(e){const t="string"==typeof e?{query:e}:e,r=this.getCacheKey(t);this.cache&&r&&(this.removeCache(r),this.request(t).then((e=>{this.mutationsEmitter.emit(h.DATA_INVALIDATED,e)})).catch((e=>console.error(e))))}setQueryData(e,t){const r=this.getCacheKey("string"==typeof e?{query:e}:e);if(this.cache&&r){const e=this.cache.get(r),i=(o=v({},e),n={data:t(e.data||null)},d(o,y(n)));this.saveCache(r,i),this.mutationsEmitter.emit(h.DATA_UPDATED,i)}var o,n}}class C{constructor(e){this.fetchError=e.fetchError,this.httpError=e.httpError,this.graphQLErrors=e.graphQLErrors}}var w=Object.defineProperty,D=Object.getOwnPropertySymbols,A=Object.prototype.hasOwnProperty,j=Object.prototype.propertyIsEnumerable,T=(e,t,r)=>t in e?w(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var L=Object.prototype.hasOwnProperty;function S(e,t,r){for(r of e.keys())if(P(r,t))return r}function P(e,t){var r,o,n;if(e===t)return!0;if(e&&t&&(r=e.constructor)===t.constructor){if(r===Date)return e.getTime()===t.getTime();if(r===RegExp)return""+e==""+t;if(r===Array){if((o=e.length)===t.length)for(;o--&&P(e[o],t[o]););return-1===o}if(r===Set){if(e.size!==t.size)return!1;for(o of e){if((n=o)&&"object"==typeof n&&!(n=S(t,n)))return!1;if(!t.has(n))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(o of e){if((n=o[0])&&"object"==typeof n&&!(n=S(t,n)))return!1;if(!P(o[1],t.get(n)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((o=e.byteLength)===t.byteLength)for(;o--&&e.getInt8(o)===t.getInt8(o););return-1===o}if(ArrayBuffer.isView(e)){if((o=e.byteLength)===t.byteLength)for(;o--&&e[o]===t[o];);return-1===o}if(!r||"object"==typeof e){for(r in o=0,e){if(L.call(e,r)&&++o&&!L.call(t,r))return!1;if(!(r in t)||!P(e[r],t[r]))return!1}return Object.keys(t).length===o}}return e!=e&&t!=t}var Q=Object.defineProperty,q=Object.defineProperties,R=Object.getOwnPropertyDescriptors,M=Object.getOwnPropertySymbols,G=Object.prototype.hasOwnProperty,I=Object.prototype.propertyIsEnumerable,x=(e,t,r)=>t in e?Q(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,k=(e,t)=>{for(var r in t||(t={}))G.call(t,r)&&x(e,r,t[r]);if(M)for(var r of M(t))I.call(t,r)&&x(e,r,t[r]);return e},F=(e,t)=>q(e,R(t));const N="RESET_STATE",H="LOADING",_="CACHE_HIT",U="REQUEST_RESULT";function V(e,t){switch(t.type){case N:return e.loading?e:t.initialState;case H:return e.error?F(k({},t.initialState),{data:e.data,loading:!0}):e.loading?e:F(k({},e),{loading:!0});case _:return e.cacheHit&&!t.resetState?e:F(k({},t.result),{cacheHit:!0,loading:!1});case U:return F(k({},t.result),{data:e.data&&t.result.data&&t.updateData?t.updateData(e.data,t.result.data):t.result.data,cacheHit:!1,loading:!1});default:return e}}function K(e,t={}){if("string"!=typeof e)throw Error("Your query must be a string. If you are using the `gql` template literal from graphql-tag, remove it from your query.");const r=n.default.useContext(s),o=t.client||r;if(null==o)throw Error("A client must be provided in order to use the useClientRequest hook.");const i=n.default.useRef(!0),a=n.default.useRef(null),u={query:e,variables:t.variables,operationName:t.operationName,persisted:t.persisted};(t.persisted||o.useGETForQueries&&!t.isMutation)&&(t.fetchOptionsOverrides=F(k({},t.fetchOptionsOverrides),{method:"GET"}));const c=o.getCacheKey(u,t),l=t.isMutation||t.isManual||t.skip,f=!t.skipCache&&o.cache&&c?o.cache.get(c):null,p=F(k({},f),{cacheHit:!!f,loading:!l&&!f}),[d,y]=n.default.useReducer(V,p),b=JSON.stringify(c);n.default.useEffect((()=>{t.updateData||y({type:N,initialState:p})}),[b]),n.default.useEffect((()=>(i.current=!0,()=>{i.current=!1})),[]);const E=function(e,t){const r=n.default.useRef();return P(t,r.current)||(r.current=t),n.default.useCallback(e,r.current)}((r=>{const n=k(k({},t),r),s=F(k({},u),{variables:n.variables,operationName:n.operationName});if(!i.current)return Promise.resolve({error:{fetchError:Error("fetchData should not be called after hook unmounted")},loading:!1,cacheHit:!1});const c=o.getCacheKey(s,n);a.current=c;const l=n.skipCache?null:o.getCache(c);return l?(y({type:_,result:l,resetState:b!==JSON.stringify(d.cacheKey)}),Promise.resolve(l)):(y({type:H,initialState:p}),o.request(s,n).then((r=>{if(n.updateData&&"function"!=typeof n.updateData)throw Error("options.updateData must be a function");const u=k({},r);if(n.useCache&&(u.useCache=!0,u.cacheKey=c,o.ssrMode)){const e={error:u.error,data:n.updateData?n.updateData(d.data,u.data):u.data};o.saveCache(c,e)}if(i.current&&c===a.current&&y({type:U,updateData:n.updateData,result:u}),t.isMutation&&o.mutationsEmitter.emit(e,F(k({},s),{mutation:e,result:u})),!(null==r?void 0:r.error)&&n.onSuccess){if("function"!=typeof n.onSuccess)throw Error("options.onSuccess must be a function");n.onSuccess(r,s.variables)}return r})))}),[o,t,u]);n.default.useEffect((()=>{d.useCache&&!o.ssrMode&&o.saveCache(d.cacheKey,d)}),[o,d]);return n.default.useEffect((()=>{const e=(e,t)=>{y({type:t,result:e})},t=t=>e(t,U),r=t=>e(t,_);return o.mutationsEmitter.on(h.DATA_INVALIDATED,t),o.mutationsEmitter.on(h.DATA_UPDATED,r),()=>{o.mutationsEmitter.off(h.DATA_INVALIDATED,t),o.mutationsEmitter.off(h.DATA_UPDATED,r)}}),[]),[E,d,(e={})=>y({type:N,initialState:k(k({},p),e)})]}var J=Object.defineProperty,W=Object.defineProperties,z=Object.getOwnPropertyDescriptors,B=Object.getOwnPropertySymbols,$=Object.prototype.hasOwnProperty,Y=Object.prototype.propertyIsEnumerable,X=(e,t,r)=>t in e?J(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Z=(e,t)=>{for(var r in t||(t={}))$.call(t,r)&&X(e,r,t[r]);if(B)for(var r of B(t))Y.call(t,r)&&X(e,r,t[r]);return e};const ee={useCache:!0,skip:!1,throwErrors:!1};var te=Object.defineProperty,re=Object.getOwnPropertySymbols,oe=Object.prototype.hasOwnProperty,ne=Object.prototype.propertyIsEnumerable,ie=(e,t,r)=>t in e?te(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var se=Object.defineProperty,ae=Object.getOwnPropertySymbols,ue=Object.prototype.hasOwnProperty,ce=Object.prototype.propertyIsEnumerable,le=(e,t,r)=>t in e?se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;e.ClientContext=s,e.GraphQLClient=O,e.LocalGraphQLClient=class extends O{constructor(e){if(super(((e,t)=>{for(var r in t||(t={}))A.call(t,r)&&T(e,r,t[r]);if(D)for(var r of D(t))j.call(t,r)&&T(e,r,t[r]);return e})({url:""},e)),this.localQueries=e.localQueries,this.requestDelayMs=e.requestDelayMs||0,!this.localQueries)throw Error("LocalGraphQLClient: `localQueries` object required in the constructor options")}verifyConfig(){}request(e){if(!this.localQueries[e.query])throw Error("LocalGraphQLClient: no query match for: "+e.query);return(t=this.requestDelayMs,new Promise((e=>{setTimeout(e,t)}))).then((()=>Promise.resolve(this.localQueries[e.query](e.variables,e.operationName)))).then((e=>e instanceof C?{error:e}:{data:e}));var t}},e.LocalGraphQLError=C,e.useClientRequest=K,e.useManualQuery=(e,t={})=>K(e,((e,t)=>{for(var r in t||(t={}))ue.call(t,r)&&le(e,r,t[r]);if(ae)for(var r of ae(t))ce.call(t,r)&&le(e,r,t[r]);return e})({useCache:!0,isManual:!0},t)),e.useMutation=(e,t={})=>K(e,((e,t)=>{for(var r in t||(t={}))oe.call(t,r)&&ie(e,r,t[r]);if(re)for(var r of re(t))ne.call(t,r)&&ie(e,r,t[r]);return e})({isMutation:!0},t)),e.useQuery=function(e,t={}){const r=Z(Z({},ee),t),o=n.default.useContext(s),i=t.client||o,[a,u]=n.default.useState(!1),[c,l]=K(e,r);if(!i)throw Error("useQuery() requires a client to be passed in the options or as a context value");if(i.ssrMode&&!1!==t.ssr&&!a&&!t.skipCache&&!t.skip){if(!l.data&&!l.error){const e=c();i.ssrPromises.push(e)}u(!0)}const f=JSON.stringify(r);n.default.useEffect((()=>{r.skip||c()}),[e,f]),n.default.useEffect((()=>{if(l.error&&r.throwErrors)throw l.error}),[l.error,r.throwErrors]);const h=n.default.useCallback(((e={})=>c(Z({skipCache:!0,updateData:(e,t)=>t},e))),[c]);return n.default.useEffect((function(){const e=(o={},(Array.isArray(r=t.refetchAfterMutations)?r:[r]).forEach((function(e){if(null!=e){var t=typeof e;"string"===t?o[e]={}:"object"===t&&(o[e.mutation]={filter:e.filter})}})),o);var r,o;const n=Object.keys(e),s=({mutation:t,variables:r})=>{const{filter:o}=e[t];(!o||r&&o(r))&&h()};return n.forEach((e=>{i.mutationsEmitter.on(e,s)})),()=>{n.forEach((e=>{i.mutationsEmitter.removeListener(e,s)}))}}),[t.refetchAfterMutations,h,i.mutationsEmitter]),p=Z({},l),W(p,z({refetch:h}));var p},e.useQueryClient=function(){return t.useContext(s)},e.useSubscription=function(e,r){const o=t.useRef(r);o.current=r;const n=t.useContext(s),i=e.client||n;if(!i)throw Error("useSubscription() requires a client to be passed in the options or as a context value");const a={query:e.query,variables:e.variables};t.useEffect((()=>{const e=i.createSubscription(a).subscribe({next:e=>{o.current(e)},error:e=>{o.current({errors:e})},complete:()=>{e.unsubscribe()}});return()=>{e.unsubscribe()}}),[])},Object.defineProperty(e,"__esModule",{value:!0})}));

@@ -507,2 +507,5 @@ import React, { useContext, useRef, useEffect } from 'react';

case actionTypes.RESET_STATE:
if (state.loading) {
return state;
}
return action.initialState;

@@ -684,3 +687,6 @@ case actionTypes.LOADING:

return () => {
client.mutationsEmitter.off(Events.DATA_INVALIDATED, dataInvalidatedCallback);
client.mutationsEmitter.off(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
client.mutationsEmitter.off(Events.DATA_UPDATED, dataUpdatedCallback);

@@ -687,0 +693,0 @@ };

@@ -516,2 +516,5 @@ 'use strict';

case actionTypes.RESET_STATE:
if (state.loading) {
return state;
}
return action.initialState;

@@ -693,3 +696,6 @@ case actionTypes.LOADING:

return () => {
client.mutationsEmitter.off(Events.DATA_INVALIDATED, dataInvalidatedCallback);
client.mutationsEmitter.off(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
);
client.mutationsEmitter.off(Events.DATA_UPDATED, dataUpdatedCallback);

@@ -696,0 +702,0 @@ };

{
"name": "graphql-hooks",
"version": "6.0.3",
"version": "6.0.4",
"description": "Graphql Hooks",

@@ -67,3 +67,3 @@ "main": "lib/graphql-hooks.js",

"homepage": "https://github.com/nearform/graphql-hooks#readme",
"gitHead": "28b9ded6c9e2b80214dff5f54815d983f2140a6c"
"gitHead": "78924a879f259277087adf5323e178ff1c240635"
}

@@ -23,2 +23,6 @@ import { dequal } from 'dequal'

case actionTypes.RESET_STATE:
// Do not reset the state if it's loading
if (state.loading) {
return state
}
return action.initialState

@@ -290,6 +294,6 @@ case actionTypes.LOADING:

const dataInvalidatedCallback = payload =>
handleEvents(payload, actionTypes.REQUEST_RESULT)
handleEvents(payload, actionTypes.REQUEST_RESULT)
const dataUpdatedCallback = payload =>
handleEvents(payload, actionTypes.CACHE_HIT)
handleEvents(payload, actionTypes.CACHE_HIT)

@@ -299,3 +303,6 @@ client.mutationsEmitter.on(Events.DATA_INVALIDATED, dataInvalidatedCallback)

return () => {
client.mutationsEmitter.off(Events.DATA_INVALIDATED, dataInvalidatedCallback)
client.mutationsEmitter.off(
Events.DATA_INVALIDATED,
dataInvalidatedCallback
)
client.mutationsEmitter.off(Events.DATA_UPDATED, dataUpdatedCallback)

@@ -302,0 +309,0 @@ }

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc