// login_middleware.dart
import 'package:alfred/alfred.dart';
class LoginMiddleware {
const LoginMiddleware();
Future<dynamic> call(HttpRequest req, HttpResponse res) async {
final body = await req.bodyAsJsonMap;
final email = body['email'] as String?;
final password = body['password'] as String?;
// you can add more requirements if you like
if (email == null || password == null) {
res.statusCode = 400;
return {'error': 'email and password are required'};
}
// save the variables in store to grab them later inside the callback function
req.store.set('email', email);
req.store.set('password', password);
return null;
}
}
and here's the implementation of this:
import 'package:alfred/alfred.dart';
import './auth_validator.dart';
final app = Alfred().post(
'/login',
(req, res) {
// your callback function
},
middleware: [
const LoginValidator(),
],
);
This is not an issue with the package, but an example of a way you could implement Middlewares very cleanly:
The idea, I got from https://github.com/vandadnp/flutter-tips-and-tricks#callable-classes-in-dart.
and here's the implementation of this:
I hope this is useful to someone :))