> For the complete documentation index, see [llms.txt](https://angel3-docs.dukefirehawk.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://angel3-docs.dukefirehawk.com/under-the-hood/controllers.md).

# Controllers

* [Controllers](#controllers)
  * [`@Expose()`](#expose)
  * [Allowing Null Values](#allowing-null-values)
  * [Named Controllers and Actions](#named-controllers-and-actions)
  * [Interacting with Requests and Responses](#interacting-with-requests-and-responses)
  * [Transforming Data](#transforming-data)
  * [Controllers without Reflection](#controllers-without-reflection)
* [Next Up...](#next-up)

## Controllers

Angel3 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](https://en.wikipedia.org/wiki/Model–view–controller) format. You can also use the [`group()`](https://angel3-docs.dukefirehawk.com/under-the-hood/basic-routing.md#route-groups) method of any [`Router`](https://pub.dev/documentation/angel3_route/latest/angel3_route/Router-class.html).

Routing a controller's `@Expose` methods needs a reflector: `MirrorsReflector` of `angel3_container_mirrors` on the Dart VM, or reflection data generated by `angel3_container_generator` (see [Dependency Injection](https://angel3-docs.dukefirehawk.com/under-the-hood/dependency-injection.md#enabling-dart-mirrors-or-other-reflection)). 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](https://angel3-docs.dukefirehawk.com/under-the-hood/dependency-injection.md).

```dart
import 'package:angel3_container_mirrors/angel3_container_mirrors.dart';
import 'package:angel3_framework/angel3_framework.dart';

@Expose('/todos')
class TodoController extends Controller {
  @Expose('/:id')
  Future<Todo> getTodo(String id) async {
    return await someAsyncAction(id);
  }

  // You can return a response handler, and have it run as well. :)
  @Expose('/login')
  RequestHandler login() => auth.authenticate('google');
}

void main() async {
  var app = Angel(reflector: MirrorsReflector());
  await app.mountController<TodoController>();
}
```

Rather than extending from `Routable`, controllers act as [plug-ins](https://angel3-docs.dukefirehawk.com/extensions-and-plugins/using-plug-ins.md) when called. This pseudo-plugin will wire all your routes for you. `app.mountController<T>()` constructs the controller with the container, injecting its constructor's parameters, and configures it; `app.configure(TodoController().configureServer)` does the same with an instance you create.

### @Expose()

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

```dart
class Expose {
  final String method;
  final String path;
  final Iterable<RequestHandler> middleware;
  final String? as;
  final List<String> allowNull;

  const Expose(
    this.path, {
    this.method = 'GET',
    this.middleware = const [],
    this.as,
    this.allowNull = const [],
  });
}
```

### 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`.

```dart
@Expose('/foo/:id?', allowNull: ['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.

```dart
@Expose('/foo')
class FooController extends Controller {
  @Expose('/some/strange/url/:id', as: 'bar')
  Future someActionWithALongNameThatWeWouldLikeToShorten(int id) async {
  }
}

void main() async {
  var app = Angel(reflector: MirrorsReflector());
  await app.mountController<FooController>();

  app.get('/some/path', (req, res) => res.redirectToAction('FooController@bar', {'id': 1337}));
}
```

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](https://angel3-docs.dukefirehawk.com/under-the-hood/requests-and-responses.md). All you have to do is declare a `RequestContext` or `ResponseContext` as a parameter, and it will be passed to the function.

```dart
@Expose('/hello')
class HelloController extends Controller {
  @Expose('/')
  Future<void> getIndex(ResponseContext res) async {
    await res.render('hello');
  }
}
```

### Transforming Data

You can use [middleware](https://angel3-docs.dukefirehawk.com/under-the-hood/middleware.md) to de/serialize data to be processed in a controller method.

```dart
Future<bool> deserializeUser(RequestContext req, ResponseContext res) async {
  var id = req.params['id'] as String;
  req.params['user'] = await asyncFetchUser(id);

  return true;
}

@Expose('/user', middleware: [deserializeUser])
class UserController extends Controller {
  @Expose('/:id/name')
  Future<String> getUserName(User user) async {
    return user.username;
  }
}

void main() async {
  var app = Angel(reflector: MirrorsReflector());
  await app.configure(UserController().configureServer);
}
```

### Controllers without Reflection

Without a reflector, a controller can still group routes: give its mount path to the `Controller` constructor, and add its routes in `configureRoutes`:

```dart
class HealthController extends Controller {
  HealthController() : super(expose: const Expose('/health'));

  @override
  void configureRoutes(Routable routable) =>
      routable.get('/', (req, res) => {'status': 'ok'});
}

void main() async {
  var app = Angel(); // no reflector
  await app.configure(HealthController().configureServer);
}
```

## Next Up

1. How to [handle parse request bodies](https://angel3-docs.dukefirehawk.com/under-the-hood/body-parsing.md) with Angel3
2. [Using Angel3 Plug-ins](https://angel3-docs.dukefirehawk.com/extensions-and-plugins/using-plug-ins.md)
