graphql-hooks
Advanced tools
Comparing version 5.4.0 to 5.4.1
@@ -6,2 +6,14 @@ # Change Log | ||
## [5.4.1](https://github.com/nearform/graphql-hooks/compare/graphql-hooks@5.4.0...graphql-hooks@5.4.1) (2021-10-20) | ||
### Bug Fixes | ||
* missing GraphQLClient type definitions ([#677](https://github.com/nearform/graphql-hooks/issues/677)) ([#678](https://github.com/nearform/graphql-hooks/issues/678)) ([b4a807b](https://github.com/nearform/graphql-hooks/commit/b4a807ba447bb9a1d827aa44031fa469e478e9f7)) | ||
* types ([#670](https://github.com/nearform/graphql-hooks/issues/670)) ([47dbf7e](https://github.com/nearform/graphql-hooks/commit/47dbf7ec00ffcff031b168318c2d83903a0d46bd)) | ||
# [5.4.0](https://github.com/nearform/graphql-hooks/compare/graphql-hooks@5.3.0...graphql-hooks@5.4.0) (2021-08-04) | ||
@@ -8,0 +20,0 @@ |
@@ -63,11 +63,68 @@ (function (global, factory) { | ||
var ReactNativeFile = function ReactNativeFile(_ref) { | ||
var uri = _ref.uri, | ||
name = _ref.name, | ||
type = _ref.type; | ||
this.uri = uri; | ||
this.name = name; | ||
this.type = type; | ||
/** | ||
* Used to mark a | ||
* [React Native `File` substitute]{@link ReactNativeFileSubstitute} | ||
* in an object tree for [`extractFiles`]{@link extractFiles}. It’s too risky to | ||
* assume all objects with `uri`, `type` and `name` properties are files to | ||
* extract. | ||
* @kind class | ||
* @name ReactNativeFile | ||
* @param {ReactNativeFileSubstitute} file A [React Native](https://reactnative.dev) [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) substitute. | ||
* @example <caption>Ways to `import`.</caption> | ||
* ```js | ||
* import { ReactNativeFile } from 'extract-files'; | ||
* ``` | ||
* | ||
* ```js | ||
* import ReactNativeFile from 'extract-files/public/ReactNativeFile.js'; | ||
* ``` | ||
* @example <caption>Ways to `require`.</caption> | ||
* ```js | ||
* const { ReactNativeFile } = require('extract-files'); | ||
* ``` | ||
* | ||
* ```js | ||
* const ReactNativeFile = require('extract-files/public/ReactNativeFile.js'); | ||
* ``` | ||
* @example <caption>An extractable file in [React Native](https://reactnative.dev).</caption> | ||
* ```js | ||
* const file = new ReactNativeFile({ | ||
* uri: uriFromCameraRoll, | ||
* name: 'a.jpg', | ||
* type: 'image/jpeg', | ||
* }); | ||
* ``` | ||
*/ | ||
var ReactNativeFile_1 = class ReactNativeFile { | ||
constructor({ uri, name, type }) { | ||
this.uri = uri; | ||
this.name = name; | ||
this.type = type; | ||
} | ||
}; | ||
/** | ||
* Checks if a value is an [extractable file]{@link ExtractableFile}. | ||
* @kind function | ||
* @name isExtractableFile | ||
* @type {ExtractableFileMatcher} | ||
* @param {*} value Value to check. | ||
* @returns {boolean} Is the value an [extractable file]{@link ExtractableFile}. | ||
* @example <caption>Ways to `import`.</caption> | ||
* ```js | ||
* import { isExtractableFile } from 'extract-files'; | ||
* ``` | ||
* | ||
* ```js | ||
* import isExtractableFile from 'extract-files/public/isExtractableFile.js'; | ||
* ``` | ||
* @example <caption>Ways to `require`.</caption> | ||
* ```js | ||
* const { isExtractableFile } = require('extract-files'); | ||
* ``` | ||
* | ||
* ```js | ||
* const isExtractableFile = require('extract-files/public/isExtractableFile.js'); | ||
* ``` | ||
*/ | ||
var isExtractableFile = function isExtractableFile(value) { | ||
@@ -77,54 +134,153 @@ return ( | ||
(typeof Blob !== 'undefined' && value instanceof Blob) || | ||
value instanceof ReactNativeFile | ||
value instanceof ReactNativeFile_1 | ||
); | ||
}; | ||
var extractFiles = function extractFiles(value, path, isExtractableFile$1) { | ||
if (path === void 0) { | ||
path = ''; | ||
} | ||
/** | ||
* Clones a value, recursively extracting | ||
* [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File), | ||
* [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and | ||
* [`ReactNativeFile`]{@link ReactNativeFile} instances with their | ||
* [object paths]{@link ObjectPath}, replacing them with `null`. | ||
* [`FileList`](https://developer.mozilla.org/en-US/docs/Web/API/Filelist) instances | ||
* are treated as [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) | ||
* instance arrays. | ||
* @kind function | ||
* @name extractFiles | ||
* @param {*} value Value (typically an object tree) to extract files from. | ||
* @param {ObjectPath} [path=''] Prefix for object paths for extracted files. | ||
* @param {ExtractableFileMatcher} [isExtractableFile=isExtractableFile] The function used to identify extractable files. | ||
* @returns {ExtractFilesResult} Result. | ||
* @example <caption>Ways to `import`.</caption> | ||
* ```js | ||
* import { extractFiles } from 'extract-files'; | ||
* ``` | ||
* | ||
* ```js | ||
* import extractFiles from 'extract-files/public/extractFiles.js'; | ||
* ``` | ||
* @example <caption>Ways to `require`.</caption> | ||
* ```js | ||
* const { extractFiles } = require('extract-files'); | ||
* ``` | ||
* | ||
* ```js | ||
* const extractFiles = require('extract-files/public/extractFiles.js'); | ||
* ``` | ||
* @example <caption>Extract files from an object.</caption> | ||
* For the following: | ||
* | ||
* ```js | ||
* const file1 = new File(['1'], '1.txt', { type: 'text/plain' }); | ||
* const file2 = new File(['2'], '2.txt', { type: 'text/plain' }); | ||
* const value = { | ||
* a: file1, | ||
* b: [file1, file2], | ||
* }; | ||
* | ||
* const { clone, files } = extractFiles(value, 'prefix'); | ||
* ``` | ||
* | ||
* `value` remains the same. | ||
* | ||
* `clone` is: | ||
* | ||
* ```json | ||
* { | ||
* "a": null, | ||
* "b": [null, null] | ||
* } | ||
* ``` | ||
* | ||
* `files` is a [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance containing: | ||
* | ||
* | Key | Value | | ||
* | :------ | :--------------------------- | | ||
* | `file1` | `['prefix.a', 'prefix.b.0']` | | ||
* | `file2` | `['prefix.b.1']` | | ||
*/ | ||
var extractFiles = function extractFiles( | ||
value, | ||
path = '', | ||
isExtractableFile$1 = isExtractableFile | ||
) { | ||
// Map of extracted files and their object paths within the input value. | ||
const files = new Map(); | ||
if (isExtractableFile$1 === void 0) { | ||
isExtractableFile$1 = isExtractableFile; | ||
} | ||
// Map of arrays and objects recursed within the input value and their clones, | ||
// for reusing clones of values that are referenced multiple times within the | ||
// input value. | ||
const clones = new Map(); | ||
var clone; | ||
var files = new Map(); | ||
/** | ||
* Recursively clones the value, extracting files. | ||
* @kind function | ||
* @name extractFiles~recurse | ||
* @param {*} value Value to extract files from. | ||
* @param {ObjectPath} path Prefix for object paths for extracted files. | ||
* @param {Set} recursed Recursed arrays and objects for avoiding infinite recursion of circular references within the input value. | ||
* @returns {*} Clone of the value with files replaced with `null`. | ||
* @ignore | ||
*/ | ||
function recurse(value, path, recursed) { | ||
let clone = value; | ||
function addFile(paths, file) { | ||
var storedPaths = files.get(file); | ||
if (storedPaths) storedPaths.push.apply(storedPaths, paths); | ||
else files.set(file, paths); | ||
} | ||
if (isExtractableFile$1(value)) { | ||
clone = null; | ||
if (isExtractableFile$1(value)) { | ||
clone = null; | ||
addFile([path], value); | ||
} else { | ||
var prefix = path ? path + '.' : ''; | ||
if (typeof FileList !== 'undefined' && value instanceof FileList) | ||
clone = Array.prototype.map.call(value, function (file, i) { | ||
addFile(['' + prefix + i], file); | ||
return null; | ||
}); | ||
else if (Array.isArray(value)) | ||
clone = value.map(function (child, i) { | ||
var result = extractFiles(child, '' + prefix + i, isExtractableFile$1); | ||
result.files.forEach(addFile); | ||
return result.clone; | ||
}); | ||
else if (value && value.constructor === Object) { | ||
clone = {}; | ||
const filePaths = files.get(value); | ||
for (var i in value) { | ||
var result = extractFiles(value[i], '' + prefix + i, isExtractableFile$1); | ||
result.files.forEach(addFile); | ||
clone[i] = result.clone; | ||
filePaths ? filePaths.push(path) : files.set(value, [path]); | ||
} else { | ||
const isList = | ||
Array.isArray(value) || | ||
(typeof FileList !== 'undefined' && value instanceof FileList); | ||
const isObject = value && value.constructor === Object; | ||
if (isList || isObject) { | ||
const hasClone = clones.has(value); | ||
if (hasClone) clone = clones.get(value); | ||
else { | ||
clone = isList ? [] : {}; | ||
clones.set(value, clone); | ||
} | ||
if (!recursed.has(value)) { | ||
const pathPrefix = path ? `${path}.` : ''; | ||
const recursedDeeper = new Set(recursed).add(value); | ||
if (isList) { | ||
let index = 0; | ||
for (const item of value) { | ||
const itemClone = recurse( | ||
item, | ||
pathPrefix + index++, | ||
recursedDeeper | ||
); | ||
if (!hasClone) clone.push(itemClone); | ||
} | ||
} else | ||
for (const key in value) { | ||
const propertyClone = recurse( | ||
value[key], | ||
pathPrefix + key, | ||
recursedDeeper | ||
); | ||
if (!hasClone) clone[key] = propertyClone; | ||
} | ||
} | ||
} | ||
} else clone = value; | ||
} | ||
return clone; | ||
} | ||
return { | ||
clone: clone, | ||
files: files, | ||
clone: recurse(value, path, new Set()), | ||
files, | ||
}; | ||
@@ -131,0 +287,0 @@ }; |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GraphQLHooks={},e.React)}(this,(function(e,t){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=r(t);function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function a(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?i(Object(r),!0).forEach((function(t){o(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var s=n.default.createContext();s.displayName="ClientContext";var u=function(e){var t=e.name,r=e.type;this.uri=e.uri,this.name=t,this.type=r},c=function(e){return"undefined"!=typeof File&&e instanceof File||"undefined"!=typeof Blob&&e instanceof Blob||e instanceof u},f=function e(t,r,n){var o;void 0===r&&(r=""),void 0===n&&(n=c);var i=new Map;function a(e,t){var r=i.get(t);r?r.push.apply(r,e):i.set(t,e)}if(n(t))o=null,a([r],t);else{var s=r?r+".":"";if("undefined"!=typeof FileList&&t instanceof FileList)o=Array.prototype.map.call(t,(function(e,t){return a([""+s+t],e),null}));else if(Array.isArray(t))o=t.map((function(t,r){var o=e(t,""+s+r,n);return o.files.forEach(a),o.clone}));else if(t&&t.constructor===Object)for(var u in o={},t){var f=e(t[u],""+s+u,n);f.files.forEach(a),o[u]=f.clone}else o=t}return{clone:o,files:i}},l=function(e){return c(e)||null!==e&&"object"==typeof e&&"function"==typeof e.pipe},h=function(){function e(e){if(void 0===e&&(e={}),!e.url)throw Error("GraphQLClient: config.url 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&&!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");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(),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.subscriptionClient=e.subscriptionClient}var t=e.prototype;return t.setHeader=function(e,t){return this.headers[e]=t,this},t.setHeaders=function(e){return this.headers=e,this},t.removeHeader=function(e){return delete this.headers[e],this},t.logErrorResult=function(e){var t=e.result,r=e.operation;console.error("GraphQL Hooks Error"),console.groupCollapsed("---\x3e Full Error Details"),console.groupCollapsed("Operation:"),console.log(r),console.groupEnd();var n=t.error;n&&(n.fetchError&&(console.groupCollapsed("FETCH ERROR:"),console.log(n.fetchError),console.groupEnd()),n.httpError&&(console.groupCollapsed("HTTP ERROR:"),console.log(n.httpError),console.groupEnd()),n.graphQLErrors&&n.graphQLErrors.length>0&&(console.groupCollapsed("GRAPHQL ERROR:"),n.graphQLErrors.forEach((function(e){return console.log(e)})),console.groupEnd())),console.groupEnd()},t.generateResult=function(e){var t=e.fetchError,r=e.httpError,n=e.graphQLErrors,o=e.data;return!!(n&&n.length>0||t||r)?{data:o,error:{fetchError:t,httpError:r,graphQLErrors:n}}:{data:o}},t.getCacheKey=function(e,t){return void 0===t&&(t={}),{operation:e,fetchOptions:a(a({},this.fetchOptions),t.fetchOptionsOverrides)}},t.getCache=function(e){var t=this.cache?this.cache.get(e):null;if(t)return t},t.saveCache=function(e,t){this.cache&&this.cache.set(e,t)},t.getFetchOptions=function(e,t){void 0===t&&(t={});var r=a(a({method:"POST",headers:a({},this.headers)},this.fetchOptions),t);if("GET"===r.method)return r;var n=f(e,"",l),o=n.files,i=JSON.stringify(n.clone);if(o.size){if(!this.FormData)throw Error("GraphQLClient: FormData must be polyfilled or passed in new GraphQLClient({ FormData })");var s=new this.FormData;s.append("operations",i);var u={},c=0;o.forEach((function(e){u[++c]=e})),s.append("map",JSON.stringify(u)),c=0,o.forEach((function(e,t){s.append(""+ ++c,t,t.name)})),r.body=s}else r.headers["Content-Type"]="application/json",r.body=i;return r},t.request=function(e,t){var r=this;void 0===t&&(t={});var n=this.url;"GET"===this.getFetchOptions(e,t.fetchOptionsOverrides).method&&(n=n+"?"+Object.entries(e).filter((function(e){return!!e[1]})).map((function(e){var t=e[0],r=e[1];return"variables"===t&&(r=JSON.stringify(r)),t+"="+encodeURIComponent(r)})).join("&"));return this.fetch(n,this.getFetchOptions(e,t.fetchOptionsOverrides)).then((function(e){return e.ok?e.json().then((function(e){return r.generateResult({graphQLErrors:e.errors,data:e.data})})):e.text().then((function(t){return r.generateResult({httpError:{status:e.status,statusText:e.statusText,body:t}})}))})).catch((function(e){return r.generateResult({fetchError:e})})).then((function(t){return t.error&&(r.logErrors&&r.logErrorResult({result:t,operation:e}),r.onError&&r.onError({result:t,operation:e})),t}))},t.createSubscription=function(e){var t=this;if(!this.subscriptionClient)throw Error("No SubscriptionClient! Please set in the constructor.");return"function"==typeof this.subscriptionClient.subscribe?{subscribe:function(r){return{unsubscribe:t.subscriptionClient.subscribe(e,r)}}}:this.subscriptionClient.request(e)},e}(),p=Object.prototype.hasOwnProperty;function d(e,t,r){for(r of e.keys())if(y(r,t))return r}function y(e,t){var r,n,o;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((n=e.length)===t.length)for(;n--&&y(e[n],t[n]););return-1===n}if(r===Set){if(e.size!==t.size)return!1;for(n of e){if((o=n)&&"object"==typeof o&&!(o=d(t,o)))return!1;if(!t.has(o))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(n of e){if((o=n[0])&&"object"==typeof o&&!(o=d(t,o)))return!1;if(!y(n[1],t.get(o)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((n=e.byteLength)===t.byteLength)for(;n--&&e.getInt8(n)===t.getInt8(n););return-1===n}if(ArrayBuffer.isView(e)){if((n=e.byteLength)===t.byteLength)for(;n--&&e[n]===t[n];);return-1===n}if(!r||"object"==typeof e){for(r in n=0,e){if(p.call(e,r)&&++n&&!p.call(t,r))return!1;if(!(r in t)||!y(e[r],t[r]))return!1}return Object.keys(t).length===n}}return e!=e&&t!=t}var g="RESET_STATE",b="LOADING",v="CACHE_HIT",E="REQUEST_RESULT";function O(e,t){switch(t.type){case g:return t.initialState;case b:return e.error?a(a({},t.initialState),{},{data:e.data,loading:!0}):e.loading?e:a(a({},e),{},{loading:!0});case v:return e.cacheHit&&!t.resetState?e:a(a({},t.result),{},{cacheHit:!0,loading:!1});case E:return a(a({},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 C(e,t){if(void 0===t&&(t={}),"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.");var r=n.default.useContext(s),o=t.client||r,i=n.default.useRef(!0),u=n.default.useRef(null),c={query:e,variables:t.variables,operationName:t.operationName,persisted:t.persisted};(t.persisted||o.useGETForQueries&&!t.isMutation)&&(t.fetchOptionsOverrides=a(a({},t.fetchOptionsOverrides),{},{method:"GET"}));var f=o.getCacheKey(c,t),l=t.isMutation||t.isManual,h=t.skipCache||!o.cache?null:o.cache.get(f),p=a(a({},h),{},{cacheHit:!!h,loading:!l&&!h}),d=n.default.useReducer(O,p),C=d[0],m=d[1],w=JSON.stringify(f);n.default.useEffect((function(){t.updateData||m({type:g,initialState:p})}),[w]),n.default.useEffect((function(){return i.current=!0,function(){i.current=!1}}),[]);var R,D,j,S=(R=function(e){if(!i.current)return Promise.resolve();var r=a(a({},t),e),n=a(a({},c),{},{variables:r.variables,operationName:r.operationName}),s=o.getCacheKey(n,r);u.current=s;var f=r.skipCache?null:o.getCache(s);return f?(m({type:v,result:f,resetState:w!==JSON.stringify(C.cacheKey)}),Promise.resolve(f)):(m({type:b,initialState:p}),o.request(n,r).then((function(e){if(r.updateData&&"function"!=typeof r.updateData)throw Error("options.updateData must be a function");var t=a({},e);if(r.useCache&&(t.useCache=!0,t.cacheKey=s,o.ssrMode)){var n={error:t.error,data:r.updateData?r.updateData(C.data,t.data):t.data};o.saveCache(s,n)}return i.current&&s===u.current&&m({type:E,updateData:r.updateData,result:t}),e})))},D=[o,t,c],j=n.default.useRef(),y(D,j.current)||(j.current=D),n.default.useCallback(R,j.current));n.default.useEffect((function(){C.useCache&&o.saveCache(C.cacheKey,C)}),[o,C]);return[S,C,function(e){return void 0===e&&(e={}),m({type:g,initialState:a(a({},p),e)})}]}var m={useCache:!0,skip:!1,throwErrors:!1};e.ClientContext=s,e.GraphQLClient=h,e.useClientRequest=C,e.useManualQuery=function(e,t){return C(e,a({useCache:!0,isManual:!0},t))},e.useMutation=function(e,t){return C(e,a({isMutation:!0},t))},e.useQuery=function(e,t){void 0===t&&(t={});var r=a(a({},m),t),o=n.default.useContext(s),i=t.client||o,u=n.default.useState(!1),c=u[0],f=u[1],l=C(e,r),h=l[0],p=l[1];if(i.ssrMode&&!1!==t.ssr&&!c&&!t.skipCache&&!t.skip){if(!p.data&&!p.error){var d=h();i.ssrPromises.push(d)}f(!0)}var y=JSON.stringify(r);return n.default.useEffect((function(){r.skip||h()}),[e,y]),n.default.useEffect((function(){if(p.error&&r.throwErrors)throw p.error}),[p.error,r.throwErrors]),a(a({},p),{},{refetch:n.default.useCallback((function(e){return void 0===e&&(e={}),h(a({skipCache:!0,updateData:function(e,t){return t}},e))}),[h])})},e.useSubscription=function(e,r){var n=t.useRef(r);n.current=r;var o=t.useContext(s),i=e.client||o,a={query:e.query,variables:e.variables};t.useEffect((function(){var e=i.createSubscription(a).subscribe({next:function(e){n.current(e)},error:function(){e.unsubscribe()},complete:function(){e.unsubscribe()}});return function(){e.unsubscribe()}}),[])},Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).GraphQLHooks={},e.React)}(this,(function(e,t){"use strict";function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=r(t);function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function s(e){for(var t=1;arguments.length>t;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?i(Object(r),!0).forEach((function(t){o(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}var a=n.default.createContext();a.displayName="ClientContext";var u=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}}},c=function(e){return u(e)||null!==e&&"object"==typeof e&&"function"==typeof e.pipe},f=function(){function e(e){if(void 0===e&&(e={}),!e.url)throw Error("GraphQLClient: config.url 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&&!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");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(),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.subscriptionClient=e.subscriptionClient}var t=e.prototype;return t.setHeader=function(e,t){return this.headers[e]=t,this},t.setHeaders=function(e){return this.headers=e,this},t.removeHeader=function(e){return delete this.headers[e],this},t.logErrorResult=function(e){var t=e.result,r=e.operation;console.error("GraphQL Hooks Error"),console.groupCollapsed("---\x3e Full Error Details"),console.groupCollapsed("Operation:"),console.log(r),console.groupEnd();var n=t.error;n&&(n.fetchError&&(console.groupCollapsed("FETCH ERROR:"),console.log(n.fetchError),console.groupEnd()),n.httpError&&(console.groupCollapsed("HTTP ERROR:"),console.log(n.httpError),console.groupEnd()),n.graphQLErrors&&n.graphQLErrors.length>0&&(console.groupCollapsed("GRAPHQL ERROR:"),n.graphQLErrors.forEach((function(e){return console.log(e)})),console.groupEnd())),console.groupEnd()},t.generateResult=function(e){var t=e.fetchError,r=e.httpError,n=e.graphQLErrors,o=e.data;return!!(n&&n.length>0||t||r)?{data:o,error:{fetchError:t,httpError:r,graphQLErrors:n}}:{data:o}},t.getCacheKey=function(e,t){return void 0===t&&(t={}),{operation:e,fetchOptions:s(s({},this.fetchOptions),t.fetchOptionsOverrides)}},t.getCache=function(e){var t=this.cache?this.cache.get(e):null;if(t)return t},t.saveCache=function(e,t){this.cache&&this.cache.set(e,t)},t.getFetchOptions=function(e,t){void 0===t&&(t={});var r=s(s({method:"POST",headers:s({},this.headers)},this.fetchOptions),t);if("GET"===r.method)return r;var n=function(e,t="",r=u){const n=new Map,o=new Map;return{clone:function e(t,i,s){let a=t;if(r(t)){a=null;const e=n.get(t);e?e.push(i):n.set(t,[i])}else{const r=Array.isArray(t)||"undefined"!=typeof FileList&&t instanceof FileList,n=t&&t.constructor===Object;if(r||n){const n=o.has(t);if(n?a=o.get(t):(a=r?[]:{},o.set(t,a)),!s.has(t)){const o=i?i+".":"",u=new Set(s).add(t);if(r){let r=0;for(const i of t){const t=e(i,o+r++,u);n||a.push(t)}}else for(const r in t){const i=e(t[r],o+r,u);n||(a[r]=i)}}}}return a}(e,t,new Set),files:n}}(e,"",c),o=n.files,i=JSON.stringify(n.clone);if(o.size){if(!this.FormData)throw Error("GraphQLClient: FormData must be polyfilled or passed in new GraphQLClient({ FormData })");var a=new this.FormData;a.append("operations",i);var f={},l=0;o.forEach((function(e){f[++l]=e})),a.append("map",JSON.stringify(f)),l=0,o.forEach((function(e,t){a.append(""+ ++l,t,t.name)})),r.body=a}else r.headers["Content-Type"]="application/json",r.body=i;return r},t.request=function(e,t){var r=this;void 0===t&&(t={});var n=this.url;"GET"===this.getFetchOptions(e,t.fetchOptionsOverrides).method&&(n=n+"?"+Object.entries(e).filter((function(e){return!!e[1]})).map((function(e){var t=e[0],r=e[1];return"variables"===t&&(r=JSON.stringify(r)),t+"="+encodeURIComponent(r)})).join("&"));return this.fetch(n,this.getFetchOptions(e,t.fetchOptionsOverrides)).then((function(e){return e.ok?e.json().then((function(e){return r.generateResult({graphQLErrors:e.errors,data:e.data})})):e.text().then((function(t){return r.generateResult({httpError:{status:e.status,statusText:e.statusText,body:t}})}))})).catch((function(e){return r.generateResult({fetchError:e})})).then((function(t){return t.error&&(r.logErrors&&r.logErrorResult({result:t,operation:e}),r.onError&&r.onError({result:t,operation:e})),t}))},t.createSubscription=function(e){var t=this;if(!this.subscriptionClient)throw Error("No SubscriptionClient! Please set in the constructor.");return"function"==typeof this.subscriptionClient.subscribe?{subscribe:function(r){return{unsubscribe:t.subscriptionClient.subscribe(e,r)}}}:this.subscriptionClient.request(e)},e}(),l=Object.prototype.hasOwnProperty;function h(e,t,r){for(r of e.keys())if(p(r,t))return r}function p(e,t){var r,n,o;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((n=e.length)===t.length)for(;n--&&p(e[n],t[n]););return-1===n}if(r===Set){if(e.size!==t.size)return!1;for(n of e){if((o=n)&&"object"==typeof o&&!(o=h(t,o)))return!1;if(!t.has(o))return!1}return!0}if(r===Map){if(e.size!==t.size)return!1;for(n of e){if((o=n[0])&&"object"==typeof o&&!(o=h(t,o)))return!1;if(!p(n[1],t.get(o)))return!1}return!0}if(r===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(r===DataView){if((n=e.byteLength)===t.byteLength)for(;n--&&e.getInt8(n)===t.getInt8(n););return-1===n}if(ArrayBuffer.isView(e)){if((n=e.byteLength)===t.byteLength)for(;n--&&e[n]===t[n];);return-1===n}if(!r||"object"==typeof e){for(r in n=0,e){if(l.call(e,r)&&++n&&!l.call(t,r))return!1;if(!(r in t)||!p(e[r],t[r]))return!1}return Object.keys(t).length===n}}return e!=e&&t!=t}var d="RESET_STATE",g="LOADING",y="CACHE_HIT",b="REQUEST_RESULT";function E(e,t){switch(t.type){case d:return t.initialState;case g:return e.error?s(s({},t.initialState),{},{data:e.data,loading:!0}):e.loading?e:s(s({},e),{},{loading:!0});case y:return e.cacheHit&&!t.resetState?e:s(s({},t.result),{},{cacheHit:!0,loading:!1});case b:return s(s({},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 v(e,t){if(void 0===t&&(t={}),"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.");var r=n.default.useContext(a),o=t.client||r,i=n.default.useRef(!0),u=n.default.useRef(null),c={query:e,variables:t.variables,operationName:t.operationName,persisted:t.persisted};(t.persisted||o.useGETForQueries&&!t.isMutation)&&(t.fetchOptionsOverrides=s(s({},t.fetchOptionsOverrides),{},{method:"GET"}));var f=o.getCacheKey(c,t),l=t.isMutation||t.isManual,h=t.skipCache||!o.cache?null:o.cache.get(f),v=s(s({},h),{},{cacheHit:!!h,loading:!l&&!h}),O=n.default.useReducer(E,v),C=O[0],m=O[1],w=JSON.stringify(f);n.default.useEffect((function(){t.updateData||m({type:d,initialState:v})}),[w]),n.default.useEffect((function(){return i.current=!0,function(){i.current=!1}}),[]);var R,S,D,j=(R=function(e){if(!i.current)return Promise.resolve();var r=s(s({},t),e),n=s(s({},c),{},{variables:r.variables,operationName:r.operationName}),a=o.getCacheKey(n,r);u.current=a;var f=r.skipCache?null:o.getCache(a);return f?(m({type:y,result:f,resetState:w!==JSON.stringify(C.cacheKey)}),Promise.resolve(f)):(m({type:g,initialState:v}),o.request(n,r).then((function(e){if(r.updateData&&"function"!=typeof r.updateData)throw Error("options.updateData must be a function");var t=s({},e);if(r.useCache&&(t.useCache=!0,t.cacheKey=a,o.ssrMode)){var n={error:t.error,data:r.updateData?r.updateData(C.data,t.data):t.data};o.saveCache(a,n)}return i.current&&a===u.current&&m({type:b,updateData:r.updateData,result:t}),e})))},S=[o,t,c],D=n.default.useRef(),p(S,D.current)||(D.current=S),n.default.useCallback(R,D.current));n.default.useEffect((function(){C.useCache&&o.saveCache(C.cacheKey,C)}),[o,C]);return[j,C,function(e){return void 0===e&&(e={}),m({type:d,initialState:s(s({},v),e)})}]}var O={useCache:!0,skip:!1,throwErrors:!1};e.ClientContext=a,e.GraphQLClient=f,e.useClientRequest=v,e.useManualQuery=function(e,t){return v(e,s({useCache:!0,isManual:!0},t))},e.useMutation=function(e,t){return v(e,s({isMutation:!0},t))},e.useQuery=function(e,t){void 0===t&&(t={});var r=s(s({},O),t),o=n.default.useContext(a),i=t.client||o,u=n.default.useState(!1),c=u[0],f=u[1],l=v(e,r),h=l[0],p=l[1];if(i.ssrMode&&!1!==t.ssr&&!c&&!t.skipCache&&!t.skip){if(!p.data&&!p.error){var d=h();i.ssrPromises.push(d)}f(!0)}var g=JSON.stringify(r);return n.default.useEffect((function(){r.skip||h()}),[e,g]),n.default.useEffect((function(){if(p.error&&r.throwErrors)throw p.error}),[p.error,r.throwErrors]),s(s({},p),{},{refetch:n.default.useCallback((function(e){return void 0===e&&(e={}),h(s({skipCache:!0,updateData:function(e,t){return t}},e))}),[h])})},e.useSubscription=function(e,r){var n=t.useRef(r);n.current=r;var o=t.useContext(a),i=e.client||o,s={query:e.query,variables:e.variables};t.useEffect((function(){var e=i.createSubscription(s).subscribe({next:function(e){n.current(e)},error:function(){e.unsubscribe()},complete:function(){e.unsubscribe()}});return function(){e.unsubscribe()}}),[])},Object.defineProperty(e,"__esModule",{value:!0})})); |
@@ -35,4 +35,6 @@ import * as React from 'react' | ||
operation: Operation, | ||
options: UseClientRequestOptions<Variables> | ||
options: UseClientRequestOptions<any, Variables> | ||
): CacheKeyObject | ||
getCache(cacheKey: CacheKeyObject): undefined | object | ||
saveCache(cacheKey: CacheKeyObject, value: object): void | ||
getFetchOptions<Variables = object>( | ||
@@ -54,3 +56,3 @@ operation: Operation<Variables>, | ||
query: string, | ||
options?: UseClientRequestOptions<Variables> | ||
options?: UseClientRequestOptions<ResponseData, Variables> | ||
): [ | ||
@@ -68,3 +70,3 @@ FetchData<ResponseData, Variables, TGraphQLError>, | ||
query: string, | ||
options?: UseQueryOptions<Variables> | ||
options?: UseQueryOptions<ResponseData, Variables> | ||
): UseQueryResult<ResponseData, Variables, TGraphQLError> | ||
@@ -78,3 +80,3 @@ | ||
query: string, | ||
options?: UseClientRequestOptions<Variables> | ||
options?: UseClientRequestOptions<ResponseData, Variables> | ||
): [ | ||
@@ -92,3 +94,3 @@ FetchData<ResponseData, Variables, TGraphQLError>, | ||
query: string, | ||
options?: UseClientRequestOptions<Variables> | ||
options?: UseClientRequestOptions<ResponseData, Variables> | ||
): [ | ||
@@ -177,3 +179,3 @@ FetchData<ResponseData, Variables, TGraphQLError>, | ||
export interface UseClientRequestOptions<Variables = object> { | ||
export interface UseClientRequestOptions<ResponseData = any, Variables = object> { | ||
useCache?: boolean | ||
@@ -186,8 +188,8 @@ isMutation?: boolean | ||
fetchOptionsOverrides?: object | ||
updateData?(previousData: any, data: any): any | ||
updateData?(previousData: ResponseData, data: ResponseData): any | ||
client?: GraphQLClient | ||
} | ||
export interface UseQueryOptions<Variables = object> | ||
extends UseClientRequestOptions<Variables> { | ||
export interface UseQueryOptions<ResponseData = any, Variables = object> | ||
extends UseClientRequestOptions<ResponseData, Variables> { | ||
ssr?: boolean | ||
@@ -210,3 +212,3 @@ skip?: boolean | ||
refetch( | ||
options?: UseQueryOptions<Variables> | ||
options?: UseQueryOptions<ResponseData, Variables> | ||
): Promise<UseClientRequestResult<ResponseData, TGraphQLError>> | ||
@@ -222,3 +224,3 @@ } | ||
type FetchData<ResponseData, Variables = object, TGraphQLError = object> = ( | ||
options?: UseClientRequestOptions<Variables> | ||
options?: UseClientRequestOptions<ResponseData, Variables> | ||
) => Promise<UseClientRequestResult<ResponseData, TGraphQLError>> | ||
@@ -225,0 +227,0 @@ |
{ | ||
"name": "graphql-hooks", | ||
"version": "5.4.0", | ||
"version": "5.4.1", | ||
"description": "Graphql Hooks", | ||
@@ -62,3 +62,3 @@ "main": "lib/graphql-hooks.js", | ||
"homepage": "https://github.com/nearform/graphql-hooks#readme", | ||
"gitHead": "3b1c33f502847f371bf1579e0bfc4edcb6dae522" | ||
"gitHead": "c57bb1ed02a6fece73de473920c9513d297f217d" | ||
} |
Sorry, the diff of this file is not supported yet
188306
3237