idempotencyKeyInterceptor function
Builds an Interceptor that injects an idempotency key into IDEMPOTENT
unary calls.
Skips:
- Streaming RPCs (Connect-Dart cannot replay them).
- Methods without an
idempotency_levelannotation (the schema did not promise dedup; a key would be misleading). - Methods that already carry the header (caller- or composed-op-supplied
keys win, e.g. per-leg keys derived as
{op_id}/{leg_index}). - NO_SIDE_EFFECTS methods, unless
includeNoSideEffects: true.
Implementation
Interceptor idempotencyKeyInterceptor([
IdempotencyConfig config = const IdempotencyConfig(),
]) {
final generator = config.keyGenerator ?? defaultIdempotencyKeyGenerator;
return <I extends Object, O extends Object>(AnyFn<I, O> next) {
return (Request<I, O> req) {
if (req.spec.streamType != StreamType.unary) {
return next(req);
}
final level = req.spec.idempotency;
if (level == null) {
return next(req);
}
if (level == Idempotency.noSideEffects && !config.includeNoSideEffects) {
return next(req);
}
if (req.headers[config.headerName] != null) {
return next(req);
}
req.headers[config.headerName] = generator();
return next(req);
};
};
}