diff --git a/package.json b/package.json index a73a829..7dba66d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "http-react", - "version": "3.7.8", + "version": "3.7.9", "description": "React hooks for data fetching", "main": "dist/index.js", "scripts": { diff --git a/src/hooks/others.ts b/src/hooks/others.ts index 9e1b950..a319c3b 100644 --- a/src/hooks/others.ts +++ b/src/hooks/others.ts @@ -41,9 +41,9 @@ export function useFetchConfig(id?: unknown) { return thisConfig as FetchInit & FetchContextType } -export function useFetchSuspense( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useFetchSuspense( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { let o = typeof init === 'string' @@ -224,13 +224,13 @@ export function useSuccess(id: any) { * @deprecated - Use the useFetch hook instead * Get everything from a `useFetch` call using its id */ -export function useFetchId(id: any) { +export function useFetchId(id: any) { const defaultsKey = serialize({ idString: serialize(id) }) const def = fetcherDefaults.get(defaultsKey) - return useFetch({ + return useFetch({ id, default: def }) @@ -289,9 +289,9 @@ export function useResolve( /** * User a `GET` request */ -export function useGET( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useGET( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -302,9 +302,9 @@ export function useGET( /** * Use a `DELETE` request */ -export function useDELETE( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useDELETE( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -315,9 +315,9 @@ export function useDELETE( /** * Use a `HEAD` request */ -export function useHEAD( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useHEAD( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -328,9 +328,9 @@ export function useHEAD( /** * Use an `OPTIONS` request */ -export function useOPTIONS( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useOPTIONS( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -342,9 +342,9 @@ export function useOPTIONS( /** * Use a `POST` request */ -export function usePOST( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function usePOST( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -355,9 +355,9 @@ export function usePOST( /** * Use a `PUT` request */ -export function usePUT( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function usePUT( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -368,9 +368,9 @@ export function usePUT( /** * Use a `PATCH` request */ -export function usePATCH( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function usePATCH( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -381,9 +381,9 @@ export function usePATCH( /** * Use a `PURGE` request */ -export function usePURGE( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function usePURGE( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -394,9 +394,9 @@ export function usePURGE( /** * Use a `LINK` request */ -export function useLINK( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useLINK( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -407,9 +407,9 @@ export function useLINK( /** * Use an `UNLINK` request */ -export function useUNLINK( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useUNLINK( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -420,9 +420,9 @@ export function useUNLINK( /** * Use a request without making it automatically */ -export function useManualFetch( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useManualFetch( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { return useFetch(init, { ...options, @@ -433,15 +433,13 @@ export function useManualFetch( /** * Get a blob of the response. You can pass an `objectURL` property that will convet that blob into a string using `URL.createObjectURL` */ -export function useFetchBlob( - init: - | (FetchConfigType & { objectURL?: boolean }) - | string, - options?: FetchConfigTypeNoUrl & { +export function useFetchBlob( + init: (FetchConfigType & { objectURL?: boolean }) | string, + options?: FetchConfigTypeNoUrl & { objectURL?: boolean } ) { - return useFetch(init, { + return useFetch(init, { ...options, async resolver(res) { const blob = await res.blob() @@ -463,11 +461,11 @@ export function useFetchBlob( /** * Get a text of the response */ -export function useFetchText( - init: FetchConfigType | string, - options?: FetchConfigTypeNoUrl +export function useFetchText( + init: FetchConfigType | string, + options?: FetchConfigTypeNoUrl ) { - return useFetch(init, { + return useFetch(init, { ...options, async resolver(res) { const text = await res.text() @@ -503,21 +501,21 @@ export function useRequestEnd(id: any) { /** * Debounce a fetch by the time given */ -export function useDebounceFetch( +export function useDebounceFetch( init: - | (Omit, 'debounce'> & { + | (Omit, 'debounce'> & { debounce?: TimeSpan }) | string | Request, - options?: Omit, 'debounce'> & { + options?: Omit, 'debounce'> & { debounce?: TimeSpan } ) { // @ts-ignore - auto can be present in the first arg const canDebounce = init?.auto ?? options?.auto ?? true - const res = useFetch(init, { + const res = useFetch(init, { ...options, auto: false }) @@ -550,7 +548,7 @@ export function useGql( value: T variables: VT }, - cfg: FetchConfigTypeNoUrl & { + cfg: FetchConfigTypeNoUrl & { /** * GraphQL variables */ diff --git a/src/hooks/use-fetch.ts b/src/hooks/use-fetch.ts index 5f00972..524a8f4 100644 --- a/src/hooks/use-fetch.ts +++ b/src/hooks/use-fetch.ts @@ -82,9 +82,9 @@ const temporaryFormData = new Map() /** * Fetch hook */ -export function useFetch( - init: FetchConfigType | string | Request, - options?: FetchConfigTypeNoUrl +export function useFetch( + init: FetchConfigType | string | Request, + options?: FetchConfigTypeNoUrl ) { const $ctx = useHRFContext() @@ -129,7 +129,7 @@ export function useFetch( ...options, // @ts-expect-error id: init?.id ?? init?.key - } as FetchConfigType) + } as Required>) const { onOnline = ctx.onOnline, @@ -143,7 +143,7 @@ export function useFetch( method = isRequest ? init.method : (METHODS.GET as HTTP_METHODS), headers = {} as Headers, body = undefined as unknown as Body, - formatBody = e => JSON.stringify(e), + formatBody = (e: any) => JSON.stringify(e), resolver = isFunction(ctx.resolver) ? ctx.resolver : DEFAULT_RESOLVER, onError, auto = isDefined(ctx.auto) ? ctx.auto : true, @@ -523,7 +523,7 @@ export function useFetch( const fetchData = useCallback( async function fetchData( - c: { headers?: any; body?: BodyType; query?: any; params?: any } = {} + c: { headers?: any; body?: any; query?: any; params?: any } = {} ) { const rawUrl = (hasBaseUrl(url) @@ -1790,7 +1790,7 @@ Learn more: https://httpr.vercel.app/docs/api#suspense loadingFirst: boolean isLoadingFirst: boolean expiration: Date - data: FetchDataType + data: 0 extends 1 & TransformData ? FetchDataType : TransformData isPending?: boolean loading: boolean isLoading: boolean @@ -1806,7 +1806,7 @@ Learn more: https://httpr.vercel.app/docs/api#suspense ) => FetchDataType fetcher: ImperativeFetch abort: () => void - config: FetchConfigType & { + config: Required> & { baseUrl: string url: string rawUrl: string diff --git a/src/types/index.ts b/src/types/index.ts index 37d3fa8..99c7e37 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -1,29 +1,29 @@ export type HTTP_METHODS = - | 'GET' - | 'DELETE' - | 'HEAD' - | 'OPTIONS' - | 'POST' - | 'PUT' - | 'PATCH' - | 'PURGE' - | 'LINK' - | 'UNLINK' + | "GET" + | "DELETE" + | "HEAD" + | "OPTIONS" + | "POST" + | "PUT" + | "PATCH" + | "PURGE" + | "LINK" + | "UNLINK"; export type FetchContextType = { - clientOnly?: boolean + clientOnly?: boolean; fetcher?( url: string, config: FetchConfigType ): Promise<{ - json?: any - data?: any - status?: number - blob?: any - text?: any - }> - headers?: any - baseUrl?: string + json?: any; + data?: any; + status?: number; + blob?: any; + text?: any; + }>; + headers?: any; + baseUrl?: string; /** * Sets the default (placeholder) value of request data. * @@ -37,65 +37,65 @@ export type FetchContextType = { * } */ value?: { - [key: string]: any - } + [key: string]: any; + }; defaults?: { [key: string]: { /** * The `id` passed to the request */ - id?: any + id?: any; /** * Default value for this request */ - value?: any - method?: HTTP_METHODS - } - } - suspense?: any[] - resolver?: (r: Response) => any - middleware?(incomindgData: any, previousData: any): any - transform?(fetchData: any): any - children?: any - auto?: boolean - memory?: boolean - refresh?: TimeSpan - attempts?: number - attemptInterval?: TimeSpan - revalidateOnFocus?: boolean - query?: any - params?: any - onOnline?: (e: { cancel: () => void }) => void - onOffline?: () => void - online?: boolean - retryOnReconnect?: boolean - cacheProvider?: CacheStoreType - revalidateOnMount?: boolean - cacheIfError?: boolean + value?: any; + method?: HTTP_METHODS; + }; + }; + suspense?: any[]; + resolver?: (r: Response) => any; + middleware?(incomindgData: any, previousData: any): any; + transform?(fetchData: any): any; + children?: any; + auto?: boolean; + memory?: boolean; + refresh?: TimeSpan; + attempts?: number; + attemptInterval?: TimeSpan; + revalidateOnFocus?: boolean; + query?: any; + params?: any; + onOnline?: (e: { cancel: () => void }) => void; + onOffline?: () => void; + online?: boolean; + retryOnReconnect?: boolean; + cacheProvider?: CacheStoreType; + revalidateOnMount?: boolean; + cacheIfError?: boolean; onFetchStart?( req: Request, config: FetchConfigType, ctx: FetchContextType - ): void + ): void; onFetchEnd?( res: Response, config: FetchConfigType, ctx: FetchContextType - ): void - maxCacheAge?: TimeSpan -} & Omit + ): void; + maxCacheAge?: TimeSpan; +} & Omit; export type CacheStoreType = { - get(k?: any): any - set(k?: any, v?: any): any - remove?(k?: any): any -} + get(k?: any): any; + set(k?: any, v?: any): any; + remove?(k?: any): any; +}; -export type CustomResponse = Omit & { - json(): Promise -} +export type CustomResponse = Omit & { + json(): Promise; +}; -export type RequestWithBody = ( +export type RequestWithBody = ( /** * The request url */ @@ -103,75 +103,75 @@ export type RequestWithBody = ( /** * The request configuration */ - reqConfig?: Omit, 'suspense'> & { + reqConfig?: Omit, "suspense"> & { /** * Default value */ - default?: R + default?: R; /** * Request query */ - query?: any + query?: any; /** * The function that formats the body */ - formatBody?: any + formatBody?: any; /** * Request params (like Express) */ - params?: any + params?: any; /** * The function that returns the resolved data */ - resolver?: (r: CustomResponse) => any + resolver?: (r: CustomResponse) => any; /** * A function that will run when the request fails */ - onError?(error: Error): void + onError?(error: Error): void; /** * A function that will run when the request completes succesfuly */ - onResolve?(data: R, res: CustomResponse): void - cacheProvider?: CacheStoreType + onResolve?(data: R, res: CustomResponse): void; + cacheProvider?: CacheStoreType; } ) => Promise<{ - error: any - data: R - config: RequestInit - status: number - res: CustomResponse -}> + error: any; + data: R; + config: RequestInit; + status: number; + res: CustomResponse; +}>; export type TimeSpan = | number - | `${string} ${'ms' | 'sec' | 'min' | 'h' | 'd' | 'we' | 'mo' | 'y'}` + | `${string} ${"ms" | "sec" | "min" | "h" | "d" | "we" | "mo" | "y"}`; /** * An imperative version of the `useFetch` hook */ export type ImperativeFetch = { - get: RequestWithBody - delete: RequestWithBody - head: RequestWithBody - options: RequestWithBody - post: RequestWithBody - put: RequestWithBody - patch: RequestWithBody - purge: RequestWithBody - link: RequestWithBody - unlink: RequestWithBody - config?: FetchContextType & FetchInit -} + get: RequestWithBody; + delete: RequestWithBody; + head: RequestWithBody; + options: RequestWithBody; + post: RequestWithBody; + put: RequestWithBody; + patch: RequestWithBody; + purge: RequestWithBody; + link: RequestWithBody; + unlink: RequestWithBody; + config?: FetchContextType & FetchInit; +}; -export type FetchConfigType = Omit< +export type FetchConfigType = Omit< RequestInit, - 'body' | 'headers' + "body" | "headers" > & { - headers?: any + headers?: any; /** * The fetch key */ - key?: any + key?: any; /** * The middleware function should return the data that will be commited to the state. It can be used for pagination, logging, etc. * @@ -180,58 +180,58 @@ export type FetchConfigType = Omit< middleware?( incomindgData: FetchDataType, previousData: FetchDataType - ): FetchDataType - transform?(fetchData: FetchDataType): FetchDataType + ): FetchDataType; + transform?(fetchData: FetchDataType): TransformData; fetcher?( url: string, - config: FetchConfigType + config: FetchConfigType ): Promise<{ - json?: any - data?: FetchDataType - status?: number - blob?: any - text?: any - }> - body?: any + json?: any; + data?: FetchDataType; + status?: number; + blob?: any; + text?: any; + }>; + body?: any; /** * Any serializable id. This is optional. */ - id?: any + id?: any; /** * url of the resource to fetch */ - url?: string + url?: string; /** * Default data value */ - default?: FetchDataType + default?: FetchDataType; /** * Refresh interval (in seconds) to re-fetch the resource * @default 0 */ - refresh?: TimeSpan + refresh?: TimeSpan; /** * This will prevent automatic requests. * By setting this to `false`, requests will * only be made by calling `reFetch()` * @default true */ - auto?: boolean + auto?: boolean; /** * Responses are saved in memory and used as default data. * If `false`, the `default` prop will be used instead. * @default true */ - memory?: boolean - onSubmit?: 'reset' | ((form: HTMLFormElement, data: FormData) => void) + memory?: boolean; + onSubmit?: "reset" | ((form: HTMLFormElement, data: FormData) => void); /** * Function to run when request is resolved succesfuly */ - onResolve?: (data: FetchDataType, res?: Response) => void + onResolve?: (data: FetchDataType, res?: Response) => void; /** * Override the cache for this specific request */ - cacheProvider?: CacheStoreType + cacheProvider?: CacheStoreType; /** * Function to run when data is mutated */ @@ -241,23 +241,23 @@ export type FetchConfigType = Omit< * An imperative version of `useFetche` */ fetcher: ImperativeFetch - ) => void + ) => void; /** * Function to run when the request fails */ - onError?: (error: Error, req?: Response) => void + onError?: (error: Error, req?: Response) => void; /** * Function to run when a request is aborted */ - onAbort?: () => void + onAbort?: () => void; /** * Whether a change in deps will cancel a queued request and make a new one */ - cancelOnChange?: boolean + cancelOnChange?: boolean; /** * Parse as json by default */ - resolver?: (d: CustomResponse) => any + resolver?: (d: CustomResponse) => any; /** * The ammount of attempts if request fails * @default 1 @@ -265,21 +265,21 @@ export type FetchConfigType = Omit< attempts?: | number | ((q: { - status: number - res: Response - error: Error - completedAttempts: number - }) => number | undefined | void) + status: number; + res: Response; + error: Error; + completedAttempts: number; + }) => number | undefined | void); /** * The interval at which to run attempts on request fail * @default 0 */ - attemptInterval?: TimeSpan + attemptInterval?: TimeSpan; /** * If a request should be made when the tab is focused. This currently works on browsers * @default false */ - revalidateOnFocus?: boolean + revalidateOnFocus?: boolean; /** * If `false`, revalidation will only happen when props passed to the `useFetch` change. * For example, you may want to have a component that should @@ -292,79 +292,82 @@ export type FetchConfigType = Omit< * Note that the behaviour when props change is the same. * @default true */ - revalidateOnMount?: boolean + revalidateOnMount?: boolean; /** * This will run when connection is interrupted */ - onOffline?: () => void + onOffline?: () => void; /** * This will run when connection is restored */ - onOnline?: (e: { cancel: () => void }) => void + onOnline?: (e: { cancel: () => void }) => void; /** * If the request should retry when connection is restored * @default true */ - retryOnReconnect?: boolean + retryOnReconnect?: boolean; /** * If using inside a `` */ - suspense?: boolean + suspense?: boolean; /** * Override base url */ - baseUrl?: string + baseUrl?: string; /** * Request method */ - method?: HTTP_METHODS + method?: HTTP_METHODS; /** * URL search params */ - query?: any + query?: any; /** * URL params */ - params?: any + params?: any; /** * Customize how body is formated for the request. By default it will be sent in JSON format * but you can set it to false if for example, you are sending a `FormData` * body, or to `b => serialize(b)` for example, if you want to send JSON data * (the last one is the default behaviour so in that case you can ignore it) */ - formatBody?: boolean | ((b: BodyType) => any) + formatBody?: boolean | ((b: any) => any); /** * The time to wait before revalidation after props change */ - debounce?: TimeSpan + debounce?: TimeSpan; /** * Will run when the request is sent */ - onFetchStart?: FetchContextType['onFetchStart'] + onFetchStart?: FetchContextType["onFetchStart"]; /** * Will run when the response is received */ - onFetchEnd?: FetchContextType['onFetchEnd'] + onFetchEnd?: FetchContextType["onFetchEnd"]; /** * If `true`, the last resolved value be returned as `data` if the request fails. If `false`, the default value will be returned instead * * @default true */ - cacheIfError?: boolean + cacheIfError?: boolean; /** * The max age a page should be cached (with no request) */ - maxCacheAge?: TimeSpan -} + maxCacheAge?: TimeSpan; +}; // If first argument is a string -export type FetchConfigTypeNoUrl = Omit< - FetchConfigType, - 'url' -> +export type FetchConfigTypeNoUrl< + FetchDataType = any, + TransformData = any +> = Omit, "url">; /** * Create a configuration object to use in a 'useFetche' call */ -export type FetchInit = FetchConfigType +export type FetchInit = FetchConfigType< + FDT, + TransformData +>; diff --git a/src/utils/index.ts b/src/utils/index.ts index 2d9cbf3..828a217 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -1,7 +1,7 @@ -'use client' -import { useLayoutEffect, useEffect, useMemo } from 'react' -import { useGql } from '../hooks/others' -import { useFetch } from '../hooks/use-fetch' +"use client"; +import { useLayoutEffect, useEffect, useMemo } from "react"; +import { useGql } from "../hooks/others"; +import { useFetch } from "../hooks/use-fetch"; import { abortControllers, @@ -11,10 +11,10 @@ import { requestInitialTimes, requestsProvider, runningMutate, - valuesMemory -} from '../internal' + valuesMemory, +} from "../internal"; -import { UNITS_MILISECONDS_EQUIVALENTS } from '../internal/constants' +import { UNITS_MILISECONDS_EQUIVALENTS } from "../internal/constants"; import { CacheStoreType, @@ -23,8 +23,8 @@ import { FetchInit, TimeSpan, FetchConfigTypeNoUrl, - FetchConfigType -} from '../types' + FetchConfigType, +} from "../types"; import { gql, hasBaseUrl, @@ -32,119 +32,119 @@ import { isFunction, queue, serialize, - windowExists -} from './shared' + windowExists, +} from "./shared"; export function getMiliseconds(v: TimeSpan): number { - if (typeof v === 'number') return v + if (typeof v === "number") return v; - const [amount, unit] = (v as string).split(' ') + const [amount, unit] = (v as string).split(" "); - const amountNumber = parseFloat(amount) + const amountNumber = parseFloat(amount); if (!(unit in UNITS_MILISECONDS_EQUIVALENTS)) { - return amountNumber + return amountNumber; } // @ts-ignore - This should return the value in miliseconds - return amountNumber * UNITS_MILISECONDS_EQUIVALENTS[unit] + return amountNumber * UNITS_MILISECONDS_EQUIVALENTS[unit]; } export function getTimePassed(key: any) { return ( Date.now() - (isDefined(requestInitialTimes.get(key)) ? requestInitialTimes.get(key) : 0) - ) + ); } export const createImperativeFetch = (ctx: FetchContextType) => { const keys = [ - 'GET', - 'DELETE', - 'HEAD', - 'OPTIONS', - 'POST', - 'PUT', - 'PATCH', - 'PURGE', - 'LINK', - 'UNLINK' - ] - - const { baseUrl } = ctx + "GET", + "DELETE", + "HEAD", + "OPTIONS", + "POST", + "PUT", + "PATCH", + "PURGE", + "LINK", + "UNLINK", + ]; + + const { baseUrl } = ctx; return { ...Object.fromEntries( new Map( - keys.map(k => [ + keys.map((k) => [ k.toLowerCase(), (url, config = {}) => (useFetch as any)[k.toLowerCase()]( hasBaseUrl(url) ? url : baseUrl + url, { ...ctx, - ...config + ...config, } - ) + ), ]) ) ), - config: ctx - } as ImperativeFetch -} + config: ctx, + } as ImperativeFetch; +}; export const useIsomorphicLayoutEffect = windowExists ? useLayoutEffect - : useEffect + : useEffect; /** * Revalidate requests that match an id or ids */ export function revalidate(id: any | any[], __reval__ = true) { if (Array.isArray(id)) { - id.map(reqId => { + id.map((reqId) => { if (isDefined(reqId)) { - const key = serialize(reqId) + const key = serialize(reqId); - const resolveKey = serialize({ idString: key }) + const resolveKey = serialize({ idString: key }); if (__reval__) { - previousConfig.set(resolveKey, undefined) + previousConfig.set(resolveKey, undefined); } - abortControllers.get(resolveKey)?.abort() + abortControllers.get(resolveKey)?.abort(); if (__reval__) { if (!isPending(key)) { queue(() => { requestsProvider.emit(key, { loading: true, - error: false - }) - }) + error: false, + }); + }); } } } - }) + }); } else { if (isDefined(id)) { - const key = serialize(id) + const key = serialize(id); - const resolveKey = serialize({ idString: key }) + const resolveKey = serialize({ idString: key }); if (__reval__) { - previousConfig.set(resolveKey, undefined) + previousConfig.set(resolveKey, undefined); } - abortControllers.get(resolveKey)?.abort() + abortControllers.get(resolveKey)?.abort(); if (__reval__) { if (!isPending(key)) { queue(() => { requestsProvider.emit(key, { loading: true, - error: false - }) - }) + error: false, + }); + }); } } } @@ -152,40 +152,40 @@ export function revalidate(id: any | any[], __reval__ = true) { } export function revalidateKey(key: any) { - revalidate([key]) + revalidate([key]); } export function cancelRequest(id: any | any[]) { if (Array.isArray(id)) { - id.map(reqId => { + id.map((reqId) => { if (isDefined(reqId)) { const key = serialize({ - idString: serialize(reqId) - }) + idString: serialize(reqId), + }); if (isPending(key)) { - revalidate(reqId, false) + revalidate(reqId, false); queue(() => { requestsProvider.emit(key, { loading: false, - error: false - }) - }) + error: false, + }); + }); } } - }) + }); } else { if (isDefined(id)) { const key = serialize({ - idString: serialize(id) - }) + idString: serialize(id), + }); if (isPending(key)) { - revalidate(id, false) + revalidate(id, false); queue(() => { requestsProvider.emit(key, { loading: false, - error: false - }) - }) + error: false, + }); + }); } } } @@ -198,63 +198,63 @@ export function cancelRequest(id: any | any[]) { */ export function queryProvider( queries: { - [e in keyof R]: R[e] + [e in keyof R]: R[e]; }, providerConfig?: { defaults?: { - [key in keyof R]?: Partial>['value']> - } + [key in keyof R]?: Partial>["value"]>; + }; config?: { /** * The base url */ - baseUrl?: string + baseUrl?: string; /** * Any aditional headers */ headers?: { - [key: string]: any - } + [key: string]: any; + }; /** * The caching mechanism */ - cacheProvider?: CacheStoreType - } + cacheProvider?: CacheStoreType; + }; } ) { - type QuerysType = typeof queries + type QuerysType = typeof queries; return function useQuery

( queryName: P, otherConfig?: Omit< FetchInit< QuerysType[P] extends ReturnType - ? QuerysType[P]['value'] + ? QuerysType[P]["value"] : any >, - 'url' + "url" > & { default?: QuerysType[P] extends ReturnType - ? QuerysType[P]['value'] - : any + ? QuerysType[P]["value"] + : any; variables?: QuerysType[P] extends ReturnType - ? QuerysType[P]['variables'] - : any - graphqlPath?: string + ? QuerysType[P]["variables"] + : any; + graphqlPath?: string; } ) { - const { defaults } = providerConfig || {} + const { defaults } = providerConfig || {}; - const thisDefaults = (defaults || ({} as any))?.[queryName] + const thisDefaults = (defaults || ({} as any))?.[queryName]; const queryVariables = { ...thisDefaults?.variables, - ...(otherConfig as any)?.variables - } + ...(otherConfig as any)?.variables, + }; - const { config = {} } = providerConfig || {} + const { config = {} } = providerConfig || {}; - const { cacheProvider, ...others } = config + const { cacheProvider, ...others } = config; const g = useGql(queries[queryName] as any, { cacheProvider: config?.cacheProvider, @@ -276,7 +276,7 @@ export function queryProvider( headers: { ...others?.headers, ...thisDefaults?.headers, - ...otherConfig?.headers + ...otherConfig?.headers, }, ...{ __fromProvider: true }, default: { @@ -287,38 +287,38 @@ export function queryProvider( * 'value' property (when using the `gql` function) */ // @ts-ignore - otherConfig?.default) as R[P]['value'] + otherConfig?.default) as R[P]["value"], }, - variables: queryVariables - }) + variables: queryVariables, + }); const thisData = useMemo( () => ({ ...g?.data, - variables: queryVariables + variables: queryVariables, }), [serialize({ data: g?.data, queryVariables })] - ) + ); return { ...g, config: { ...g?.config, - config: undefined + config: undefined, }, - data: thisData - } as Omit & { + data: thisData, + } as Omit & { data: { data: QuerysType[P] extends ReturnType - ? QuerysType[P]['value'] - : any - errors?: any[] + ? QuerysType[P]["value"] + : any; + errors?: any[]; variables: QuerysType[P] extends ReturnType - ? QuerysType[P]['variables'] - : any - } - } - } + ? QuerysType[P]["variables"] + : any; + }; + }; + }; } /** @@ -329,50 +329,50 @@ export function mutateData( ) { for (let pair of pairs) { try { - const [k, v, _revalidate] = pair - const key = serialize({ idString: serialize(k) }) - const requestCallId = '' + const [k, v, _revalidate] = pair; + const key = serialize({ idString: serialize(k) }); + const requestCallId = ""; if (isFunction(v)) { - let newVal = v(cacheForMutation.get(key)) - runningMutate.set(key, undefined) + let newVal = v(cacheForMutation.get(key)); + runningMutate.set(key, undefined); requestsProvider.emit(key, { data: newVal, isMutating: true, - requestCallId - }) + requestCallId, + }); if (_revalidate) { - previousConfig.set(key, undefined) - requestsProvider.emit(serialize(k), {}) + previousConfig.set(key, undefined); + requestsProvider.emit(serialize(k), {}); } queue(() => { - valuesMemory.set(key, newVal) - cacheForMutation.set(key, newVal) - }) + valuesMemory.set(key, newVal); + cacheForMutation.set(key, newVal); + }); } else { - runningMutate.set(key, undefined) + runningMutate.set(key, undefined); requestsProvider.emit(key, { requestCallId, isMutating: true, - data: v - }) + data: v, + }); if (_revalidate) { - previousConfig.set(key, undefined) - requestsProvider.emit(serialize(k), {}) + previousConfig.set(key, undefined); + requestsProvider.emit(serialize(k), {}); } queue(() => { - valuesMemory.set(key, v) - cacheForMutation.set(key, v) - }) + valuesMemory.set(key, v); + cacheForMutation.set(key, v); + }); } } catch (err) {} } } -export function fetchOptions( - init: string | FetchConfigType, - options?: Omit, 'url'> +export function fetchOptions( + init: string | FetchConfigType, + options?: FetchConfigTypeNoUrl ) { - return typeof init === 'string' - ? { url: init, ...options } - : (init as FetchConfigType) + return ( + typeof init === "string" ? { url: init, ...options } : init + ) as FetchConfigType; }