idempotency 0.1.0
idempotency: ^0.1.0 copied to clipboard
Client-side idempotency keys for Dart and Flutter: persist a key before the request fires, replay stored responses on retries, detect request-in-progress conflicts.
// Runnable tour of client-side idempotency keys:
// dart example/idempotency.dart
//
// Shows: key creation before the request fires, in-progress detection for
// concurrent duplicates, and replay of the recorded key on retry.
import 'package:idempotency/idempotency.dart';
void main() {
final stored = <String, String>{}; // pretend durable storage
final keys = IdempotencyKeys(
store: (operation, key) => stored[operation] = key ?? '',
load: (operation) => stored[operation],
);
// 1) First attempt of "refund-order-7": mint and persist a key.
final key1 = keys.keyFor('refund-order-7');
print('first attempt key: $key1');
// 2) The retry (same operation) replays the SAME key — the server sees
// a duplicate and must not charge twice.
final key2 = keys.keyFor('refund-order-7');
print('retry replays key: $key2 (same: ${key1 == key2})');
// 3) A concurrent second request while the first is in flight?
print('in-flight duplicate? ${keys.hasPendingAttempt('refund-order-7')}');
// 4) Request completed — the next "refund-order-7" is a NEW operation
// and gets a fresh key.
keys.complete('refund-order-7');
final key3 = keys.keyFor('refund-order-7');
print('after complete: $key3 (fresh: ${key3 != key1})');
}