Controllers

Controllers

Angel has built-in support for controllers. This is yet another way to define routes in a manageable group, and can be leveraged to structure your application in the MVC format. You can also use the group() method of any Router.

The metadata on controller classes is processed via reflection only once, at startup. Do not believe that your controllers will be crippled by reflection during request handling, because that possibility is eliminated by pre-injecting dependencies.

  1. import 'package:angel_framework/angel_framework.dart';
  2. import 'package:angel_container/mirrors.dart';
  3. @Expose("/todos")
  4. class TodoController extends Controller {
  5. @Expose("/:id")
  6. getTodo(id) async {
  7. return await someAsyncAction();
  8. }
  9. // You can return a response handler, and have it run as well. :)
  10. @Expose("/login")
  11. login() => auth.authenticate('google');
  12. }
  13. main() async {
  14. Angel app = new Angel(reflector: MirrorsReflector());
  15. await app.configure(new TodoController().configureServer);
  16. }

Rather than extending from Routable, controllers act as plugins when called. This pseudo-plugin will wire all your routes for you.

@Expose()

The glue that holds it all together is the Expose annotation:

  1. class Expose {
  2. final String method;
  3. final Pattern path;
  4. final List middleware;
  5. final String as;
  6. final List<String> allowNull;
  7. const Expose(Pattern this.path,
  8. {String this.method: "GET",
  9. List this.middleware: const [],
  10. String this.as: null,
  11. List<String> this.allowNull: const[]});
  12. }

Allowing Null Values

Most fields are self-explanatory, save for as and allowNull. See, request parameters are mapped to function parameters on each handler. If a parameter is null, an error will be thrown. To prevent this, you can pass its name to allowNull.

  1. @Expose("/foo/:id?", allowNull: const["id"])

Named Controllers and Actions

The other is as. This allows you to specify a custom name for a controller class or action. ResponseContext contains a method, redirectToAction that can redirect to a controller action.

  1. @Expose("/foo")
  2. class FooController extends Controller {
  3. @Expose("/some/strange/url/:id", as: "bar")
  4. someActionWithALongNameThatWeWouldLikeToShorten(int id) async {
  5. }
  6. }
  7. main() async {
  8. Angel app = new Angel();
  9. app.get("/some/path", (req, res) async => res.redirectToAction("FooController@bar", {"id": 1337}));
  10. }

If you do not specify an as, then controllers and actions will be available by their names in code. Reflection is cool, huh?

Interacting with Requests and Responses

Controllers can also interact with requests and responses. All you have to do is declare a RequestContext or ResponseContext as a parameter, and it will be passed to the function.

  1. @Expose("/hello")
  2. class HelloController extends Controller {
  3. @Expose("/")
  4. Future getIndex(ResponseContext res) async {
  5. await res.render("hello");
  6. }
  7. }

Transforming Data

You can use middleware to de/serialize data to be processed in a controller method.

  1. Future<bool> deserializeUser(RequestContext req, res) async {
  2. var id = req.params['id'] as String;
  3. req.params['user'] = await asyncFetchUser(id);
  4. return true;
  5. }
  6. @Expose("/user", middleware: const [deserializeUser])
  7. class UserController extends Controller {
  8. @Expose("/:id/name")
  9. Future<String> getUserName(User user) async {
  10. return user.username;
  11. }
  12. }
  13. main() async {
  14. Angel app = new Angel();
  15. await app.configure(new UserController().configureServer);
  16. }

Next Up…

  1. How to handle parse request bodies with Angel
  2. Using Angel Plug-ins