mk_graphql library

Classes

A Link that injects authentication headers into every request.
Terminating Link that batches multiple concurrent GraphQL HTTP POST queries into a single HTTP array payload, via dio.Dio.
BigIntScalarConverter
Cache
Interface for normalized GraphQL cache implementations.
CancelToken
Controls cancellation of Dio's requests.
CompositeGraphQLRequest
Combines multiple GraphQLRequest instances into a single composed request.
DateTimeScalarConverter
Custom scalar converters for standard & custom GraphQL scalar types.
HTTP Link execution transport powered by dio.Dio.
DioLinkCancelTokenContextEntry
Context entry for attaching a dio.CancelToken to a Request.
DocumentNode
GraphQLClient
Central GraphQL Client managing cache, links, and operation requests.
GraphQLError
Represents a single GraphQL Error returned in a GraphQL response payload.
GraphQLErrorLocation
Represents location coordinates of an error inside a GraphQL query document.
GraphQLPaginator<TData, TVars, TItem>
A reactive pagination manager that executes GraphQL queries and accumulates items.
GraphQLRequest<TData, TVars>
Represents an immutable typed GraphQL request.
GraphQLResponse<TData>
A typed response emitted by GraphQLClient.request.
HiveCache
A Cache that persists the normalized record store to a Hive Box so it survives app restarts, while keeping every read/write on the fast in-memory InMemoryCache path — the box is only a durable mirror, updated in the background after each mutation.
Terminating Link for executing HTTP POST GraphQL requests via dio.Dio — an intentionally lightweight alternative to DioLink (no proactive GET-for-queries, no response-context headers, best-effort cancellation).
InMemoryCache
Normalized in-memory cache store.
JsonScalarConverter
LoggerOptions
Configuration options for logging GraphQL operations.
PaginationState<TItem>
Immutable state holding the current items and status of a paginated query.
RecordSource
Key-value storage map for normalized GraphQL entities and references.
RetryOptions
Configures automatic retry-with-backoff for a query (and, when explicitly set on the request, a mutation or subscription) on transient network failures.
Terminating Link for GraphQL over Server-Sent Events (SSE).
TokenPair
A session's access token, optional refresh token, and when they were issued/last refreshed.
TokenStorage
Persistent, secure storage for the session's TokenPair, shared by every GraphQLClient in the app through the i singleton.
Middleware Link that automatically injects __typename selection fields into all GraphQL document AST selection sets.
UnauthorizedContext
Normalized info about a possibly-unauthorized response, passed to IsUnauthorizedCallback — built the same way whether it came from a normal streamed Response or a thrown ServerException, so detection logic doesn't need to juggle two nullable inputs or duplicate checks for both cases.
Universal WebSocket Link for GraphQL Subscriptions.

Enums

AuthFailure
How AuthLink should react to a possibly-unauthorized response, decided by IsUnauthorizedCallback (or the built-in default when none is supplied).
ErrorPolicy
Defines how GraphQL field errors are handled during request execution.
FetchPolicy
Controls how GraphQLClient handles reading from cache vs querying network.
ResponseSource
Indicates where the response data originated from.

Extensions

GraphQLClientPaginationExtension on GraphQLClient
Extension adding pagination factories to GraphQLClient.
GraphQLExceptionExtension on GraphQLException
Helper extension to map GraphQL errors / exceptions to structured types.
GraphQLRequestExecutionExtension on GraphQLRequest<TData, TVars>
Extension adding direct execution, refetch, and pagination methods on GraphQLRequest.

Functions

autoMergeGraphQLData<TData>(GraphQLRequest<TData, dynamic> request, TData previous, TData incoming) → TData
Automatically merges previous and incoming GraphQL query data objects by converting them to JSON, deeply concatenating list fields, and parsing back using request.parseData.
cappedBackoffDelay({required int attempt, required Duration initialDelay, required Duration maxDelay, required double multiplier}) → Duration
Exponential backoff delay for attempt (0 = the first attempt, before any failure), starting at initialDelay and multiplying by multiplier for each subsequent attempt, capped at maxDelay so a long-lived failure (a dead server, no network) settles into a fixed, bounded retry cadence instead of growing forever. Shared by WebSocketLink's reconnect scheduling; RetryOptions uses its own attempt-counted variant since it isn't capped the same way.
classifyDioException(DioException e, StackTrace stackTrace) → LinkException
Classifies a dio.DioException into the matching DioLink*Exception — shared by every Dio-based terminating link (DioLink, SseLink) so connection failures (timeouts, cancellation, DNS/socket errors, bad TLS certificates, non-2xx statuses) are reported the same, structured way everywhere instead of each transport bucketing most of them into one generic exception.
computeRequestKey(GraphQLRequest request) → String
Canonical identity for a GraphQLRequest: same operation, same document text, and same variables (regardless of map key insertion order) all map to the same key. Shared by InMemoryCache's query storage keys, the in-flight request dedup map, and the active-watcher registry on GraphQLClient so all three agree on request identity.
dataToMap(dynamic data) → Map<String, dynamic>?
Helper to convert a typed data object (e.g. Freezed / JsonSerializable / Map) into a JSON map.
deepMergeJson(Map<String, dynamic> prev, Map<String, dynamic> incoming) → Map<String, dynamic>
Recursively merges two JSON maps, automatically concatenating any matching List fields and merging nested Maps, while updating new page metadata (e.g. pageInfo, cursors).

Typedefs

IsTokenExpiredCallback = FutureOr<bool> Function()
Optional callback that returns whether the current token is expired. If omitted, expiry is not checked proactively — only unauthorized responses trigger refresh.
IsUnauthorizedCallback = AuthFailure Function(UnauthorizedContext context)
Classifies a possibly-unauthorized response/exception into an AuthFailure. Receives a normalized UnauthorizedContext built the same way for both a streamed Response and a thrown ServerException, so custom detection logic can read errors/statusCode without caring which case it came from.
ItemExtractor<TData, TItem> = List<TItem> Function(TData data)
Extracts the list of items from a query response.
ItemMerger<TItem> = List<TItem> Function(List<TItem> current, List<TItem> incoming)
Merges existing items with newly fetched items. Defaults to appending.
KeyGetter = String? Function(Map<String, dynamic> data)
NextVariablesCallback<TData, TVars> = TVars? Function({required TVars currentVars, required TData lastData, required int totalLoaded})
Callback computing the next page's typed variables. Return null when there are no more pages.
OnRefreshCallback = FutureOr<Map<String, String>?> Function(GraphQLClient refreshClient)
Callback invoked when the access token is expired. Receives a plain GraphQLClient (no auth link attached) that can be used to perform the refresh request via its normal typed API (e.g. refreshClient.future(...)). Should return new headers to use (e.g. {'Authorization': 'Bearer <newToken>'}), or return null / throw to trigger token revocation.
OnRevokeTokenCallback = void Function()
Callback invoked when the token is revoked (refresh failed or server returned unauthorized and refresh is not possible).
RefreshCallback = FutureOr<TokenPair?> Function(GraphQLClient refreshClient, String refreshToken)
Performs token refresh given the currently stored refresh token — always non-null, since GraphQLClient only calls this when one is actually persisted (no stored refresh token revokes immediately without calling this at all) — and returns the new TokenPair to persist, or null/throws to revoke. Receives a plain GraphQLClient (no auth link attached) to run the refresh request via its normal typed API.
TokenHeaderCallback = FutureOr<Map<String, String>> Function(String token)
Callback that builds the auth headers (e.g. Authorization) for a given token, read from TokenStorage.i by the caller — only invoked when a token is actually stored, so token is always non-null.
Upload = MultipartFile
Represents an uploaded file scalar in GraphQL operations.
WebSocketPayloadCallback = FutureOr Function()

Exceptions / Errors

AppServerException
General server-side exception.
BadRequestException
Bad request / Validation failed exception.
CertificateException
The server's TLS/SSL certificate failed validation.
DioLinkCanceledException
Exception thrown when a request is cancelled in DioLink.
DioLinkCertificateException
Exception thrown when the server's TLS/SSL certificate fails validation.
DioLinkConnectionException
Exception thrown when there is no network connectivity, or the connection is refused/reset (DNS failure, socket error, etc).
DioLinkParserException
Exception thrown when response parsing fails in DioLink.
DioLinkServerException
Exception thrown when a server error occurs in DioLink.
DioLinkTimeoutException
Exception thrown when a network timeout occurs in DioLink.
DioLinkUnkownException
Exception thrown on generic unknown network errors in DioLink.
GraphQLException
Base class for all structured GraphQL exceptions.
HttpLinkCanceledException
Exception thrown when a request is cancelled in HttpLink via DioLinkCancelTokenContextEntry.
HttpLinkConnectionException
Exception thrown when there is no network connectivity, or the connection is refused/reset (DNS failure, socket error, etc) in HttpLink.
NetworkException
Network connection exception.
NotFoundException
Resource not found exception.
ParseException
Parse exception.
RequestCancelledException
Exception thrown when a GraphQL request is cancelled.
RevokeTokenException
Thrown internally when the auth token must be revoked.
TimeoutException
Request timeout exception.
UnAuthorizedException
Unauthorized / Unauthenticated exception.
ValidationException
Thrown when GraphQL input or query validation fails.