Skip to main content

trpc_dart 0.3.0 copy "trpc_dart: ^0.3.0" to clipboard
trpc_dart: ^0.3.0 copied to clipboard

Pure Dart runtime for tRPC v11 clients - links, batching, SuperJSON, typed errors, and a state-agnostic query cache.

trpc_dart #

pub package pub points license GitHub CI

Pure Dart runtime for tRPC v11 clients. Provides a composable link pipeline, automatic HTTP batching, SuperJSON decoding, typed error hierarchies, and a state-agnostic query cache.

Works anywhere Dart runs: Flutter (iOS, Android, Web, macOS, Windows, Linux), Dart CLI tools, and backend Dart servers.

Part of the rpc-dart monorepo.


Features #

  • Composable link pipeline: Chain middleware for authentication, retries, logging, context, and transport.
  • HTTP batching transport: HttpBatchLink combines multiple procedure calls dispatched in the same event-loop tick into a single index-aligned HTTP request.
  • SuperJSON envelope support: Decodes Date into DateTime, bigint into BigInt, NaN/Infinity, Set, and Uri without silent data loss.
  • Zero-cast JSON reader: RpcJson parses JSON with Dart 3 pattern matching, attaching field breadcrumbs (UserGetByIdOutput.receipt.authorizedAt) to any type mismatch.
  • Three-state PATCH handling: RpcOpt<T> distinguishes omitted keys, explicit null, and updated values.
  • Framework-free query cache: RpcQueryCache manages query deduplication, invalidation streams, and optimistic updates without tying you to any state management library.
  • Typed exception table: Exceptions map directly to the tRPC v11 error specification (RpcBadRequestException, RpcUnauthorizedException, RpcNotFoundException, and more).

Installation #

Add trpc_dart to your pubspec.yaml:

dependencies:
  trpc_dart: ^0.3.0

Then run:

dart pub get
# or for Flutter:
flutter pub get

Quickstart #

Generated client code uses RpcClient to execute procedure calls:

import 'package:trpc_dart/trpc_dart.dart';

void main() async {
  // 1. Configure client and link chain
  final client = RpcClient(
    endpoint: Uri.parse('https://api.example.com/trpc'),
    transformer: RpcTransformer.superjson,
    links: [
      // Logs requests and responses, redacting secrets automatically
      LoggingLink(onEvent: (event) => print('[rpc] ${event.event} ${event.path}')),

      // Retries transient failures with exponential backoff
      RetryLink(policy: const RpcRetryPolicy(maxAttempts: 3)),

      // Automatically refreshes tokens on 401 UNAUTHORIZED
      AuthLink(
        getHeaders: () async => {'authorization': 'Bearer my-token'},
        // Return fresh headers, or null when the refresh updated what getHeaders reads.
        onUnauthorized: () async {
          await refreshSessionToken();
          return null;
        },
      ),

      // Terminal transport: coalesces calls into batched HTTP requests
      HttpBatchLink(endpoint: Uri.parse('https://api.example.com/trpc')),
    ],
  );

  // 2. Execute procedure directly or through generated bindings
  try {
    final response = await client.execute(const RpcRequest(
      path: 'user.getById',
      kind: RpcProcedureKind.query,
      input: {'id': 'user-123'},
    ));
    print('Raw response: $response');
  } on RpcUnauthorizedException {
    print('Session expired');
  } on RpcBadRequestException catch (e) {
    print('Validation failed: ${e.fieldErrors}');
  } on RpcException catch (e) {
    print('RPC error (${e.code}): ${e.message}');
  }
}

Future<void> refreshSessionToken() async {
  // Fetch fresh credentials
}

Links execute in the order declared in the links list:

final client = RpcClient(
  endpoint: Uri.parse('https://api.example.com/trpc'),
  links: [
    // 1. Request logging with automatic redaction
    LoggingLink(
      onEvent: (e) => print('${e.event} ${e.path} (${e.durationMs}ms)'),
      redactHeaders: {'x-custom-secret'},
    ),

    // 2. Correlation IDs and dynamic application headers
    ContextLink(
      correlate: true, // generates and attaches x-request-id
      dynamicHeaders: () async => {'x-client-version': '1.0.0'},
    ),

    // 3. Authentication with single-flight refresh lock
    AuthLink(
      getHeaders: () async => {'authorization': 'Bearer $token'},
      onUnauthorized: () async {
        await authService.refreshToken();
        return null; // or return a fresh header map
      },
    ),

    // 4. Retry link: queries retry automatically; mutations only retry if idempotent
    RetryLink(
      policy: RpcRetryPolicy(
        maxAttempts: 3,
        backoff: const Duration(milliseconds: 250),
      ),
    ),

    // 5. Terminal batch transport (exactly one termination link required)
    HttpBatchLink(
      endpoint: Uri.parse('https://api.example.com/trpc'),
      maxBatchSize: 10,
    ),
  ],
);

Query Cache & Invalidation #

RpcQueryCache runs independently of Flutter and state-management packages:

final cache = client.cache;

// Watch a query: returns an RpcQueryRef with a broadcast stream
final ref = cache.watch(
  const RpcQueryKey(path: ['user', 'me']),
  () => fetchCurrentUser(),
);

ref.stream.listen((state) {
  switch (state) {
    case RpcAsyncLoading():
      print('Loading user...');
    case RpcAsyncData(:final data):
      print('Loaded user: $data');
    case RpcAsyncError(:final error):
      print('Query failed: $error');
  }
});

// Invalidate specific query keys or entire subtrees:
cache.invalidate(const RpcQueryKey(path: ['user'])); // refetches all 'user.*' watchers

// Listen to invalidations:
cache.onInvalidate().listen((key) {
  print('Cache invalidated: ${key.path.join(".")}');
});

// Optimistic update:
cache.setQueryData(
  const RpcQueryKey(path: ['user', 'me']),
  updatedUser,
);

Zero-Cast Deserialization (RpcJson) #

RpcJson eliminates uncaught TypeError crashes when server contracts change:

// Type-safe extraction with breadcrumb paths:
final name = RpcJson.asString(data['name'], 'User.name');
final count = RpcJson.asInt(data['count'], 'User.count');
final date = RpcJson.asDateTime(data['createdAt'], 'User.createdAt');
final items = RpcJson.asList(data['items'], (item, path) => Item.fromJson(item as Map<String, Object?>));

If the server sends a number instead of a string, RpcJson throws RpcDecodeException: RpcDecodeException(DECODE) at User.name (expected String, got int): expected String but received int



License #

MIT © Aditya Jandu

Real-time subscriptions #

SSE and WebSocket transports with automatic reconnection and tracked() resume:

final endpoint = Uri.parse('http://127.0.0.1:8787/trpc');
final client = RpcClient(
  endpoint: endpoint,
  links: [
    SplitLink(
      unaryLink: HttpBatchLink(endpoint: endpoint),
      subscriptionLink: HttpSubscriptionLink(endpoint: endpoint),
    ),
  ],
);

final ticks = client.subscribe<Map<String, Object?>>(
  path: 'streams.onServerTick',
  input: null,
  decode: (value) => value! as Map<String, Object?>,
);

See docs/guides/subscriptions.md for the full guide.

oRPC transport & binary transfers #

OrpcLink speaks the oRPC RPCHandler/RPCLink wire (tested against oRPC 1.16.3): {json, meta} envelopes with numeric meta tags, slash-delimited pathname routing, GET ?data= queries, multipart uploads with indexed file maps, root-file and streaming downloads, and SSE event iterators with last-event-id resume. It composes with the same middleware links:

final endpoint = Uri.parse('https://api.example.com/rpc');
final client = RpcClient(
  endpoint: endpoint,
  links: [AuthLink(getHeaders: loadCredentials), OrpcLink(endpoint: endpoint)],
);

Binary primitives work on every platform (no dart:io in the library):

final receipt = await api.uploads.avatar.mutate(
  UploadsAvatarInput(file: RpcFile.bytes('a.png', bytes, contentType: 'image/png')),
  onSendProgress: (p) => print(p.fraction),
);
final file = await api.files.download.query(
  onReceiveProgress: (p) => print('${p.transferredBytes}/${p.totalBytes}'),
);
await for (final chunk in api.files.stream.query()) { /* RpcByteStream */ }

ORPCError payloads map onto the typed exception hierarchy via RpcException.fromOrpcWire (defined, code, status, message, data). On tRPC, binary fields ride SuperJSON registerCustom annotations (Uint8Array base64, File {name, type, data}).

See docs/guides/orpc-quickstart.md and docs/guides/file-transfers.md.

0
likes
160
points
184
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Pure Dart runtime for tRPC v11 clients - links, batching, SuperJSON, typed errors, and a state-agnostic query cache.

Repository (GitHub)
View/report issues
Contributing

Topics

#trpc #rpc #client #type-safe #http

License

MIT (license)

Dependencies

http

More

Packages that depend on trpc_dart