UNPKG

gqty

Version:

The No-GraphQL Client for TypeScript

158 lines (157 loc) • 6.75 kB
import type { BaseGeneratedSchema, FetchOptions } from '.'; import type { Cache } from '../Cache'; import type { GQtyError, RetryOptions } from '../Error'; import type { ScalarsEnumsHash, Schema } from '../Schema'; import type { Selection } from '../Selection'; import { type SchemaContext } from './context'; import type { Debugger } from './debugger'; import { type Unsubscribe } from './resolveSelections'; export type CreateResolversOptions = { aliasLength?: number; batchWindow?: number; cache: Cache; debugger?: Debugger; depthLimit: number; fetchOptions: FetchOptions; scalars: ScalarsEnumsHash; schema: Readonly<Schema>; parentContext?: SchemaContext; }; export type Resolvers<TSchema extends BaseGeneratedSchema> = { /** * Create internal parts for `resolve()` and `subscribe()`, useful for * custom fetching logics. The React package uses this funciton. */ createResolver: CreateResolverFn<TSchema>; /** * Query, mutation and subscription in a promise. * * Selections to queries and mutations are fetched with * `fetchOptions.fetcher`, the result is resolved with the cache updated * according to the current fetch policy * * Subscriptions are disconnected upon delivery of the first data message, * the cache is updated and the data is resolved, essentially behaving like * a promise. */ resolve: ResolveFn<TSchema>; /** * Query, mutation and subscription in an async generator. * * Subscription data continuously update the cache, while queries and * mutations are fetched once and then listen to future cache changes * from the same selections. * * This function subscribes to *cache changes*, termination of underlying * subscription (WebSocket/EventSource) does not stop this generator. * * Calling `.return()` does not terminate pending promises, use * `onSubscribe()` to acquire the unsubscribe function. */ subscribe: SubscribeFn<TSchema>; }; export type ResolverParts<TSchema extends BaseGeneratedSchema> = { /** * The schema accessors for capturing selections and reading values from the * cache. */ accessor: TSchema; /** * A container object for internal states. */ context: SchemaContext; /** * A promise that resolves the query, mutation or subscription. A one-off * counterpart to `subscribe()`. */ resolve: () => Promise<unknown>; /** * Restores the previous selections set from an internal cache, used during * refetches where selections must be cleared periodically to prevent stale * inputs. */ restorePreviousSelections: () => void; /** * The current selections set to be used for query building. */ selections: Set<Selection>; /** * Sends pending queries and continuously listens to cache changes. A * "streaming" counterpart to `resolve()`. */ subscribe: (callbacks?: { onComplete?: () => void; onError?: (error: Error | GQtyError) => void; onNext?: (value: unknown) => void; }) => () => void; }; export type CreateResolverFn<TSchema extends BaseGeneratedSchema> = (options?: ResolveOptions & SubscribeOptions) => ResolverParts<TSchema>; export type ResolveFn<TSchema extends BaseGeneratedSchema> = <TData = unknown>(fn: DataFn<TSchema, TData>, options?: ResolveOptions) => Promise<TData>; export type SubscribeFn<TSchema extends BaseGeneratedSchema> = <TData = unknown>(fn: DataFn<TSchema, TData>, options?: SubscribeOptions) => AsyncIterableIterator<TData> & { unsubscribe: Unsubscribe; }; export type DataFn<TSchema, TResult = unknown> = (schema: TSchema) => TResult; export type ResolverOptions = { /** * Defines how a query should fetch from the cache and network. * * - `default`: Serves the cached contents when it is fresh, and if they are * stale within `staleWhileRevalidate` window, fetches in the background and * updates the cache. Or simply fetches on cache stale or cache miss. During * SWR, a successful fetch will not notify cache updates. New contents are * served on next query. * - `no-store`: Always fetch and does not update on response. * GQty creates a temporary cache at query-level which immediately expires. * - `no-cache`: Always fetch, updates on response. * - `force-cache`: Serves the cached contents regardless of staleness. It * fetches on cache miss or a stale cache, updates cache on response. * - `only-if-cached`: Serves the cached contents regardless of staleness, * throws a network error on cache miss. * * _It takes effort to make sure the above stays true for all supported * frameworks, please consider sponsoring so we can dedicate even more time on * this._ */ cachePolicy?: RequestCache; /** Custom GraphQL extensions to be exposed to the query fetcher. */ extensions?: Record<string, unknown>; /** Retry strategy upon fetch failure. */ retryPolicy?: RetryOptions; onSelect?: SchemaContext['select']; operationName?: string; }; export type ResolveOptions = ResolverOptions & { /** * Awaits resolution it the query results in a fetch. Specify `false` to * immediately return the current cache, placeholder data will be returned on * a partial or complete cache miss. * * @default true */ awaitsFetch?: boolean; onFetch?: (fetchPromise: Promise<unknown>) => void; /** * When specified, query errors are called here instead of being thrown. */ onError?: (error: unknown) => void; }; export type SubscribeOptions = ResolverOptions & { /** * Intercept errors thrown from the underlying subscription client or query * fetcher. * * If omitted, the `subscribe()` generator throws and closes on the first * error, terminating other active subscriptions triggered from the same * selections. */ onError?: (error: unknown) => void; /** * Called when a subscription is established, receives an unsubscribe * function that immediately terminates the async generator and any pending * promise. * * @deprecated Use the `unsubscribe` method returned from `subscribe()` instead. */ onSubscribe?: (unsubscribe: Unsubscribe) => void; }; export declare const createResolvers: <TSchema extends BaseGeneratedSchema>({ aliasLength, batchWindow, cache: resolverCache, debugger: debug, depthLimit, fetchOptions, fetchOptions: { cachePolicy: defaultCachePolicy, retryPolicy: defaultRetryPoliy, }, scalars, schema, parentContext, }: CreateResolversOptions) => Resolvers<TSchema>;