Middleware<T extends Object?> typedef
A middleware function that wraps or intercepts a handler.
A Middleware takes an existing Handler and returns a new Handler that provides additional behavior before or after calling the original handler. This enables composition of cross-cutting concerns like logging, validation, error handling, timing, etc.
Middleware follows the decorator pattern:
- It receives the "next" handler in the chain
- It creates a new handler that wraps the next handler
- When called, it can perform pre-processing, call the next handler, then post-process
Example:
// Timing middleware that logs how long the handler takes
Middleware<String> timingMiddleware = (next) {
return (input) async {
final sw = Stopwatch()..start();
try {
return await next(input);
} finally {
sw.stop();
print('Took ${sw.elapsedMilliseconds}ms');
}
};
};
// Validation middleware that checks input before processing
Middleware<String> validationMiddleware = (next) {
return (input) async {
if (input.isEmpty) throw ArgumentError('Input cannot be empty');
return await next(input);
};
};
Implementation
@experimental
typedef Middleware<T extends Object?> = Handler<T> Function(Handler<T>);