rknell / alfred

A performant, expressjs like server framework with a few gadgets that make life even easier.
Other
523 stars 29 forks source link

class-based Middlewares #88

Open tomassasovsky opened 2 years ago

tomassasovsky commented 2 years ago

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.

// 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(),
  ],
);

I hope this is useful to someone :))

d-markey commented 2 years ago

Love it!

Rodsevich commented 2 years ago

Amazing! Please create a Controllers section in the documentation with this format!