Skip to main content

mk_graphql 1.2.1-dev.2 copy "mk_graphql: ^1.2.1-dev.2" to clipboard
mk_graphql: ^1.2.1-dev.2 copied to clipboard

A clean, modern, simplified GraphQL client for Dart & Flutter with normalized caching, composable links, and stream-based operation execution.

1.2.1-dev.2 #

  • Breaking: Reworked token storage. TokenStorage is now a concrete singleton (TokenStorage.i, backed by flutter_secure_storage + shared_preferences) instead of an injectable abstract interface — SecureTokenStorage and the tokenStorage: constructor parameter are removed; GraphQLClient always talks to TokenStorage.i. AuthToken is replaced by TokenPair (now Equatable). Removed GraphQLClient.setAuthToken(), .clearAuthToken(), and .onAuthTokenChange — there's no longer a change-notification stream; drive app-wide auth state off AuthLink.registerRevokeTokenListener(...) and TokenStorage.i.setTokenListener(...) instead. .isAuthenticated remains and now reads TokenStorage.i.accessToken.
  • Breaking: Renamed the tokenHeader parameter on GraphQLClient/AuthLink to accessTokenHeader. Added a new optional refreshTokenHeader callback — when provided, its headers are attached to every request sent through the internal refresh client (the one passed into onTokenRefresh/refreshCallback) instead of accessTokenHeader, for refresh endpoints that expect the refresh token itself as a header.
  • Breaking: Renamed AccessTokenCallback to TokenHeaderCallback and changed its signature from Function() to Function(String token) — accessTokenHeader/refreshTokenHeader/SseLink.tokenHeader now receive the current token (read from TokenStorage.i by the caller) as an argument instead of having to read TokenStorage.i themselves, and are only invoked when a token is actually stored (so token is never null in practice, and the callback's return type is now non-nullable Map<String, String> too). refreshTokenHeader still has no default — the refresh token normally reaches your refresh endpoint via the refreshCallback parameter instead (for a body/variable); pass refreshTokenHeader only if it should also/instead go out as a header.
  • Breaking: HttpLink and BatchLink now run on dio.Dio instead of package:http — their client: constructor parameter is now dio.Dio? instead of http.Client?, and the http package dependency is dropped entirely. HttpLink's multipart upload detection now matches DioLink's: pass Upload/dio.MultipartFile values (not http.MultipartFile, which the public Upload typedef never pointed to) as GraphQL variables. HttpLinkConnectionException/HttpLinkCanceledException are unchanged and still thrown for the equivalent failures. HttpLink keeps its manual best-effort cancellation race (rather than delegating to Dio's own cancelToken:) since that still depends on adapter cooperation it doesn't want to require.
  • Added isUnauthorized to GraphQLClient/AuthLink — an optional AuthFailure Function(UnauthorizedContext context) that classifies a possibly-unauthorized response/exception, so a custom API's own convention (a non-standard error code, message, or status field) can drive the client's behavior instead of the built-in default. UnauthorizedContext normalizes errors/statusCode/errorCode the same way whether the failure came from a streamed Response or a thrown ServerException, so detection logic doesn't need to juggle two nullable inputs. AuthFailure has three outcomes: none (pass through), refresh (attempt a refresh and retry once), and revoke (skip the refresh attempt entirely and revoke immediately — for failures a refresh wouldn't fix, like a valid token that simply lacks permission). The built-in default maps extensions.code/HTTP status of UNAUTHORIZED/UNAUTHENTICATED/401 to refresh and FORBIDDEN/403 to revoke (previously grouped with 401 and always attempted a refresh first).
  • Internal: Consolidated GraphQL error parsing/mapping into graphql_error_mapper.dart (extractErrorCode, mapGraphQLError(s)) — previously the extensions['code'] extraction and the gql_exec.GraphQLError → this package's GraphQLError mapping were each hand-rolled in three-plus places (GraphQLExceptionExtension, GraphQLClient._executeNetworkRequest, UnauthorizedContext.errorCode).
  • Fix: A revoked/failed-refresh request no longer surfaces to future()/stream() as a generic AppServerException('No response received from GraphQL server.'). AuthLink now always surfaces the real cause: the original FORBIDDEN/401 response or exception when there's nothing more specific, or a RevokeTokenException describing why the refresh attempt itself failed (wrapping whatever onTokenRefresh/refreshCallback threw) when that's more specific.
  • Fix: HttpLink and BatchLink now parse responses with the same ResponseParser DioLink/SseLink/WebSocketLink already use, instead of a hand-rolled parse that kept only errors[].message and silently dropped locations/path/extensions — meaning extensions.code (which AuthLink's unauthorized detection and GraphQLExceptionExtension both key off) was lost for any error routed through either link.
  • Split auth_link.dart into auth_types.dart (typedefs, AuthFailure, UnauthorizedContext), refresh_header_link.dart (the internal link refreshTokenHeader uses), and auth_link.dart (just AuthLink itself) — the public API (package:mk_graphql/mk_graphql.dart) is unchanged.
  • Fix: SseLink no longer has its own duplicated, non-deduped 401-refresh logic. It now surfaces an unauthorized response as a ServerException (via the same classifyDioException classification DioLink uses) so an outer AuthLink catches and retries it through its existing single-flight refresh lock — the same path every other link goes through — instead of racing its own independent retry against AuthLink's.
  • HttpLink: Added cancellation support via the existing DioLinkCancelTokenContextEntry context entry (the same CancelToken used everywhere else in the pipeline) — cancelling stops HttpLink from waiting on the in-flight request and throws HttpLinkCanceledException. Note package:http has no request-abort primitive, so the underlying request itself keeps running in the background; it's just no longer waited on. Also added HttpLinkConnectionException for connection-level failures (http.ClientException, e.g. DNS/socket errors) and reclassified malformed response bodies as ResponseFormatException — previously both fell into a single generic ServerException bucket. Added test coverage (previously untested).
  • Fix: AuthLink's internal token-refresh client now shares the exact same configured Dio instance as the rest of the pipeline (same defaultHeaders, same interceptors), instead of silently falling back to a second, bare Dio() whenever the app didn't pass its own dio: to GraphQLClient(...). Previously, refresh requests would go out missing any headers configured via defaultHeaders.
  • Fix: Fixed a race in WebSocketLink where two subscriptions started back-to-back, before the first connection finished handshaking, could each open their own WebSocketChannel — the second silently replacing (and leaking) the first. Connection attempts are now single-flight, mirroring AuthLink's existing refresh dedup.
  • Resource cleanup: GraphQLClient.dispose(), AuthLink, SseLink, HttpLink, and BatchLink now close the Dio/http.Client they created for themselves (never one the caller passed in — that stays the caller's to close). BatchLink.dispose() also cancels its pending batch timer and fails any queued-but-undispatched requests instead of leaving their callers hanging forever.
  • Performance: TypenameLink and the query-document printing done by every terminating link (DioLink, SseLink, WebSocketLink, HttpLink, BatchLink) and by LoggerLink now cache their result per DocumentNode instance. Generated requests hold one static final DocumentNode per operation (and hand-written ones resolve through the shared parse cache), so the same instance recurs on every call of a given operation — previously each call re-walked and rebuilt the whole AST (TypenameLink) and re-serialized it back to a query string (printNode, on every single network request) from scratch.
  • Internal: De-duplicated the twice-written dio.Response JSON-body coercion in DioLink into one helper.

1.2.0 #

  • Breaking: OnRefreshCallback (used by onTokenRefresh on GraphQLClient, AuthLink, and SseLink) now receives a plain GraphQLClient (no auth link attached) instead of a raw DioLink, so refresh logic can use the typed client API (refreshClient.future(...), .stream(...)) instead of hand-rolling a raw HTTP request.
  • Fix: AuthLink now also catches a thrown ServerException (e.g. DioLinkServerException, raised for a real non-2xx HTTP status) and treats a 401/403 status — or a parsed UNAUTHORIZED/UNAUTHENTICATED/FORBIDDEN GraphQL error code — as unauthorized. Previously the refresh-and-retry flow only fired for HTTP 200 responses carrying a GraphQL error payload, silently skipping real HTTP-level 401/403s.
  • Managed token storage: GraphQLClient can now own its auth session end-to-end via the new refreshCallback parameter and TokenStorage (backed by flutter_secure_storage through the new SecureTokenStorage, whose onChange is driven by FlutterSecureStorage.registerListener; injectable for tests via tokenStorage). Supply refreshCallback: (refreshClient, refreshToken) async => AuthToken(...) and the client reads/writes the Authorization header and persists refreshed tokens itself — no more app-side token storage plumbing. New GraphQLClient.setAuthToken() (call after login), .clearAuthToken() (call on logout), .isAuthenticated, and .onAuthTokenChange (a Stream<AuthToken?> that emits on every login/refresh and null on logout or a revoked refresh — listen to it to drive app-wide auth state, e.g. redirect to login).
  • Breaking: Removed onTokenRefresh from GraphQLClient (still available on the lower-level AuthLink/SseLink) — refreshCallback is now the sole source of truth for refresh at the client level. RefreshCallback's refreshToken parameter is now non-nullable: the client skips calling it and revokes immediately when there's no stored refresh token, instead of asking every callback to null-check it.
  • However many requests fail at once, AuthLink makes at most one refresh call and queues the rest behind it, retrying all of them once it resolves — already true via its single-flight refresh lock, now covered by an explicit concurrent-401 test through the refreshCallback path.
  • Pre-parsed request documents: Added GraphQLRequest.documentNode (a DocumentNode), which GraphQLClient now sends instead of parsing document per request. Defaults to the existing shared string-keyed parse cache (GraphQLClient.getParsedDocument) for hand-written requests — no behavior change there — but mk_graphql_generator now overrides it with a static final field computed once per generated request class, skipping even that cache lookup on every subsequent request of that type.
  • Fix: DioLink no longer lets a malformed GraphQL response body (errors/data present but wrongly shaped — a non-Map error entry, a missing message, etc.) escape as a raw, unclassified TypeError. ResponseParser.parseResponse does unchecked casts internally; DioLink now wraps that call so a bad body always surfaces as DioLinkParserException → ParseException (for a 2xx response) or degrades DioLinkServerException.parsedResponse to null while still preserving the real status code (for a non-2xx response), instead of a bug-shaped exception with no stack trace or classification.
  • Added DioLinkConnectionException (DioExceptionType.connectionError — no connectivity, DNS failure, socket error) and DioLinkCertificateException (DioExceptionType.badCertificate — TLS/SSL validation failure) as dedicated DioLink exception types, matching the existing timeout/cancel/server distinction instead of bucketing both into the generic DioLinkUnkownException. GraphQLExceptionExtension.fromLinkException maps them to NetworkException and the new CertificateException respectively (previously connectionError was reclassified after the fact by unwrapping DioLinkUnkownException.originalException in two separate places — now decided once, at the source).

1.1.0 #

  • Dynamic Pagination Variables: Added applyVariables() and updateVariables() to GraphQLPaginator to dynamically update active variables (e.g. search queries, genre/status filters, sorting) on page 1 without recreating the paginator or wiping other active filter criteria.
  • Refetch & Pagination Reset Lifecycle: refetch() resets _baseRequest = initialRequest, restoring page 1 and clearing active filters/search to defaults, while loadNext() persists and accumulates items across pages.
  • Fine-Grained Page Tracking: Added optional getPage and hasNextPage callbacks to GraphQLPaginator.page(...) to allow authoritative backend pagination metadata (such as PageInfo.hasNextPage) to govern whether subsequent pages exist.
  • ErrorPolicy Support: Added ErrorPolicy.none, ErrorPolicy.ignore, and ErrorPolicy.all across requests, client executions, copy constructors, and client defaults.
  • Performance & Cache Optimization: Added deterministic canonical JSON variable cache key sorting and Document AST caching.
  • Documentation: Updated comprehensive guides for client requests, caching, links, and Flutter BLoC emit.forEach pagination patterns.

1.0.1 #

  • Pagination: added GraphQLPaginator with offset/page/cursor factories, a reactive PaginationState (items, isLoading, isLoadingMore, hasMore, error), and GraphQLClient/GraphQLRequest extension methods (paginate, paginateOffset, paginatePage, paginateCursor) for building infinite lists without hand-rolled pagination state.
  • Added an optional requestId override on GraphQLRequest, enabling cross-instance optimistic-response coalescing (used internally by CompositeGraphQLRequest).
  • Repository moved into the unified mk_graphql monorepo alongside mk_graphql_generator; no API changes from the move itself.

1.0.0 #

  • Initial release of mk_graphql.
  • Composable Link Architecture:
    • AuthLink with automatic 401 interception, thread-safe asynchronous token refresh queuing, and token revocation hooks.
    • DioLink powered by Dio with full cancellation support (CancelToken), automatic GraphQL Multipart Request spec uploads (Upload scalar / MultipartFile), and HTTP interceptors.
    • SseLink for Server-Sent Events (SSE) subscriptions with dynamic token header injection and 401 retry support.
    • WebSocketLink for GraphQL over WebSockets (graphql-ws and legacy protocol).
    • HttpLink for lightweight HTTP operations.
    • BatchLink for batching multiple GraphQL requests into a single HTTP payload.
    • TypenameLink for automatic __typename injection into AST selection sets.
    • LoggerLink for structured console logging with customizable options.
  • Client & Caching:
    • GraphQLClient supporting both Future (future()) and Stream (stream()) operations.
    • Pluggable cache interface with built-in normalized InMemoryCache.
    • Configurable fetch policies (cacheFirst, cacheOnly, networkOnly, cacheAndNetwork, noCache).
    • Optimistic response support.
  • Fully typed responses and exceptions (GraphQLResponse, GraphQLException, UnAuthorizedException, RequestCancelledException).
1
likes
0
points
845
downloads

Publisher

verified publisherkishormainali.com

Weekly Downloads

A clean, modern, simplified GraphQL client for Dart & Flutter with normalized caching, composable links, and stream-based operation execution.

Homepage
Repository (GitHub)
View/report issues

Topics

#graphql #flutter #client #sse #dio

License

unknown (license)

Dependencies

async, collection, dio, equatable, flutter, flutter_secure_storage, gql, gql_exec, gql_link, meta, shared_preferences, web_socket_channel

More

Packages that depend on mk_graphql