# Introduction

[![The Angel Framework](https://angel-dart.github.io/assets/images/logo.png)](https://angel-dart.github.io)

[![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg)](https://gitter.im/angel_dart/discussion) [![Pub](https://img.shields.io/pub/v/angel_framework.svg)](https://pub.dartlang.org/packages/angel_framework) [![Build status](https://travis-ci.org/angel-dart/framework.svg?branch=master)](https://travis-ci.org/angel-dart/framework) ![License](https://img.shields.io/github/license/angel-dart/framework.svg)

This is the documentation for [Angel](https://angel-dart.dev), a backend framework in the Dart language. This website consists of multiple guides and pages about features within the framework, as well as external links to YouTube videos, Pub packages, and Github repositories providing supplemental information.

New to Angel? Read the getting started guide, and you'll be well on your way:

<https://docs.angel-dart.dev/v/2.x/guides/getting-started>


# Migration from Angel 1.1.x


# Rationale - Why a new Version?

TODO


# 2.0.0 Migration Guide

Based on [this discussion](https://github.com/angel-dart/angel/issues/49).

Based on the changelog, up to `1.1.0`: <https://pub.dartlang.org/packages/angel_framework/versions/1.1.1#-changelog-tab->

## Main Points

* `angel_diagnostics` is deprecated - instead just pass a `Logger` and set it as `app.logger`.
* Removed `AngelFatalError`, and subsequently `fatalErrorStream`.
  * Errors are automatically create `500`. Set `app.logger` to see output.
  * `angel_errors` is no longer useful.
* Removed all `@deprecated` members.
* Removed @Hooked, beforeProcessed, and afterProcessed.
* Made injections in RequestContext private.
* Renamed properties in AngelBase to configuration.
* Added support for pattern matching and other injections via `@Parameter()`
* Officially deprecated properties in Angel.
* Fixed a bug where cached routes would not heed the request method. #173
* Reworked error handling logic; now, errors will not automatically default to sending JSON.
* Removed the onController stream from Angel.
* Controllers now longer use call, which has now been renamed to configureServer.

### Notes

Aside from these points, there are several things to note.

Migration in itself will be pretty easy to achieve. Plugins and services haven't really changed, it's just the HTTP server itself.

## What should I use instead of `X`?

In 1.1.0, the following were completely removed:

* `Angel.after`,
* `Angel.before`
* `Angel.justBeforeStart`
* `Angel.justBeforeStop`
* `Angel.fatalErrorStream`
  * There is no replacement for `before`/`after`. This way, it is easier to keep track of the order request handlers run. responseFinalizers are still in place.
  * `justBeforeStart`, `justBeforeStop` => `startupHooks`, `shutdownHooks`
  * `fatalErrorStream` is no longer necessary; you can just set `app.errorHandler`. Fatal errors will be wrapped in a 500 response.

## How should I define global middleware?

`app.use((req, res) => ...)`

Much cleaner in `1.1.0`. 😄


# ORM


# About

Angel, like many other Web server frameworks, features support for object-relational mapping, or *ORM*. ORM tools allow for conversion from database results to Dart classes.

Angel's ORM uses Dart's `build` system to generate query builder classes from your `Model` classes, and takes advantage of Dart's strong typing to prevent errors at runtime.

Take, for example, the following class:

```dart
@orm
abstract class _Pokemon extends Model {
    String get nickName;

    int get level;

    int get experiencePoints;

    @belongsTo
    PokemonTrainer get trainer;

    @belongsTo
    PokemonSpecies get species;

    @belongsTo
    PokemonAttack get attack0;

    @belongsTo
    PokemonAttack get attack2;

    @belongsTo
    PokemonAttack get attack3;

    @belongsTo
    PokemonAttack get attack4;
}
```

`package:angel_orm_generator` will generate code that lets you do the following:

```dart
app.get('/trainer/int:id/first_moves', (req, res) async {
    var id = req.params['id'] as int;
    var executor = req.container.make<QueryExecutor>();
    var trainer = await findTrainer(id);
    var query = PokemonQuery()..where.trainerId.equals(id);
    var pokemon = await query.get(executor);
    return pokemon.map((p) => p.attack0.name).toList();
});
```

This section of the Angel documentation consists mostly of guides, rather than technical documentation.

For more in-depth documentation, see the actual `angel_orm` project on Github:

<https://github.com/angel-dart/orm>


# Basic Functionality

Before starting with the ORM, it is highly recommended to familiar one's self with `package:angel_serialize`, as it is the foundation for `package:angel_orm`:

<https://github.com/angel-dart/serialize>

To enable the ORM for a given model, simply add the `@orm` annotation to its definition:

```dart
@orm
@serializable
abstract class _Todo {
    bool get isComplete;

    String get text;

    @Column(type: ColumnType.long)
    int get score;
}
```

The generator will produce a `TodoQuery` class, which contains fields corresponding to each field declared in `_Todo`. Each of `TodoQuery`'s fields is a subclass of `SqlExpressionBuilder`, corresponding to the given type. For example, `TodoQuery` would look *something* like:

```dart
class TodoQuery extends Query<Todo, TodoQueryWhere> {
    BooleanSqlExpressionBuilder get isComplete;

    StringSqlExpressionBuilder get text;

    NumericSqlExpressionBuilder<int> get score;
}
```

Thus, you can query the database using plain-old-Dart-objects (*PODO's*):

```dart
Future<List<Todo>> leftToDo(QueryExecutor executor) async {
    var query = TodoQuery()..where.isComplete.isFalse;
    return await query.get(executor);
}

Future<void> markAsComplete(Todo todo, QueryExecutor executor) async {
    var query = TodoQuery()
        ..where.id.equals(todo.idAsInt)
        ..values.isComplete = true;

    await query.updateOne(executor);
}
```

The glue holding everything together is the `QueryExecutor` interface. To support the ORM for any arbitrary database, simply extend the class and implement its abstract methods.

Consumers of a `QueryExecutor` typically inject it into the app's [dependency injection](https://github.com/angel-dart/gitbook/tree/e9d526478e563b918b4172f7cee31471132f4321/dependency-injection.md) container:

```dart
app.container.registerSingleton<QueryExecutor>(PostgresExecutor(...));
```

*At the time of this writing*, there is only support for PostgreSQL, though more databases may be added eventually.


# Relations

Relational modeling is one of the most commonly-used features of sql databases - after all, it *is* the namesake of the term "relational database."

Angel supports the following kinds of relations by means of annotations on fields:

* `@hasOne` (one-to-one)
* `@hasMany` (one-to-many)
* `@belongsTo` (one-to-one)
* `@manyToMany` (many-to-many)

By default, the keys for columns are inferred automatically. In the following case:

```dart
@orm
@serializable
abstract class _Wheel extends Model {
  @belongsTo
  Car get car;
}
```

The local key defaults to `car_id`, and the foreign key defaults to `id`. You can manually override these:

```dart
@BelongsTo(localKey: 'carId', foreignKey: 'licenseNumber')
Car get car;
```

The ORM computes relationships by performing `JOIN`s, so that even complex relationships can be fetched using just one query, rather than multiple.

## Many-to-many Relationships

A very common situation that occurs when using relational databases is where two tables may be bound to multiple copies of each other. For example, in a school database, each student could be registered to multiple classes, and each class could have multiple students taking it.

This is typically handled by creating a third table, which joins the two together. In the Angel ORM, this is relatively straightforward:

```dart
@orm
@serializable
abstract class _Class extends Model {
  String get courseName;

  @ManyToMany(_Enrollment)
  List<_Student> get students;
}

@orm
@serializable
abstract class _Student extends Model  {
  String get name;
  int get year;

  @ManyToMany(_Enrollment)
  List<_Class> get classes;
}

@orm
@serializable
abstract class _Enrollment {
    @belongsTo
    _Student get student;

    @belongsTo
    _Class get class_;
}
```


# Migrations

Angel's ORM ships with support for running database migrations, using a system modeled over [that of Laravel](https://laravel.com/docs/5.7/migrations).

An example is shown below:

```dart
class UserMigration implements Migration {
  @override
  void up(Schema schema) {
    schema.create('users', (table) {
      table
        ..serial('id').primaryKey()
        ..varChar('username', length: 32).unique()
        ..varChar('password')
        ..boolean('account_confirmed').defaultsTo(false);
    });
  }

  @override
  void down(Schema schema) {
    schema.drop('users');
  }
}
```

Migrations can be used to either create, alter, or drop database tables.

For more in-depth documentation, consult the `angel_migration` documentation:

<https://github.com/angel-dart/migration>

If you use `angel_orm_generator`, then a migration will be generated by default for each class annotated with `@orm`.

To disable this:

```dart
@Orm(generateMigrations: false)
abstract class _MyModel extends Model {}
```

## Running Migrations

Using `package:angel_migration_runner`, we can create executables that run our database migrations:

```dart
import 'package:angel_migration_runner/angel_migration_runner.dart';
import 'package:angel_migration_runner/postgres.dart';
import 'package:postgres/postgres.dart';
import '../../angel_migration/example/todo.dart';

var migrationRunner = PostgresMigrationRunner(
  PostgreSQLConnection('127.0.0.1', 5432, 'test'),
  migrations: [
    UserMigration(),
    TodoMigration(),
  ],
);
```

Running this file will produce output like the following:

```
Executes Angel migrations.

Usage: migration_runner <command> [arguments]

Global options:
-h, --help    Print this usage information.

Available commands:
  help       Display help information for migration_runner.
  refresh    Resets the database, and then re-runs all migrations.
  reset      Resets the database.
  rollback   Undoes the last batch of migrations.
  up         Runs outstanding migrations.

Run "migration_runner help <command>" for more information about a command.
```

The migration runner keeps track of a `migrations` table, in order to be able to keep track of which migrations it has run.


# NoSQL

As one can imagine, a SQL ORM cannot be used with a NoSQL database. However, this is usually not a problem, because the ideal use cases for NoSQL databases typically do not require the functionality present in an ORM (namely, relation support).

With a NoSQL databases, you can use the `Service` API (you likely already are!), and use `Service.map` to deal with Dart data only, rather than messing around with `Map`s, and risking typos and refactoring challenges.

If you are using `package:angel_serialize`, this is pretty easy:

```dart
abstract class _Greeting extends Model {
    String get text;

    double get attachedMoney;
}

var service = MongoService(...);
var mappedService = service.map(GreetingSerializer.fromMap, GreetingSerializer.toMap);

// Now you can get Greeting instances.
var greeting = await mappedService.read(id);
print([greeting.text, greeting.attachedMoney]);
```


# PostgreSQL

PostgreSQL support is provided by way of `package:angel_orm_postgres`. The `PostgreSQLExecutor` implements `QueryExecutor`, and takes care of running prepared queries, and passing values to the database server.

`angel init` projects using the ORM include helpers like this to load app configuration into a database connection:

```dart
Future<void> configureServer(Angel app) async {
  var connection = await connectToPostgres(app.configuration);
  await connection.open();

  app
    ..container.registerSingleton<QueryExecutor>(PostgreSQLExecutor(connection))
    ..shutdownHooks.add((_) => connection.close());
}

Future<PostgreSQLConnection> connectToPostgres(Map configuration) async {
  var postgresConfig = configuration['postgres'] as Map ?? {};
  var connection = PostgreSQLConnection(
      postgresConfig['host'] as String ?? 'localhost',
      postgresConfig['port'] as int ?? 5432,
      postgresConfig['database_name'] as String ??
          Platform.environment['USER'] ??
          Platform.environment['USERNAME'],
      username: postgresConfig['username'] as String,
      password: postgresConfig['password'] as String,
      timeZone: postgresConfig['time_zone'] as String ?? 'UTC',
      timeoutInSeconds: postgresConfig['timeout_in_seconds'] as int ?? 30,
      useSSL: postgresConfig['use_ssl'] as bool ?? false);
  return connection;
```

Typically, you'll want to use app configuration to create the connection, rather than hard coding values.


# Guides


# Getting Started

## Getting Started

In this first guide, we will:

* Download the `angel_framework` package from Pub.
* Launch an `AngelHttp` server.
* Add some basic routes to an app.
* Add a 404 error handler.

The source code for this example can be found here:

<https://github.com/angel-dart/examples-v2/tree/master/docs_examples/getting_started>

## First Steps

This tutorial relies on the terminal/command-line, so if are not well-versed in using such tools, you should copy/paste the snippets found on this page.

If you have not yet installed the Dart SDK, then it is required that you do so before continuing:

<https://www.dartlang.org/tools/sdk#install>

In addition, the `curl` tool will be used to send requests to our server:

<https://curl.haxx.se/download.html>

Also, you will need to have the Dart SDK in your `PATH` environment variable, so that the `dart` and `pub` executables can be found from your command line:

<https://www.java.com/en/download/help/path.xml>

Finally, note that some steps will mention Unix-specific programs, like `nano`. Windows users should instead use Notepad. Alternative programs will be mentioned where relevant.

## Project Setup

The first thing we'll need to do is create a new directory (folder) for our project.

```bash
mkdir hello_angel
cd hello_angel
```

Next, we create a `pubspec.yaml` file, and enter the following contents:

```yaml
name: hello_angel
dependencies:
    angel_framework: ^2.0.0
```

Now, just run `pub get`, which will install the `angel_framework` library, and its dependencies:

```
Resolving dependencies... (3.3s)
+ angel_container 1.0.0
+ angel_framework 2.0.0
+ angel_http_exception 1.0.0+3
(... more output omitted)
Changed 33 dependencies!
```

## Launching an HTTP Server

Angel can speak different protocols, but more often than not, we'll want it to speak HTTP.

Create a directory named `bin`, and a file within `bin` named `main.dart`.

Your folder structure should now look like this:

```
hello_angel
    bin/
        main.dart
    pubspec.yaml
```

Add the following to `bin/main.dart`:

```dart
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_framework/http.dart';

main() async {
    var app = Angel();
    var http = AngelHttp(app);
    await http.startServer('localhost', 3000);
}
```

Next, in your terminal, run the command `dart bin/main.dart`. Your server will now be running, and will listen for input until you kill it by entering `Control-C` (the `SIGINT` signal) into the terminal.

Open a new terminal window, and type the following:

```bash
curl localhost:3000 && echo
```

You'll just see a blank line, but the fact that you *didn't see an error* means that the server is indeed listening at port `3000`.

## Adding a Route

By adding *routes* to our server, we can respond to requests sent to different URL's.

Let's a handler at the *root* of our server, and print a simple `Hello, world!` message.

From this point, all new code needs to be added *before* the call to `http.startServer` (or else it will never run).

Add this code to your program:

```dart
app.get('/', (req, res) => res.write('Hello, world!'));
```

`bin/main.dart` should now look like the following:

```dart
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_framework/http.dart';

main() async {
    var app = Angel();
    var http = AngelHttp(app);
    app.get('/', (req, res) => res.write('Hello, world!'));
    await http.startServer('localhost', 3000);
}
```

(Note that this is the last time the entire file will be pasted, for the sake of brevity.)

Now, if you rerun `curl localhost:3000 && echo`, you'll see the message `Hello, world!` printed to your terminal!

## Route Handlers

Let's break down the line we just added:

```dart
app.get('/', (req, res) => res.write('Hello, world!'));
```

It consists of the following components:

* A call to `app.get`
* A string, `'/'`,
* A closure, taking two parameters: `req` and `res`
* The call `res.write('Hello, world!')`, which is

  also the return value of the aforementioned closure.

`Angel.get` is one of several methods (`addRoute`, `post`, `patch`, `delete`, `head`, `get`) that can be used to add routes that correspond to [HTTP methods](https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html) to an `Angel` server instance.

Combined with the path, `'/'`, this signifies that whenever a request is sent to the *root* of our server, which in this case is the URL `http://localhost:3000`, the attached closure should be invoked.

The path is important because it defines the conditions under which code should run. For example, if we were to visit `http://localhost:3000/foo`, we'd just see a blank line printed again, because there is no route mounted corresponding to the path `'/foo'`.

The two parameters, `req` and `res`, hold the types `RequestContext` and `ResponseContext`, respectively. We'll briefly cover these in the next section.

Finally, we call `res.write`, which, as you may have surmised, prints a value to the outgoing HTTP response. That's how we are able to print `Hello, world!`.

## Printing Headers

Just as their names suggest, the `RequestContext` and `ResponseContext` classes are abstractions used to read and write data on the Web.

By reading the property `req.headers`, we can access the [HTTP headers](https://tools.ietf.org/html/rfc2616#section-4.2) sent to us by the client:

```dart
app.get('/headers', (req, res) {
    req.headers.forEach((key, values) {
        res.write('$key=$values');
        res.writeln();
    });
});
```

Run the following:

```bash
curl -H 'X-Foo: bar' -H 'Accept-Language: en-US' \
http://localhost:3000/headers && echo
```

And you'll see output like the following:

```
user-agent=[curl/7.54.0]
accept=[*/*]
accept-language=[en-US]
x-foo=[bar]
host=[localhost:3000]
```

## Reading Request Bodies

Web applications very often have users send data upstream, where it is then handled by the server.

Angel has built-in functionality for parsing bodies of three MIME types:

* `application/json`
* `application/x-www-form-urlencoded`
* `multipart/form-data`

(You can also handle others, but that's beyond the scope of this demo.)

So, as long as the user sends data in one of the above forms, we can handle it in the same way.

Add the following route. It will listen on the path `'/greet'` for a `POST` request, and then attempt to parse the incoming request body.

Afterwards, it reads the `name` value from the body, and computes a greeting string.

```dart
app.post('/greet', (req, res) async {
    await req.parseBody();

    var name = req.bodyAsMap['name'] as String;

    if (name == null) {
        throw AngelHttpException.badRequest(message: 'Missing name.');
    } else {
        res.write('Hello, $name!');
    }
});
```

To visit this, enter the following `curl` command:

```bash
curl -X POST -d 'name=Bob' localhost:3000/greet && echo
```

You should see `Hello, Bob!` appear in your terminal.

## Adding an Error Handler

In the previous example, you might have noticed this line:

```dart
throw AngelHttpException.badRequest(message: 'Missing name.');
```

Angel handles errors thrown while calling route handlers, preventing your server from crashing. Ultimately, all errors are wrapped in the `AngelHttpException` class, or sent as-is if they are already instances of `AngelHttpException`.

By default, either an HTML page is printed, or a JSON message is displayed (depending on the client's `Accept` header). In many cases, however, you might want to do something else, i.e. rendering an error page, or logging errors through a service like Sentry.

To add your own logic, set the `errorHandler` of your `Angel` instance. It is a function that accepts 3 parameters:

* `AngelHttpException`
* `RequestContext`
* `ResponseContext`

```dart
var oldErrorHandler = app.errorHandler;

app.errorHandler = (e, req, res) {
if (e.statusCode == 400) {
    res.write('Oops! You forgot to include your name.');
} else {
    return oldErrorHandler(e, req, res);
}
```

Note that we kept a reference to the previous error handler, so that existing logic can be reused if the case we wrote for is not handled.

To trigger a `400 Bad Request` and see our error handler in action, run the following:

```bash
curl -H 'Content-Type: application/x-www-form-urlencoded' \
-X POST localhost:3000/greet && echo
```

You will now see `'Oops! You forgot to include your name.'` printed to the console.

## Conclusion

Congratulations on creating your first Angel server! Hopefully this is just one of many more to come.

The choice is now yours: either continue reading the other guides posted on this site, or tinker around and learn the ropes yourself.

You can find `angel_*` packages on the Pub site, and read the documentation found in their respective `README` files:

<https://pub.dartlang.org/packages?q=dependency%3Aangel_framework>

Don't forget that for discussion and support, you can either file a Github issue, or join the Gitter chat:

<https://gitter.im/angel_dart/discussion>


# Basic Routing

* [Routing](broken://pages/-LdMcGfctFfUjqQNgLOb#routing)
* [Route Parameters](broken://pages/-LdMcGfctFfUjqQNgLOb#route-parameters)
  * [Parsing Parameters](broken://pages/-LdMcGfctFfUjqQNgLOb#parsing-parameters)
* [`RegExp` Routes](broken://pages/-LdMcGfctFfUjqQNgLOb#regexp-routes)
* [Mounting and Sub-Apps](broken://pages/-LdMcGfctFfUjqQNgLOb#sub-apps)
* [Route Groups](broken://pages/-LdMcGfctFfUjqQNgLOb#route-groups)
* [Extended Documentation](broken://pages/-LdMcGfctFfUjqQNgLOb#extended-documentation)
* [Next Up...](broken://pages/-LdMcGfctFfUjqQNgLOb#next-up)

## Routing

There is only one method responsible for adding routes to your application:

```dart
app.addRoute('<method>', '<path>', requestHandler);
```

However, the following methods are available for convenience, and are the ones you will use most often. Each method's name responds to an HTTP request method. For example, a route declared with `app.get(...)`, will respond to HTTP `GET` requests.

```dart
app.get('<path>', requestHandler);
app.post('<path>', requestHandler);
app.patch('<path>', requestHandler);
app.delete('<path>', requestHandler);
```

Your `requestHandler` should take the following form:

```dart
typedef FutureOr<dynamic> RequestHandler(RequestContext req, ResponseContext res);
```

Your `requestHandler` can return any Dart value, whether a function, or an object. See the [Requests and Responses](/2.x/guides/requests-and-responses#return-values) pages for detailed documentation.

Route paths *do not* have to begin with a forward slash, as leading and trailing slashes are stripped from route paths internally.

## Route Parameters

Say you're building an API, or an MVC application. You typically want to serve the same view template on multiple paths, corresponding to different ID's. You can do this as follows, and all parameters will be available via `req.params`:

```dart
app.get('/todos/:id', (req, res) async => {'id': req.params['id']});
```

Remember, route parameters *must* be preceded by a colon (':'). Parameter names must start with a letter or underscore, optionally followed by letters, underscores, or numbers. Parameters will match any character except a forward slash ('/') in a request URI.

Examples:

* `:id`
* `:_hello`
* `:param123`
* `info_about_:username`

### Parsing Parameters

With a special syntax, you can build routes that automatically parse parameters as `ints` or `doubles`:

```dart
app
  ..get('/add/int:number', (req, res) => req.params['number'] * 3)
  ..get('/multiply/double:number', (req, res) => req.params['number'] * 5.0);
```

## RegExp Routes

Route parameters can also have custom regular expressions, to remove the requirement of manual parsing. Simply enclose the regular expression in a set of parentheses following the parameter's name.

```dart
app.get(r'/number/:num([0-9]+(\.[0-9])?)', ...);
```

## Sub-Apps

You can `mount` routers, or `use` entire sub-apps.

```dart
var app = new Angel();
app.get('/', 'Hello!');

var subRouter = new Router()..get('/', 'Subroute');
app.mount('/sub', subApp);
// Now, you can visit /sub and receive the message "Subroute"

var subApp = new Angel()..get('/hello', 'world');
app.use('/api', subApp);

// GET /api/hello returns "world"
```

## Route Groups

Routes can also be grouped together. Route parameters will be applied to sub-routes automatically. Route groups can be nested as well.

```dart
app.group('/user/:id', (router) {
  router
    ..get('/messages', (String id) => fetchUserMessages(id))
    ..group('/nested', ...);
});
```

## Extended Documentation

For more documentation on the router, see [its repository](https://github.com/angel-dart/route). [`package:angel_route`](https://pub.dartlang.org/packages/angel_route) has no `dart:io` or `dart:mirrors` dependency, and it also supports browser use (both hash and push state).

## Next Up...

Learn how [middleware](/2.x/guides/middleware) let you reuse functionality across your entire routing setup.


# Installation & Setup

* [Getting Started](/2.x/guides/installation#getting-started)
  * [Installation](/2.x/guides/installation#installation)
    * [Prerequisites](/2.x/guides/installation#prequisites)
* [Next Up...](/2.x/guides/installation#next-up)

## Getting Started

Let's get it started, ha!

### Installation

#### Prerequisites

* Firstly, ensure you have the [Dart SDK](https://www.dartlang.org/downloads/) installed.

Now, install the [Angel CLI](/2.x/guides/cli). The CLI includes several code generators and commands that will help you expedite your development cycle.

```bash
$ pub global activate angel_cli
```

Now, let's create a sample project, called `hello`.

Run:

```bash
$ angel init hello
```

This will create a folder called `hello`, and copy the [Angel boilerplate](https://github.com/angel-dart/angel) into it. If you wanted to initialize a project within the current directory, instead of making new one, you could have run:

```bash
$ angel init
```

Follow the instructions given. There are different types of boilerplates, but all of the server templates will generate very similarly-structured projects.

It's easy to run our server. Just type the following:

```bash
# Use the `--observe` flag to enable hot reloading in Angel.
dart --observe bin/server.dart
```

And there you have it - you've created an Angel application!

## Next Up...

Continue reading to learn about [requests and responses](/2.x/guides/requests-and-responses).


# Without the Boilerplate

It's very easy to setup a bare-bones Angel server.

Any Dart project needs a project file, called `pubspec.yaml`. This file almost always contains a `dependencies` section, where you will install the Angel framework libraries.

```yaml
dependencies:
    angel_framework: ^2.0.0
```

You might also want to install packages such as `angel_static`, `angel_cache`, `angel_jael`, and `angel_cors`.

Next, run `pub get` on the command line, or in your IDE if it has Dart support. This will install the framework and all of its dependencies.

Next, create a file, `bin/main.dart`. Put this code in it:

```dart
import 'dart:io';
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_framework/http.dart';

main() async {
  var app = new Angel();
  var http = AngelHttp(app);

  app.get("/", (req, res) => "Hello, world!");

  var server = await http.startServer();
  print("Angel server listening at ${http.uri}");
}
```

The specifics are not that important, but there are a few important calls here:

* `var app = new Angel()` - The base Angel server is a simple class, and we need an instance of it to run our server. The name `app` is a convention adopted from Express. In general, call an Angel instance `app`. This has no effect on functionality, but it makes it easier for other developers to understand your code.
* `app.get("/", (req, res) => "Hello, world!");` - This is a [route](broken://pages/-LeJLRfzM2Bq6ZFfq6tV), and tells our server to respond to all GET requests at our server root with `"Hello, world!"`. The response will automatically be encoded as JSON. Head over to the [Basic Routing](broken://pages/-LeJLRfzM2Bq6ZFfq6tV) tutorial to learn about routes, and how they work.
* `await http.startServer(...)` - This asynchronous call is what actually starts the server listening. Without it, your application won't be accessible over HTTP (as it won't ever listen for requests).

That's it! Your server is ready to serve requests. You can easily start it from the command line like this:

```
dart bin/main.dart
```


# Requests & Responses

* [Requests and Responses](/2.x/guides/requests-and-responses#requests-and-responses)
  * [Return Values](/2.x/guides/requests-and-responses#return-values)
  * [Other Parameters](/2.x/guides/requests-and-responses#other-parameters)
  * [Queries, Files and Bodies](/2.x/guides/requests-and-responses#queries-files-and-bodies)
* [Next Up...](/2.x/guides/requests-and-responses#next-up)

## Requests and Responses

Angel is inspired by Express, and such, request handlers in general resemble those from Express. Request handlers can return any Dart object (see [how they are handled](/2.x/guides/requests-and-responses#return-values)). Basic request handlers accept two parameters:

* [`RequestContext`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext-class.html) - Contains vital information about the client requesting a resource, such as request method, request body, IP address, etc. The request object can also be used to pass information from one handler to the next.&#x20;
* [`ResponseContext`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext-class.html) - Allows you to send headers, write data, and more, to be sent to the client. To prevent a response from being modified by future handlers, call `res.end()` to prevent further writing.

### Return Values

Request handlers can return any Dart value. Return values are handled as follows:

* If you return a `bool`: Request handling will end prematurely if you return `false`, but it will continue if you return `true`.
* If you return `null`: Request handling will continue, unless you closed the response object by calling [`res.close()`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext/close.html). Some response methods, such as [`res.redirect()`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext/redirect.html) or [`res.serialize()`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext/serialize.html) automatically close the response.
* A `RequestHandler`: the returned handler will be executed.
* A `Stream`: `toList` will be called, and then returned.
* A `Future`: it will be awaited, and then returned.
* Anything else: Whatever other Dart value you return will be serialized as a response. The default method is to encode responses as JSON, using `json.encode`. However, you can change a response's serialization method by setting `res.serializer = foo;`. If you want to assign the same serializer to all responses, globally set [`serializer`](https://pub.dartlang.org/documentation/angel_framework/latest/angel_framework/Angel/serializer.html) on your Angel instance. If you are only returning JSON-compatible Dart objects, like Maps or Lists, you might consider injecting `JSON.encode` as a serializer, to improve runtime performance (this is the default in `2.0`).

### Other Parameters

Request handlers can take other parameters, instead of just a `RequestContext` and `ResponseContext`. Consult the [dependency injection documentation](/2.x/guides/dependency-injection#in-routes-and-controllers).

### Queries, Files and Bodies

You can access a mutable `Map` based on the URI query parameters by calling `RequestContext.queryParameters`.

Consult the [body parsing documentation](/2.x/guides/body-parsing) to understand how to handle user input.

If you [write your own plugin](https://github.com/angel-dart/gitbook/tree/0635bfd7dc6fad24577470ec1bd761c6e99b29d5/advanced/writing-a-plugin.md), be sure to use the `lazy` alternatives.

For more information, see the API docs:

[RequestContext](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext-class.html)

[ResponseContext](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext-class.html)

## Next Up...

Now, let's learn about Angel's [flexible router](broken://pages/-LeJLRfzM2Bq6ZFfq6tV).


# Dependency Injection

Angel uses a [container hierarchy](https://github.com/angel-dart/container) for DI. Dependency injection makes it easier to build applications with multiple moving parts, because logic can be contained in one location and reused at another place in your application.

## Adding a Singleton

```dart
Future<void> myPlugin(Angel app) async  {
  app.container.registerSingleton(SomeClass("foo"));
  app.container.registerSingleton<SomeAbstractClass>(MyImplClass());
  app.container.registerFactory((_) => SomeClass("foo"));
  app.container.registerLazySingleton((_) => SomeOtherClass());
  app.container.registerNamedSingleton('yes', Yes());
}
```

You can also inject within a `RequestContext`, as each one has a `controller` property that extends from the app's global container.

Accessing these injected properties is easy, and strongly typed:

```dart
// Inject types.
var todo = req.container.make<Todo>();
print(todo.isComplete);

// Or by name
var db = await req.container.findByName<Db>('database');
var collection = db.collection('pets');
```

## In Routes and Controllers

In Angel 2.0, by wrapping a function in a call to `ioc`, you can automatically inject the dependencies of any route handler.

```dart
app.get("/some/class/text", ioc((SomeClass singleton) => singleton.text)); // Always "foo"

app.post("/foo", ioc((SomeClass singleton, {Foo optionalInjection}));

@Expose("/my/controller")
class MyController extends Controller {

  @Expose("/bar")
  // Inject classes from container, request parameters or the request/response context :)
  bar(SomeClass singleton, RequestContext req) => "${singleton.text} bar"; // Always "foo bar"

  @Expose("/baz")
  baz({Foo optionalInjection});
}
```

As you can imagine, this is very useful for managing things such as database connections.

```dart
configureServer(Angel app) async {
  var db = Db("mongodb://localhost:27017/db");
  await db.open();
  app.container.registerSingleton(db);
}

@Expose("/users")
class ApiController extends Controller {
  @Expose("/:id")
  fetchUser(String id, Db db) => db.collection("users").findOne(where.id(ObjectId.fromHexString(id)));
}
```

## Dependency-Injected Controllers

`Controller`s have dependencies injected without any additional configuration by you. However, you might want to inject dependencies into the constructor of your controller.

```dart
@Expose('/controller')
class MyController {
  final AngelAuth auth;
  final Db db;

  MyController(this.auth, this.db);

  @Expose('/login')
  login() => auth.authenticate('local');
}

main() async {
  // At some point in your application, register necessary dependencies as singletons...
  app.container.registerSingleton(auth);
  app.container.registerSingleton(db);

  // Create the controller with injected dependencies
  await app.mountController<MyController>();
}
```

## Enabling `dart:mirrors` or other Reflection

By default, Angel will use the `EmptyReflector()` to power its `Container` instances, which has no support for `dart:mirrors`, so that it can be used in contexts where Dart reflection is not available.

However, by using a different `Reflector`, you can use the full power of Angel's DI system. `angel init` projects use the `MirrorsReflector()` by default.

If your application is using any sort of functionality reliant on annotations or reflection, either include the MirrorsReflector, or use a static reflector variant.

The following use cases require reflection:

* Use of `Controller`s, via `@Expose()` or `@ExposeWS()`
* Use of dependency injection into **constructors**, whether in controllers or plain `container.make` calls
* Use of the `ioc` function in any route

The `MirrorsReflector` from `package:angel_container/mirrors.dart` is by far the most convenient pattern, so use it if possible.

However, the following alternatives exist:

* Generation via `package:angel_container_generator`
* Creating an instance of `StaticReflector`
* Manually implementing the `Reflector` interface (cumbersome; not recommended)


# Basic Routing

* [Routing](/2.x/guides/basic-routing-1#routing)
* [Route Parameters](/2.x/guides/basic-routing-1#route-parameters)
  * [Parsing Parameters](/2.x/guides/basic-routing-1#parsing-parameters)
* [`RegExp` Routes](/2.x/guides/basic-routing-1#regexp-routes)
* [Mounting and Sub-Apps](/2.x/guides/basic-routing-1#sub-apps)
* [Route Groups](/2.x/guides/basic-routing-1#route-groups)
* [Extended Documentation](/2.x/guides/basic-routing-1#extended-documentation)
* [Next Up...](/2.x/guides/basic-routing-1#next-up)

## Routing

There is only one method responsible for adding routes to your application:

```dart
app.addRoute('<method>', '<path>', requestHandler);
```

However, the following methods are available for convenience, and are the ones you will use most often. Each method's name responds to an HTTP request method. For example, a route declared with `app.get(...)`, will respond to HTTP `GET` requests.

```dart
app.get('<path>', requestHandler);
app.post('<path>', requestHandler);
app.patch('<path>', requestHandler);
app.delete('<path>', requestHandler);
```

Your `requestHandler` should take the following form:

```dart
typedef FutureOr<dynamic> RequestHandler(RequestContext req, ResponseContext res);
```

Your `requestHandler` can return any Dart value, whether a function, or an object. See the [Requests and Responses](/2.x/guides/requests-and-responses#return-values) pages for detailed documentation.

Route paths *do not* have to begin with a forward slash, as leading and trailing slashes are stripped from route paths internally.

## Route Parameters

Say you're building an API, or an MVC application. You typically want to serve the same view template on multiple paths, corresponding to different ID's. You can do this as follows, and all parameters will be available via `req.params`:

```dart
app.get('/todos/:id', (req, res) async => {'id': req.params['id']});
```

Remember, route parameters *must* be preceded by a colon (':'). Parameter names must start with a letter or underscore, optionally followed by letters, underscores, or numbers. Parameters will match any character except a forward slash ('/') in a request URI.

Examples:

* `:id`
* `:_hello`
* `:param123`
* `info_about_:username`

### Parsing Parameters

With a special syntax, you can build routes that automatically parse parameters as `ints` or `doubles`:

```dart
app
  ..get('/add/int:number', (req, res) => req.params['number'] * 3)
  ..get('/multiply/double:number', (req, res) => req.params['number'] * 5.0);
```

## RegExp Routes

Route parameters can also have custom regular expressions, to remove the requirement of manual parsing. Simply enclose the regular expression in a set of parentheses following the parameter's name.

```dart
app.get(r'/number/:num([0-9]+(\.[0-9])?)', ...);
```

## Sub-Apps

You can `mount` routers, or `use` entire sub-apps.

```dart
var app = new Angel();
app.get('/', 'Hello!');

var subRouter = new Router()..get('/', 'Subroute');
app.mount('/sub', subApp);
// Now, you can visit /sub and receive the message "Subroute"

var subApp = new Angel()..get('/hello', 'world');
app.use('/api', subApp);

// GET /api/hello returns "world"
```

## Route Groups

Routes can also be grouped together. Route parameters will be applied to sub-routes automatically. Route groups can be nested as well.

```dart
app.group('/user/:id', (router) {
  router
    ..get('/messages', (String id) => fetchUserMessages(id))
    ..group('/nested', ...);
});
```

## Extended Documentation

For more documentation on the router, see [its repository](https://github.com/angel-dart/route). [`package:angel_route`](https://pub.dartlang.org/packages/angel_route) has no `dart:io` or `dart:mirrors` dependency, and it also supports browser use (both hash and push state).

## Next Up...

Learn how [middleware](/2.x/guides/middleware) let you reuse functionality across your entire routing setup.


# Request Lifecycle

Requests in the Angel framework go through a relatively complex lifecycle, and to truly master the framework, one must understand that lifecycle.

1. `startServer` is called.
2. Each `HttpRequest` is sent through `handleRequest`.
3. `handleRequest` converts the `HttpRequest` to a `RequestContext`, and converts its `HttpResponse` into a `ResponseContext`.
4. `angel_route` is used to match the request path to a list of request handlers.
5. Each handler is executed.
6. If the response is using streaming, and not buffering content, skip to step 8 (default).&#x20;
7. All `responseFinalizers` are run.
8. If `res.isDetached == false`, all headers, the status code and the response buffer are sent through the actual `HttpResponse`.
9. The `HttpResponse` is closed.

If at any point an error occurs, Angel will catch it. See the [error handling](/2.x/guides/error-handling) docs for more.


# Middleware

* [Middleware](/2.x/guides/middleware#middleware)
  * [Denying Requests via Middleware](/2.x/guides/middleware#denying-requests-via-middleware)
  * [Declaring Middleware](/2.x/guides/middleware#declaring-middleware)
  * [Named Middleware](/2.x/guides/middleware#named-middleware)
  * [Global Middleware](/2.x/guides/middleware#global-middleware)
  * [`chain([...])`](/2.x/guides/middleware#chain)
  * [\*\*Maintaining Code Readability](/2.x/guides/middleware#maintaining-code-readability)
* [Next Up...](/2.x/guides/middleware#next-up)

## Middleware

Sometimes, it becomes to recycle code to run on multiple routes. Angel allows for this in the form of *middleware*. Middleware are frequently used as authorization filters, or to serialize database data for use in subsequent routes. Middleware in Angel can be any route handler, whether a function or arbitrary data. You can also throw exceptions in middleware.

### Denying Requests via Middleware

A middleware should return either `true` or `false`. If `false` is returned, no further routes will be executed. If `true` is returned, route evaluation will continue. (more on request handler return values [here](/2.x/guides/requests-and-responses#return-values)).

In practice, you will only need to write a `return` statement when you are returning `true`.

As you can imagine, this is perfect for authorization filters.

### Declaring Middleware

You can call a router's `chain` method, or assign middleware in the `middleware` parameter of a route method.

```dart
// All ways ultimately accomplish the same thing.
// Keep it readable!

// Cleanest. Use when it doesn't create visual clutter of its own.
app.chain([cors()]).get('/', 'world!');

// Another readable use of the `.chain()` method.
app.chain([cors()]).get('/something', (req, res) {
  // Do something here...
});

// Use when more than one middleware is involved, or when
// using an anonymous function as a handler (or middleware that spans
// multiple lines)
app.get('/', chain([
  someMiddleware,
  (req, res) => ...,
  (req, res) {
    return 'world!';
  },
]));

// The `middleware: ` parameter is used internally by `package:angel_route`.
// Avoid using it when you can.
app.get('/', 'world!', middleware: [someListOfMiddleware]);
```

Though this might at first seem redundant, there are actually reasons for all three existing.

By convention, though, follow these *readability* rules when building Angel servers:

* Routes with no middleware should not use `chain`, `app.chain`, or \`middleware. Self-explanatory.
* Routes with one middleware and one handler should use `app.chain([...])` when:
  * The construction of all the middleware does not take more than one line.
* In all other cases, use the `chain` meta-handler.
* Avoid using `middleware: ...` directly, as it is used internally `package:route`.

### Global Middleware

To add a handler that handles *every* request, call `app.fallback`. This is merely shorthand for calling `app.all('*', <handler>)`. (more info on request lifecycle [here](/2.x/guides/request-lifecycle)).

```dart
app.fallback((req, res) async => res.close());
```

For more complicated middleware, you can also create a class.

Canonically, when using a class as a request handler, it should provide a `handleRequest(RequestContext, ResponseContext)` method. This pattern is seen throughout many Angel plugins, such as `VirtualDirectory` or `Proxy`.

The reason for this is that a name like `handleRequest` makes it very clear to anyone reading the code what it is supposed to do. This is the same rationale behind [controllers](/2.x/guides/controllers) providing a `configureServer` method.

```dart
class MyCanonicalHandler {
 Future<bool> handleRequest(RequestContext req, ResponseContext res) async {
  // Do something cool...
 }
}

app.use(MyCanonicalHandler().handleRequest);
```

### Maintaining Code Readability

Take the following example. At first glance, it might not be very easy to read.

```dart
app.get('/the-route', chain([
  banIp('127.0.0.1'),
  'auth',
  ensureUserHasAccess(),
  (req, res) async => true,
  takeOutTheTrash()
  (req, res) {
   // Your route handler here...
  }
]));
```

In general, consider it a code smell to stack multiple handlers onto a route like this; it hampers readability, and in general just doesn't look good.

Instead, when you have multiple handlers, you can split them into multiple `chain` calls, assigned to variables, which have the added benefit of communicating what each set of middleware does:

```dart
var authorizationMiddleware = chain([
 banIp('127.0.0.1'),
 requireAuthentication(),
 ensureUserHasAccess(),
]);

var someOtherMiddleware = chain([
 (req, res) async => true,
 takeOutTheTrash(),
]);

var theActualRouteHandler = (req, res) async {
 // Handle the request...
};

app.get('/the-route', chain([
 authorizationMiddleware,
 someOtherMiddleware,
 theActualRouteHandler,
]);
```

**Tip**: Prefer using named functions as handlers, rather than anonymous functions, or concrete objects.

## Next Up...

Take a good look at [controllers](/2.x/guides/controllers) in Angel!


# Controllers

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

## 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](https://en.wikipedia.org/wiki/Model–view–controller) format. You can also use the [`group()`](/2.x/guides/basic-routing-1#route-groups) method of any [`Router`](https://www.dartdocs.org/documentation/angel_common/latest/angel_framework/Router-class.html).

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](/2.x/guides/dependency-injection).

```dart
import 'package:angel_framework/angel_framework.dart';
import 'package:angel_container/mirrors.dart';

@Expose("/todos")
class TodoController extends Controller {

  @Expose("/:id")
  getTodo(id) async {
    return await someAsyncAction();
  }

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

main() async {
  Angel app = new Angel(reflector: MirrorsReflector());
  await app.configure(new TodoController().configureServer);
}
```

Rather than extending from `Routable`, controllers act as [plugins](https://github.com/angel-dart/angel/wiki/Using-Plug-ins) when called. This pseudo-plugin will wire all your routes for you.

### @Expose()

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

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

  const Expose(Pattern this.path,
      {String this.method: "GET",
      List this.middleware: const [],
      String this.as: null,
      List<String> 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: 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.

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

main() async {
  Angel app = new Angel();

  app.get("/some/path", (req, res) async => 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](/2.x/guides/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.

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

### Transforming Data

You can use [middleware](/2.x/guides/middleware) to de/serialize data to be processed in a controller method.

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

  return true;
}

@Expose("/user", middleware: const [deserializeUser])
class UserController extends Controller {

  @Expose("/:id/name")
  Future<String> getUserName(User user) async {
    return user.username;
  }

}

main() async {
  Angel app = new Angel();
  await app.configure(new UserController().configureServer);
}
```

## Next Up...

1. How to [handle parse request bodies](/2.x/guides/body-parsing) with Angel
2. [Using Angel Plug-ins](/2.x/guides/using-plug-ins)


# Parsing Request Bodies

Interactive Web applications typically require some type of user input (whether that user is a human, machine, or otherwise is irrelevant). Angel features built-in support for parsing request bodies with the following content types:

* `application/x-www-form-urlencoded`
* `application/json`
* `multipart/form-data`

## Parsing the body

All you need to do to parse a request body is call `RequestContext.parseBody`. This method is idempotent, and only ever performs the body-parsing logic once, so it is recommended to call it any time you access the request body, unless you are 100% sure that it has been parsed before.

You can access the body as a `Map`, `List`, or `Object`, depending on your use case:

```dart
app.post('/my_form', (req, res) async {
    // Parse the body, if it has not already been parsed.
    await req.parseBody();

    // Access fields from the body, which is the most common use case.
    var userId = req.bodyAsMap['user_id'] as String;

    // If the user posted a List, i.e., through JSON:
    var count = req.bodyAsList.length;

    // To access the body, regardless of its runtime type:
    var objectBody = req.bodyAsObject as SomeType;
});
```

## Handling File Uploads

In the case of `multipart/form-data`, Angel will also populate the `uploadedFiles` field. The `UploadedFile` wrapper class provides mechanisms for reading content types, metadata, and accessing the contents of an uploaded file as a `Stream<List<int>>`:

```dart
app.post('/upload', (req, res) async {
    await req.parseBody();

    var file = req.uploadedFiles.first;

    if (file.contentType.type == 'video') {
        // Write directly to a file.
        await file.data.pipe(someFile.openWrite());
    }
});
```

## Custom Body Parsing

You can handle other content types by manually parsing the body. You can set `bodyAsObject`, `bodyAsMap`, or `bodyAsList` exactly once:

```dart
Future<void> unzipPlugin(Angel app) async {
    app.fallback((req, res) async {
        if (!req.hasParsedBody
            && req.contentType.mimeType == 'application/zip') {
            var archive = await decodeZip(req.body);
            var fields = <String, dynamic>{};

            for (var file in archive.files) {
                fields[file.path] = file.mode;
            }

            req.bodyAsMap = fields;
        }

        return true;
    });
}
```

If the user did not provide a `content-type` header when `parseBody` is called, a `400 Bad Request` error will be thrown.


# Using Plug-ins

* [Using Plug-ins](/2.x/guides/using-plug-ins#using-plug-ins)
  * [Execution Order](/2.x/guides/using-plug-ins#execution-order)
  * [Writing a Plug-in](https://github.com/angel-dart/angel/wiki/Writing-a-Plugin)
* [Next Up...](/2.x/guides/using-plug-ins#next-up)

## Using Plug-ins

Angel is designed to be extensible. As such, it exposes a typedef, `AngelConfigurer`, that has special privileges within the framework - they act as plug-ins and can be called via `app.configure()`.

Plug-ins simply need to accept an `Angel` instance as a parameter, and return a `Future` (the result of which will be ignored, unless it throws an error). `Angel` instances have several facilities available to be customized, and thus it is easy to use a custom plug-in to bring about desired functionality within your application.

```dart
typedef Future AngelConfigurer(Angel app);
```

As a convention, Angel plug-ins should be hooked up **before** the call to `startServer`.

```dart
import 'dart:io';
import 'package:angel_framework/angel_framework';

plugin(Angel app) async {
  print("Do stuff here");
}

main() async {
  Angel app = new Angel();
  await app.configure(plugin);
  await app.startServer();
}
```

### Execution Order

Plugins are usually immediately invoked by `app.configure()`. However, you may run into certain plug-ins that depend on other facilities already being available, or all of your [services](https://github.com/angel-dart/gitbook/tree/54d8067cabe0aaea05a76df8fbcfac7c57bc7450/guides/ervice-basics.md) already being mounted. You can set aside a plug-in to be run just before server startupby adding it to `app.startupHooks`, instead of directly calling `app.configure()`.

```dart
app.startupHooks.addAll([
  myPlugin(),
  AngelWebSocket().configureServer,
  fooBarBazQuux()
]);
```

Likewise, you can add hooks that run just before the app is shutdown, via `Angel.shutdownHooks`.

## Next Up...

Learn how to generate content for clients by [rendering views](/2.x/guides/rendering-views).


# Rendering Views

* [Rendering Views](/2.x/guides/rendering-views#rendering-views)
  * [Example](/2.x/guides/rendering-views#example)
  * [`ViewGenerator` typedef](/2.x/guides/rendering-views#viewgenerator)
* [Next Up...](/2.x/guides/rendering-views#next-up)

## Rendering Views

Just like `res.render` in Express, Angel's `ResponseContext` exposes a `Future` called `render`. This invokes whichever function is assigned to your server's `viewGenerator`.

There is a Mustache templating plug-in for Angel available: <https://github.com/angel-dart/mustache>

There is also [Jael](https://github.com/angel-dart/jael), one of the few actively-developed HTML templating engines for Dart.

Angel support for Jael is provided through [`package:angel_jael`](https://pub.dartlang.org/packages/angel_jael).

Another is Jinja2, which was recently ported by to Dart by [Olzhas Suleimen](https://github.com/ykmnkmi/jinja.dart).

Angel support for Jinja2 can be found here: <https://pub.dartlang.org/packages/angel_jinja>

### Example

```dart
app.get('/view', (req, res) async => await res.render('hello', {'locals': ['foo', 'bar']});
```

### ViewGenerator

Angel declares the following typedef:

```dart
/// A function that asynchronously generates a view from the given path and data.
typedef Future<String> ViewGenerator(String path, [Map data]);
```

A templating plug-in can assign one of these to `app.viewGenerator` to set itself up:

```dart
import 'dart:io';
import 'package:angel_framework/angel_framework.dart';

Future<void> plugin(Angel app) async {
  app.viewGenerator = (String path, [Map data]) async {
    return "Requested view $path with locals: $data";
  };
}

main() async {
  var app = new Angel();
  await app.configure(plugin);
  await app.startServer();
}
```

## Next Up...

1. Explore Angel's isomorphic [client library](https://github.com/angel-dart/client).
2. Find out how to [test Angel applications](/2.x/guides/testing).


# Service Basics

* [Services](/2.x/guides/service-basics#services)
  * [Service Parameters and Middleware](/2.x/guides/service-basics#service-parameters-and-middleware)
  * [Mounting Services](/2.x/guides/service-basics#mounting-services)
* [Next Up...](/2.x/guides/service-basics#next-up)

## Services

One of the main concepts within Angel, which is borrowed from FeathersJS, is a *service*. You more than likely have already dealt with another implementation of the service concept. In Angel, a *service* is a class that acts as a Web interface and exposes CRUD actions operating on a set of data. Angel services extend `Routable`, and thus can be mounted on a certain path and become REST endpoints.

The Angel core library includes the `Service` base class, as well as two in-memory service classes. Database adapter packages, such as [`package:angel_mongo`](https://github.com/angel-dart/mongo) include service classes that let you interact with a database without writing complex code yourself.

Services can also be filtered or reacted to with [service hooks](broken://pages/-LdMbPeA8cHCGP4-sHU6).

A service looks like this:

```dart
class MyService extends Service<String, Map<String, dynamic>> {
  // GET /
  // Fetch all resources. Usually returns a List.
  @override
  Future<List<Map<String, dynamic>>> index([Map<String, dynamic> params]);

  // GET /:id
  // Fetch one resource, by its ID
  @override
  Future<Map<String, dynamic>> read(String id, [Map<String, dynamic> params]);

  // POST /
  // Create a resource. This endpoint should return
  // the created resource.
  @override
  Future<Map<String, dynamic>> create(Map<String, dynamic> data, [Map<String, dynamic> params]);

  // PATCH /:id
  // Modifies a resource. Clients can submit only the data
  // they want to change, and the corresponding resource will
  // have only those fields changed. This endpoint should return
  // the modified resource.
  @override
  Future<Map<String, dynamic>> modify(String id, Map<String, dynamic> data, [Map<String, dynamic> params]);

  // POST /:id
  // Overwrites a resource. The existing resource is completely
  // replaced by the new data. This endpoint should return the
  // new resource.
  @override 
  Future<Map<String, dynamic>> update(String id, Map<String, dynamic> data, [Map<String, dynamic> params]);

  // DELETE /:id
  // Deletes a resource. This endpoint should return the
  // deleted resource.
  @override
  Future<Map<String, dynamic>> remove(String id, [Map<String, dynamic> params]);
}
```

There are meta-methods that default to delegating to the above:

* `findOne`
* `readMany`

You can override these for your service, if it will improve performance.

### Service Parameters and Middleware

You might notice that each service method accepts an optional `Map` of parameters. When accessed via HTTP (i.e., not over Websockets), `req.query` or `req.bodyAsMap` is passed here (`query` for `index`, `read` and `delete`, `bodyAsMap` for `create`, `update` and `modify`). To pass custom parameters to a service, you should create a middleware to do so. `@Middleware` annotations can be prepended to service classes or service methods. For example, the following will pass `foo='bar'` to every method in the service:

```dart
Future<bool> myMiddleware(RequestContext req, res) async {
  req.queryParameters['foo'] = 'bar';
  return true;
}

@Middleware(const [myMiddleware])
class MyService extends Service {
  // Responds with "['bar']"
  @override index([Map params]) async => [params['query']['foo']];
}
```

Additionally, when accessed by a client, `params` will contain a field called `provider`.

```dart
class MyService extends Service {
  @override
  create(data, [Map params]) async {
    if (params == null || params['provider'] == null) {
       // Accessed via server
    }
  }
}
```

`provider` will be a `Providers` class, whose `String via` will tell you where the service is being accessed from, i.e. `'rest'`, `'graphql'` or `'websocket'`.

### Mounting Services

As mentioned above, services extend `Routable`, so you can simply `app.use()` them. You can also supplement them with additional routes or middleware, placed *before* the mounting of a service:

```dart
app.get("/user/:id/todos", ioc((id) => fetchUserTodos(id))));

// Another way to apply a middleware to a service
app.all("/user/*", [someMiddleware], middleware: ['some', 'more', 'middleware']);

app.use('/user', TypedService<User>(MongoService(db.collection("users"))));

// Access app services. Returns a HookedService if there is one, otherwise just the plain service.
// Leading and trailing slashes are ignored.
var service = app.findService('user'); // The user service
var service = app.service<String, Map<String, dynamic>>('secret');
```

## Additional Notes

Important things to consider when writing your own service:

* [mongo](https://github.com/angel-dart/mongo/blob/master/lib/mongo_service.dart) is a good reference implementation]
* Services need only worry about handling `Map`s. Object serialization should be handled by `angel_serialize`, another serializer, or `TypedService`.
* Allowing users to query the service via query string is optional (see `allowQuery`)
* Allowing users to remove all entries is **optional**, and should be disabled by default
  * `DELETE /null` should trigger an evaluation of `allowRemoveAll`
  * `Service.toId` will return `null` in these cases
* Always return the most recent representation of the data
  * After `remove`, return the old item
  * After modify/update, return what the item looks like in the database
* `modify` and `update` are **not** interchangeable!
  * `modify` merges changes into an existing item
  * `update` **overwrites** an existing item
  * BOTH should create an item with the given ID if it does not already exist


# Testing

* [Testing](/2.x/guides/testing#testing)
  * [`connectTo(...)`](/2.x/guides/testing#connectto)
  * [`isJson(..)`](/2.x/guides/testing#isjson)
  * [`hasStatus(...)`](/2.x/guides/testing#hasstatus)
  * [More Matchers...](/2.x/guides/testing#more-matchers)
* [Next Up...](/2.x/guides/testing#next-up)

## Testing

Dart already has fantastic testing support, through a library of [testing helpers](https://github.com/angel-dart/test) that will make test writing faster. The following functions are exported by [`package:angel_test`](https://github.com/angel-dart/test), and will make your testing much easier.

### connectTo

[Full definition](https://www.dartdocs.org/documentation/angel_test/latest/angel_test/connectTo.html)

This function will start `app` on an available port, and return a `TestClient` instance (based on [`package:angel_client`](https://github.com/angel-dart/client)) configured to send requests to the server. The client also supports session manipulation.

```dart
main() {
  TestClient client;

  setUp(() async {
    client = await connectTo(myApp);
  });

  // Shut down server, and cancel pending requests
  tearDown(() => client.close());

  test('hello', () async {
    // The server URL is automatically prepended to paths.
    // This returns an http.Response. :)
    var response = await client.get('/hello');
  });
}
```

### isJson

A `Matcher` that asserts that the given `http.Response` equals `value` when decoded as JSON. This uses `test.equals` internally, so anything that would pass that matcher passes this one.

### hasStatus

A `Matcher` that asserts the given `http.Response` has the given `status` code.

### More Matchers

The complete set of `angel_test` Matchers can be found [here](https://www.dartdocs.org/documentation/angel_test/latest/angel_test/angel_test-library.html).

## Next Up...

1. Find out how to [handle errors](/2.x/guides/error-handling) in an Angel application.
2. Learn how to use the handy [Angel CLI](https://github.com/angel-dart/cli).


# Error Handling

* [Error Handling](/2.x/guides/error-handling#error-handling)
* [Next Up...](/2.x/guides/error-handling#next-up)

## Error Handling

Error handling is one of the most important concerns in building Web applications. The easiest way to throw an HTTP exception is to actually `throw` one. Angel provides an `AngelHttpException` class to take care of this.

```dart
app.get('/this-page-does-not-exist', (req, res) async {
  // 404 Not Found
  throw new AngelHttpException.notFound();
});
```

Of course, you will probably want to handle these errors, and potentially render views upon catching them.

Fortunately, Angel runs every request in a `try`/`catch`, and gracefully intercepts exceptions. This enables Angel to catch errors on every request, and not crash the server. Unhandled errors are wrapped in instances of `AngelHttpException`, which can be handled as follows.

You can also turn on the `useZone` flag in `AngelHttp` or another driver (i.e. HTTP/2) to run each request in its own `Zone`, though by Angel 2, this is no longer necessary.

To provide custom error handling logic:

```dart
// Typically, you want to preserve the old error handler, unless you are
// completely replacing the functionality.
var oldErrorHandler = app.errorHandler;

app.errorHandler = (e, req, res) {
  if (someCondition || req.accepts('text/html', strict: true)) {
    // Do something else special...
  } else {
    // Otherwise, use the default functionality.
    return oldErrorHandler(e, req, res);
  }
}
```

## Next Up...

Congratulations! You have completed the basic Angel tutorials. Take what you've learned on a spin in a small side project, and then move on to learning about [services](https://github.com/angel-dart/gitbook/tree/a86bb3ed5ef10659302349798bc64097e527b725/guides/service-basics.md).


# Pattern Matching and Parameter

`package:angel_framework` has nice support for injecting values from HTTP headers, query string, and session/cookie values, as well as pattern-matching for request handlers.

These act as a clean shorthand for commonly-used functionality.

Here is a simple example of each of them in action:

```dart
app.get('/cookie', ioc((@CookieValue('token') String jwt) {
    return jwt;
}));

app.get('/header', ioc((@Header('x-foo') String header) {
    return header;
}));

app.get('/query', ioc((@Query('q') String query) {
    return query;
}));

app.get('/session', ioc((@Session('foo') String foo) {
    return foo;
}));

app.get('/match', ioc((@Query('mode', match: 'pos') String mode) {
    return 'YES $mode';
}));

app.get('/match', ioc((@Query('mode', match: 'neg') String mode) {
    return 'NO $mode';
}));

app.get('/match', ioc((@Query('mode') String mode) {
    return 'DEFAULT $mode';
}));
```

## `@Header()`

A simple parameter annotation to inject the value of a sent HTTP header. Throws a 400 if the header is absent.

## `@Query()`

Searches for the value of a query parameter.

## `@Session()`

Fetches a value from the session.

## `@CookieValue()`

Gets the value of a cookie.

## `@Parameter()`

The base class driving the above matchers.

Supports:

* `defaultValue`
* `required`
* custom `error` message

<https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/Parameter-class.html>


# Command Line

The [Angel CLI](https://github.com/angel-dart/cli) is a friendly command line tool enabling quick scaffolding of common project constructs.

To install it:

```bash
$ pub global activate angel_cli
```

You'll then be able to run:

```bash
$ angel --help
```

The above will print documentation about each available command.

## Scaffolding

### New Projects

Bootstrapping a new Angel project, complete, CORS, hot-reloading, and more, is as easy as running:

```bash
$ angel init <dirname>
```

You'll be ready to go after this!

### Project Files

Use `angel make` to scaffold common Dart files:

* `angel make service` - Generate an in-memory, MongoDB, RethinkDB, file-based, or other [service](https://github.com/angel-dart/gitbook/tree/a86bb3ed5ef10659302349798bc64097e527b725/services/service-basics.md).
* `angel make test`
* `angel make plugin`
* `angel make model`
* `angel make model --orm`
* `angel make controller`

### Deployment helpers

* `sudo -E angel deploy nginx -o /etc/sites-available/my_app.conf`
* `sudo -E angel deploy systemd -o /etc/systemd/system/my_app.service`

## Renaming the Project

To rename your project, and fix all references, run:

```bash
$ angel rename <new-name>
```


# Writing a Plugin

[Guidelines](/2.x/guides/writing-a-plugin#guidelines)

Writing a [plug-in](/2.x/guides/using-plug-ins) is easy. You can provide plug-ins as either functions, or classes:

```dart
AngelConfigurer awesomeify({String message = 'This request was intercepted by an awesome plug-in.'}) {
  return (Angel app) async {
    app.fallback((req, res) async => res.write(message));
  };
}

class MyAwesomePlugin {
  @override
  Future<void> configureServer(Angel app) async {
    app.responseFinalizers.add((req, res) async {
      res.headers['x-be-awesome'] = 'All the time :)';
    });
  }
}

await app.configure(MyAwesomePlugin().configureServer);
```

## Guidelines

* Plugins should only do one thing, or serve one purpose.
* Functions are preferred to classes.
* Always need to be well-documented and thoroughly tested.
* Make sure no other plugin already serves the purpose.
* Use the provided Angel API's whenever possible. This will help your plugin resist breaking change in the future.
* Try to get it added to the `angel-dart` organization (ask in the chat).
* Plugins should *generally* be small, as they usually serve just one purpose.
* Plugins are allowed to modify app configuration.
* Stay away from `req.rawRequest` and `res.rawResponse` if possible. This can restrict people from

  using your plugin on multiple platforms.
* Avoid checking `app.isProduction`; leave that to user instead.
* Always use `req.parseBody()` before accessing the request body.

Finally, your plugin should expose common options in a simple way. For example, the (deprecated) [compress](https://github.com/angel-dart/compress) plugin has a shortcut function, `gzip`, to set up GZIP compression, whereas for any other codec, you would manually have to specify additional options.

This can greatly aid readability, as there is simply less text to read in the most common cases.

```dart
main() {
  var app = new Angel();

  // Calling gzip()
  app.responseFinalizers.add(gzip());

  // Easier than:
  app.responseFinalizers.add(compress('lzma', lzma));
}
```


# Packages


# Database Adapters


# Front-end


# Jael template engine

**Jael** is a simple, yet powerful, server-side HTML templating engine for Dart. Although it can be used in any application, it comes with first-class support for the [Angel](https://angel-dart.github.io) framework.

Though its syntax is but a superset of HTML, it supports features such as:

* **Custom elements**
* Loops
* Conditionals
* Template inheritance
* Block scoping
* `switch` syntax
* Interpolation of any Dart expression

## Small Example

```markup
<!-- layout.jl -->
<html>
    <head>
        <title>{{ title }} - My App</title>
    </head>
    <body>
        <block name="content"></block>
        <div class="footer">
          <!-- Footer content... -->
        </div>
    </body>
</html>

<!-- user-info.jl -->
<element name="user-info">
    <img src=user.avatar ?? "http://example.com/img/default-avatar">
    Hello, {{ user.name }}!
</element>

<!-- hello.jl -->
<extend src="layout.jl">
  <include src="user-info.jl" />
  <block name="content">
    <user-info @user=getCurrentlyAuthenticatedUserSomehow() />
  </block>
</extend>
```

The typical flow of a full-stack Dart application is to develop two separate apps:

* The server
* The client, an entire SPA

However, the truth is, many projects will never reach great scale, or are not extensive Web applications, and thus do not need the added complexity of an SPA. In such a case, creating an SPA will consume much excess time.

Jael allows developers to create a frontend for their application without having to worry about push state, increased development time, or having to find complex ways to achieve "server-side rendering."

Rather than forcing you to learn an entire DSL, Jael's syntax is one you already know - HTML. All directives take the form of HTML elements, and are applied either by the preprocessor or at runtime. Jael's AST is simple to patch, so it is relatively straightforward to patch it to add new features.

Jael can easily be used in any application with the following two packages:

* `package:jael`
* `package:jael_preprocessor`

However, [Angel](https://angel-dart.github.io) users only need install `package:angel_jael` to include templating in their server-side applications. One of Angel's goals is to make Web development faster, and having a tool like Jael at its disposal only brings that goal even closer to fruition.


# Basics

* [Interpolation](/2.x/packages/front-end/jael/basics#interpolation)
* [Attributes](/2.x/packages/front-end/jael/basics#attributes)
  * [Attribute Values](/2.x/packages/front-end/jael/basics#attribute-values)
  * [Quoted Attribute Names](/2.x/packages/front-end/jael/basics#quoted-attribute-names)
  * [Unescaped Attributes](/2.x/packages/front-end/jael/basics#unescaped-attributes)

Jael syntax is a superset of HTML. The following is valid both in HTML and Jael:

```markup
<!DOCTYPE html>
<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <h1>Hello!</h1>
  </body>
</html>
```

However, Jael adds two major changes.

## Interpolation

Firstly, text blocks can contain *interpolations*, which are merely Dart expression contained in double curly braces (`{{ }}`). The value within the braces, once evaluated will be HTML escaped, to prevent XSS. To achieve unescaped output, append a hyphen (`-`) to the first brace (`{{- }}`).

```markup
<div>
  {{ user.name }}
</div>

<!-- Do not HTML escape this: -->
<div>
  {{- raw.data.will.not.be('escaped') }}
</div>
```

## Attributes

Secondly, whereas in HTML, the values of attributes can only be strings, Jael allows for their values to be any Dart expression:

```markup
<img src=profile.avatar ?? "http://example.com/img/avatars/default.png">
<a class=['btn', 'ban-default', 'btn-lg']>Link</a>
<p style={'color': 'red'}></p>
```

### Attribute Values

Values are handled as such:

* Maps: Serialized as though they were `style` attributes.
* Iterables: Joined by a space, like `class` attributes.
* Anything else: `toString()` is invoked.

### Quoted Attribute Names

In case the name of your attribute is not a valid Dart identifier, you can wrap it with quotes, and it will still be processed as per normal:

```markup
<button "(click)"="myEventHandler($event)" />
```

### Unescaped Attributes

These will also be HTML escaped; however, you can replace `=` with `!=` to print unescaped text:

```markup
<img src!="<SCARY XSS STRING BEWARE!!!>" />
```


# Custom Elements

HTML is good for its purpose, because each element (ex. `div`, `a`, `ul`), has its own purpose, and when invoked, reproduces specific functionality.

The goal of proposals like Web Components, and frameworks like React, Vue, and Angular, is to let developers create custom components that encapsulate data and can be called to reproduce specific output.

Jael also supports defining elements; in fact, they are analogous to defining functions in Dart code.

The benefit of defining custom elements in Jael as opposed to in a client-side framework is that they build directly to standard HTML, and require no additional features in an end-user's browser.

## Defining Elements

To define your own element, simply use the `<element>` tag:

```markup
<element name="todo-item">
    <input type="checkbox" checked=todo.completed disabled>
    {{ todo.text }}
</element>
```

The best practice is to define elements in their own file, so that they can be imported into the scope using an  tag:

```markup
<extend src="layout.jl">
    <block name="content">
        <include src="todo-item.jl" />
        <todo-item for-each=todos @todo=item />
    </block>
</extend>
```

## Passing Data

You might have noticed that in the earlier example, some attributes of the `todo-item` were prefixed with an arroba (`@`), while others were not. There is, of course, a reason for this.

When rendering a custom element, attributes with the `@` are injected into the custom element's scope. This is analogous to passing arguments to a function.

Attributes without the `@` are passed to the root of the created element. Thus, you can pass attributes like `class` and `style` to custom elements, and therefore apply visual effects, etc.

Directives like `if` and `for-each` also work with custom elements, of course.

## Specifying a Tag Name

By default, custom elements are replaced with a `div`. There may be times you wish to override this, for example, to render a `todo-item` as an `a` element.

Use the special `as` attribute to facilitate this:

```markup
<todo-item as="a" for-each=todos @todo=item />
```

## Emitting without a Tag Name

There may be times when you need to emit the contents of an element, *without* a container element. In such a case, pass `as=false`, and the contents will be rendered in the current context, rather than in a new element.


# Strict Resolution

Dart is an imperative language, where you have the agency to cast values to other types, to execute multiple statements, and ultimately create a program by explicitly declaring every action that should be taken.

HTML, and subseqently, Jael, are declarative markup languages, and thus give you considerably less control over the flow of data and type information. Functionality like type checks, which are manageable in Dart, are both unintuitive and verbose in a markup language.

To compensate, Jael can enable or disable what can be referred to as *strict resolution*. `package:angel_jael` by default disables strict resolution, and `strictResolution` is available as a parameter to both the `jael` function in Angel, and the `Render()` constructor in Jael.

Jael's expression parser is **not** the one from `package:analyzer`, so the evaluation of expressions at runtime is up to the `Renderer` class. When strict resolution is on, all referenced identifiers **must** be present in the scope, and the only values allowed for `if`, conditionals, and similar expressions are `bool`.

For example, take the following snippet:

```markup
<ul if=user?.name?.isNotEmpty>
  <li>
    Talk to @{{ user.name }}
  </li>
</ul>
```

If strict resolution is **on**:

* If `user` is not in the scope of values passed to the renderer, an error will be thrown.
* If the expression `user?.name?.isNotEmpty` is `null`,

  then an error will be thrown.

If strict resolution is **off**:

* If `user` is not in the scope of values, Jael will just substitute it with `null`.
* If `user?.name` is `null`, Jael will substitute the expression with `null`.
* If the expression `user?.name?.isNotEmpty` does not evaluate to `true`

  (that is to say, it *can* be `null`!), then the `ul` will simply not be rendered.

Overall, strict resolution should likely be off for most cases, as type checking is not often that important when writing HTML templates.


# Directive: declare

Use a `declare` tag to *create* named variables within a block scope. This is analogous to a variable declaration in Dart.

This Dart code:

```dart
var one = 1, two = 2, three = null;
```

Becomes this Jael:

```markup
<declare one=1 two=2 three>
 // Scoped content...
</declare>
```

Another example (this is actually the test for `declare` functionality):

```markup
<div>
 <declare one=1 two=2 three=3>
   <ul>
    <li>{{one}}</li>
    <li>{{two}}</li>
    <li>{{three}}</li>
   </ul>
   <ul>
    <declare three=4>
      <li>{{one}}</li>
      <li>{{two}}</li>
      <li>{{three}}</li>
    </declare>
   </ul>
 </declare>
</div>
```

Which yields:

```markup
<div>
  <ul>
    <li>
      1
    </li>
    <li>
      2
    </li>
    <li>
      3
    </li>
  </ul>
  <ul>
    <li>
      1
    </li>
    <li>
      2
    </li>
    <li>
      4
    </li>
  </ul>
</div>
```


# Directive: for-each

To render content for each member of an `Iterable`, use the `for-each` directive:

```markup
<ul>
  <li for-each=artists as="artist">
    <a href="/artist/" + artist.id>
      {{ artist.name }}
    </a>
  </li>
</ul>
```

Use an `as` attribute to specify the name each member of the iterable will be scoped as. If it is not provided, it defaults to `item`:

```markup
<ul>
  <li for-each=[1, 2, 3]>
    {{ item }} takes {{ item.bitLength }} bit(s) to store.
  </li>
</ul>
```


# Directive: extend

Jael supports template inheritance by means of `extend` and `block`.

Note the following example:

```markup
<!-- layout.jl -->
<html>
    <head>
        <title>{{ title }} - My App</title>
    </head>
    <body>
        <block name="content"></block>
        <div class="footer">
          <!-- Footer content... -->
        </div>
    </body>
</html>

<!-- hello.jl -->
<extend src="layout.jl">
  <block name="content">
    <img src=user.avatar ?? "http://example.com/img/default-avatar">
    Hello, {{ user.name }}!
  </block>
</extend>
```

To extend a layout, instead of the file containing an `<html>` node, create a file with an `<extend>` node. The `src` attribute should point to the correct file. Then, add `<block>` tags that will replace the corresponding `<block>` tags declared in the parent file.


# Directive: if

Similar to `*ngIf` in Angular, Jael supports a simple `if` directive. Use `if` to only an element if a certain condition is `true`:

```markup
<i if=user.locale == 'en'>
  Hello, {{ user.name }}!
</i>
<i if=user.locale == 'jp'>
  こんにちは, {{ user.name }}!
</i>
```


# Directive: include

Use an `include` tag to copy in the contents of another template into the current one. The path, specified with a `src` attribute, will be resolved relative to the path of the current file.

This set-up:

```markup
<!-- components/todo.jl -->
<div class="list-item">
  <div class="title">{{ todo.title }}</div>
</div>

<!-- todo_list.jl -->
<div class="list">
  <div for-each=todos as="todo">
    <include src="components/todo.jl" />
  </div>
</div>
```

Will be renderered as:

```markup
<div class="list">
  <div>
    <div class="list-item">
      <div class="title">Clean your room</div>
    </div>
  </div>
  <div>
    <div class="list-item">
      <div class="title">Do the dishes</div>
    </div>
  </div>
</div>
```


# Directive: switch

Jael's `switch` directive is similar to a Dart `switch` statement. It takes a `value` as input, and evaluates an infinite number of `case` tags, only evaluating the first whose value matches the one in question. A `default` tag can be provided as a fallback.

```markup
<switch value=account.isDisabled>
  <case value=true>
    Good riddance!
  </case>
  <case value=false>
    You are in good standing.
  </case>
  <default>
    Weird...
  </default>
</switch>
```


# Introduction

[![The Angel Framework](https://angel-dart.github.io/assets/images/logo.png)](https://angel-dart.github.io)

[![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg)](https://gitter.im/angel_dart/discussion) [![Pub](https://img.shields.io/pub/v/angel_framework.svg)](https://pub.dartlang.org/packages/angel_framework) [![Build status](https://travis-ci.org/angel-dart/framework.svg?branch=master)](https://travis-ci.org/angel-dart/framework) ![License](https://img.shields.io/github/license/angel-dart/framework.svg)

**Fill out the** [**v1.0.0 survey**](https://docs.google.com/forms/d/e/1FAIpQLSfEgBNsOoi_nYZMmg2IAGyMv1nNaa6B3kUk3QdNJU5987ucVA/viewform?usp=sf_link) **now!!!**

**The Dart server framework that's ready for showtime.**

[Contribution Guidelines](https://github.com/angel-dart/roadmap/blob/master/CONTRIBUTING.md)

[File an Issue](https://github.com/angel-dart/angel/issues)

[API Documentation](http://www.dartdocs.org/documentation/angel_framework/latest)

There are a few server-side frameworks rising within Dart at this moment, but Angel has a different goal than all the rest. Angel aims to be a server-side framework optimized for full-stack development. Angel users should be able to write both their backends and frontends **entirely** in Dart, and share as much code across each platform as possible.

## Flexible!

For this to work, Angel must be flexible, and have a low learning curve. Thus, the basic API is modeled after Express, and new functionality is added via plug-ins.

## Hot Reloading!

[Hot reloading](https://github.com/angel-dart/hot) is a great solution to slow edit-refresh cycles, and makes the Angel experience unlike that of any other framework, in *any* other language.

## Scalability!

The final goal of Angel is **scalability**. As your application grows, Angel aims to continue working, with little or no change in server-side configuration.

## Let's go!

Ready to take a swing? [Getting started](/1.x/the-basics/installation) is simple.


# 1.1.0 Migration Guide

Based on [this discussion](https://github.com/angel-dart/angel/issues/49).

Based on the changelog, up to `1.1.0`: <https://pub.dartlang.org/packages/angel_framework/versions/1.1.1#-changelog-tab->

## Main Points

* `angel_diagnostics` is deprecated - instead just pass a `Logger` and set it as `app.logger`.
* Removed `AngelFatalError`, and subsequently `fatalErrorStream`.
  * Errors are automatically create `500`. Set `app.logger` to see output.
  * `angel_errors` is no longer useful.
* Removed all `@deprecated` members.
* Removed @Hooked, beforeProcessed, and afterProcessed.
* Made injections in RequestContext private.
* Renamed properties in AngelBase to configuration.
* Added support for pattern matching and other injections via `@Parameter()`
* Officially deprecated properties in Angel.
* Fixed a bug where cached routes would not heed the request method. #173
* Reworked error handling logic; now, errors will not automatically default to sending JSON.
* Removed the onController stream from Angel.
* Controllers now longer use call, which has now been renamed to configureServer.

### Notes

Aside from these points, there are several things to note.

Migration in itself will be pretty easy to achieve. Plugins and services haven't really changed, it's just the HTTP server itself.

## What should I use instead of `X`?

In 1.1.0, the following were completely removed:

* `Angel.after`,
* `Angel.before`
* `Angel.justBeforeStart`
* `Angel.justBeforeStop`
* `Angel.fatalErrorStream`
  * There is no replacement for `before`/`after`. This way, it is easier to keep track of the order request handlers run. responseFinalizers are still in place.
  * `justBeforeStart`, `justBeforeStop` => `startupHooks`, `shutdownHooks`
  * `fatalErrorStream` is no longer necessary; you can just set `app.errorHandler`. Fatal errors will be wrapped in a 500 response.

## How should I define global middleware?

`app.use((req, res) => ...)`

Much cleaner in `1.1.0`. 😄


# Social


# The Basics


# Installation & Setup

* [Getting Started](/1.x/the-basics/installation#getting-started)
  * [Installation](/1.x/the-basics/installation#installation)
    * [Prerequisites](/1.x/the-basics/installation#prequisites)
* [Next Up...](/1.x/the-basics/installation#next-up)

## Getting Started

Let's get it started, ha!

### Installation

#### Prerequisites

* Firstly, ensure you have the [Dart SDK](https://www.dartlang.org/downloads/) installed.

Now, install the [Angel CLI](/1.x/the-basics/cli). The CLI includes several code generators and commands that will help you expedite your development cycle.

```bash
$ pub global activate angel_cli
```

Now, let's create a sample project, called `hello`.

Run:

```bash
$ angel init hello
```

This will create a folder called `hello`, and copy the [Angel boilerplate](https://github.com/angel-dart/angel) into it. If you wanted to initialize a project within the current directory, instead of making new one, you could have run:

```bash
$ angel init
```

You'll notice that the following folder structure is there for you:

```
.idea/ - IntelliJ metadata.
.vscode/ - VSCode metadata.
bin/ - Contains a script to run the application.
config/ - Static configuration files.
lib/
  src/
    config/ - Attach miscellaneous plugins to your application.
      plugins/ - Plugins you have written yourself.
    models/ - In-code representations of the data your application manages.
    routes/ - Routing config
      controllers/ - Contains your controllers.
    services/ - Contains RESTful services.
    validators/ - Contains validators that can validate input on the client and server sides.
test/ - Test files for services and endpoints.
tool/ - Helper files for build/task tools, such as Grinder.
views/ - Mustache views.
web/ - Client-side code.
```

It's easy to run our server. Just type the following:

```bash
# Use the `--observe` flag to enable hot reloading in Angel.
dart --observe bin/server.dart
```

And there you have it - you've created an Angel application!

## Next Up...

Continue reading to learn about [requests and responses](/1.x/the-basics/requests-and-responses).


# Without the Boilerplate

It's very easy to setup a bare-bones Angel server.

Any Dart project needs a project file, called `pubspec.yaml`. This file almost always contains a `dependencies` section, where you will install the Angel framework libraries.

```yaml
dependencies:
    angel_framework: ^1.1.0
```

You might also want to install packages such as `angel_static`, `angel_cache`, `angel_jael`, and `angel_cors`.

Next, run `pub get` on the command line, or in your IDE if it has Dart support. This will install the framework and all of its dependencies.

Next, create a file, `bin/server.dart`. Put this code in it:

```dart
import 'dart:io';
import 'package:angel_framework/angel_framework.dart';

main() async {
  Angel app = new Angel();

  app.get("/", "Hello, world!");

  var server = await app.startServer();
  print("Angel server listening on port ${server.port}");
}
```

The specifics are not that important, but there are three important calls here:

1. `Angel app = new Angel()` - The base Angel server is a simple class, and we need an instance of it to run our server. The name `app` is a convention adopted from Express. In general, call an Angel instance `app`. This has no effect on functionality, but it makes it easier for other developers to understand your code.
2. `app.get("/", "Hello, world!");` - This is a [route](/1.x/the-basics/basic-routing), and tells our server to respond to all GET requests at our server root with `"Hello, world!"`. The response will automatically be encoded as JSON. Head over to the [Basic Routing](/1.x/the-basics/basic-routing) tutorial to learn about routes, and how they work.
3. `await app.startServer(...)` - This asynchronous call is what actually starts the server listening. Without it, your application won't be accessible over HTTP (as it won't ever listen for requests).

That's it! Your server is ready to serve requests. You can easily start it from the command line like this:

```
dart bin/server.dart
```


# Requests & Responses

* [Requests and Responses](/1.x/the-basics/requests-and-responses#requests-and-responses)
  * [Return Values](/1.x/the-basics/requests-and-responses#return-values)
  * [Other Parameters](/1.x/the-basics/requests-and-responses#other-parameters)
  * [Queries, Files and Bodies](/1.x/the-basics/requests-and-responses#queries-files-and-bodies)
* [Next Up...](/1.x/the-basics/requests-and-responses#next-up)

## Requests and Responses

Angel is inspired by Express, and such, request handlers in general represent those from Express. Request handlers can be functions, or plain Dart objects (see [how they are handled](/1.x/the-basics/requests-and-responses#return-values)). Basic request handlers accept two parameters:

* [`RequestContext`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext-class.html) - Contains vital information about the client requesting a resource, such as request method, request body, IP address, etc. The request object can also be used to pass information from one handler to the next.&#x20;
* [`ResponseContext`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext-class.html) - Allows you to send headers, write data, and more, to be sent to the client. To prevent a response from being modified by future handlers, call `res.end()` to prevent further writing.

Both requests and responses contain a Map of `properties` that can be filled with arbitrary data and read/modified at any point during the [request lifecycle](/1.x/the-basics/request-lifecycle).

### Return Values

Request handlers can return any Dart value. Return values are handled as follows:

* If you return a `bool`: Request handling will end prematurely if you return `false`, but it will continue if you return `true`.
* If you return `null`: Request handling will continue, unless you closed the response object by calling [`res.end()`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext/end.html). Some response methods, such as [`res.redirect()`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext/redirect.html) or [`res.serialize()`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext/serialize.html) automatically close the response.
* Anything else: Whatever other Dart value you return will be serialized as a response. The default method is to encode responses as JSON, and to do so using reflection (see `package:json_god`). However, you can change a response's serialization method by setting `res.serializer = foo;`. If you want to assign the same serializer to all responses, call [`injectSerializer`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/Angel/injectSerializer.html) on your Angel instance. If you are only returning JSON-compatible Dart objects, like Maps or Lists, you might consider injecting `JSON.encode` as a serializer, to improve runtime performance.

### Other Parameters

Request handlers can take other parameters, instead of just a `RequestContext` and `ResponseContext`. All parameters will be [injected](/1.x/the-basics/dependency-injection) into a response, whether from [`req.injections`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext/injections.html), [`req.params`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext/params.html), or [`req.properties`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext/properties.html).

Request handlers do not even have to be functions at all. You can provide singleton values as request handlers, and they will always be sent to clients without running any functions.

```dart
main() {
  Angel app = new Angel();

  // String will be JSON-encoded
  app.get('/', (req, res) async => "Hello, world!");

  // Access params
  app.get('/:id', (req, res) async => "ID: ${req.params['id']}");

  app.post('/', ["More", "arbitrary", "data"]);

  app.get('/todos/:id', (String id) => fetchTodoById(id));
}
```

### Queries, Files and Bodies

[`req.query`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext/query.html) and [`req.body`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext/body.html) are `Map`s, and are available on each request. [`req.files`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext/files.html) is a List of files uploaded to the server.

**Angel automatically parses** `multipart/form-data`**,** `application/json`**, and** `application/x-www-form-urlencoded` **bodies.**

When you are in production, one way to improve performance is by only parsing request bodies when it is necessary. In such a case, you will have to use [`lazyBody()`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext/lazyBody.html), [`lazyFiles()`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext/lazyFiles.html), etc. to access request body information. The request body will only be parsed once.

```dart
main() {
  // Set this flag to lazy-parse bodies
  app.lazyParseBodies = true;

  app.get('/', () {
    // Requests that don't need the body, never see the body
  });

  app.post('/:id', (req, res) async {
    var body = await req.lazyBody();

    // Same as running:
    await req.parse();
    var body = req.body;
  });
}
```

`req.query` can be used without parsing the request body. However, the query string parser in `package:body_parser` supports advanced queries like the following, so you may consider parsing the body:

```dart
// This query string:
// ?foo=bar&bar.baz.foo=hello&bar.world=quux
//
// becomes:
{
  "foo": "bar",
  "bar": {
    "world": "quux",
    "baz": {
      "foo": "hello"
    }
  }
}
```

If you [write your own plugin](/1.x/advanced/writing-a-plugin), be sure to use the `lazy` alternatives.

For more information, see the API docs:

[RequestContext](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/RequestContext-class.html)

[ResponseContext](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/ResponseContext-class.html)

## Next Up...

Now, let's learn about Angel's [flexible router](/1.x/the-basics/basic-routing).


# Dependency Injection

Angel uses Emil Persson's [Container](https://pub.dartlang.org/packages/container) for DI. Dependency injection makes it easier to build applications with multiple moving parts, because logic can be contained in one location and reused at another place in your application.

## Adding a Singleton

```dart
class MyPlugin extends AngelPlugin {
  @override
  call(Angel app) async {
    app.container.singleton(new SomeClass("foo"));
  }
}

class SomeClass {
  String text;
  SomeClass(this.text);
}
```

You can also inject within a `RequestContext`.

```dart
// Inject types
req.inject(Todo, someTodoInstanceSingleton);

// Or by name
req.inject('database', await databaseProvider.connect('proto://conn-string'));

// Inject into *every* request
app.inject('foo', bar);
```

## In Routes and Controllers

```dart
app.get("/some/class/text", (SomeClass singleton) => singleton.text); // Always "foo"

app.post("/foo", (SomeClass singleton, {Foo optionalInjection});

@Expose("/my/controller")
class MyController extends Controller {

  @Expose("/bar")
  // Inject classes from container, request parameters or the request/response context :)
  bar(SomeClass singleton, RequestContext req) => "${singleton.text} bar"; // Always "foo bar"

  @Expose("/baz")
  baz({Foo optionalInjection});
}
```

As you can imagine, this is very useful for managing things such as database connections.

```dart
configureServer(Angel app) async {
  var db = new Db("mongodb://localhost:27017/db");
  await db.open();
  app.container.singleton(db);
}

@Expose("/users")
class ApiController extends Controller {
  @Expose("/:id")
  fetchUser(String id, Db db) => db.collection("users").findOne(where.id(new ObjectId.fromHexString(id)));
}
```

## Dependency-Injected Controllers

`Controller`s have dependencies injected without any additional configuration by you. However, you might want to inject dependencies into the constructor of your controller.

```dart
@Expose('/controller')
class MyController {
  final AngelAuth auth;
  final Db db;

  MyController(this.auth, this.db);

  @Expose('/login')
  login() => auth.authenticate('local');
}

main() async {
  // At some point in your application, register necessary dependencies as singletons...
  app.container.singleton(auth);
  app.container.singleton(db);

  // Create the controller with injected dependencies
  await app.configure(app.container.make(MyController));
}
```


# Basic Routing

* [Routing](/1.x/the-basics/basic-routing#routing)
* [Route Parameters](/1.x/the-basics/basic-routing#route-parameters)
* [`RegExp` Routes](/1.x/the-basics/basic-routing#regexp-routes)
* [Mounting and Sub-Apps](/1.x/the-basics/basic-routing#sub-apps)
* [Route Groups](/1.x/the-basics/basic-routing#route-groups)
* [Extended Documentation](/1.x/the-basics/basic-routing#extended-documentation)
* [Next Up...](/1.x/the-basics/basic-routing#next-up)

## Routing

There is only one method responsible for adding routes to your application:

```dart
app.addRoute('<method>', '<path>', requestHandler);
```

However, the following methods are available for convenience, and are the ones you will use most often. Each method's name responds to an HTTP request method. For example, a route declared with `app.get(...)`, will respond to HTTP `GET` requests.

```dart
app.get('<path>', requestHandler);
app.post('<path>', requestHandler);
app.patch('<path>', requestHandler);
app.delete('<path>', requestHandler);
```

Your `requestHandler` can be any Dart value, whether a function, or an object. See the [Requests and Responses](/1.x/the-basics/requests-and-responses#return-values) pages for detailed documentation.

Route paths *do not* have to begin with a forward slash, as leading and trailing slashes are stripped from route paths internally.

## Route Parameters

Say you're building an API, or an MVC application. You typically want to serve the same view template on multiple paths, corresponding to different ID's. You can do this as follows, and all parameters will be available via `req.params`:

```dart
app.get('/todos/:id', (RequestContext req, res) async => {'id': req.params['id']});
```

Remember, route parameters *must* be preceded by a colon (':'). Parameter names must start with a letter or underscore, optionally followed by letters, underscores, or numbers. Parameters will match any character except a forward slash ('/') in a request URI.

Examples:

* `:id`
* `:_hello`
* `:param123`

## RegExp Routes

You can also use a `RegExp` as a route pattern, but you may have to parse the URI yourself, if you need to access specific parameters.

```dart
app.post(new RegExp(r'\/todos/([A-Za-z0-9]+)'), (req, res) async => "RegExp");
```

Route parameters can also have custom regular expressions, to remove the requirement of manual parsing. Simply enclose the regular expression in a set of parentheses following the parameter's name.

```dart
app.get(r'/number/:num([0-9]+(\.[0-9])?)', ...);
```

## Sub-Apps

You can `mount` routers, or `use` entire sub-apps.

```dart
Angel app = new Angel();
app.get('/', 'Hello!');

var subRouter = new Router()..get('/', 'Subroute');
app.mount('/sub', subApp);
// Now, you can visit /sub and receive the message "Subroute"

var subApp = new Angel()..get('/hello', 'world');
app.use('/api', subApp);

// GET /api/hello returns "world"
```

## Route Groups

Routes can also be grouped together. Route parameters will be applied to sub-routes automatically. Route groups can be nested as well.

```dart
app.group('/user/:id', (router) {
  router.get('/messages', (String id) => fetchUserMessages(id));
  router.group('/nested', ...);
});
```

## Extended Documentation

For more documentation on the router, see [its repository](https://github.com/angel-dart/route). [`package:angel_route`](https://pub.dartlang.org/packages/angel_route) has no `dart:io` or `dart:mirrors` dependency, and it also supports browser use (both hash and push state).

## Next Up...

Learn how [middleware](/1.x/the-basics/middleware) let you reuse functionality across your entire routing setup.


# Request Lifecycle

Requests in the Angel framework go through a relatively complex lifecycle, and to truly master the framework, one must understand that lifecycle.

1. `startServer` is called.
2. Each `HttpRequest` is sent through `handleRequest`.
3. `beforeProcessed` is fired with the `HttpRequest`.
4. `handleRequest` converts the `HttpRequest` to a `RequestContext`, and converts its `HttpResponse` into a

   `ResponseContext`.
5. `angel_route` is used to match the request path to a list of request handlers.
6. `before` and `after` are combined with the handler list.
7. Each handler is executed.
8. `afterProcessed` is fired with the `HttpRequest`.
9. *All* `responseFinalizers` are run, if `res.willCloseItself != true`.
10. If `res.willCloseItself = false`, all headers, the status code and the response buffer are sent through the actual `HttpResponse`.
11. The `HttpResponse` is closed.

If at any point an error occurs, Angel will catch it. See the [error handling](/1.x/the-basics/error-handling) docs for more.


# Middleware

* [Middleware](/1.x/the-basics/middleware#middleware)
  * [Denying Requests via Middleware](/1.x/the-basics/middleware#denying-requests-via-middleware)
  * [Declaring Middleware](/1.x/the-basics/middleware#declaring-middleware)
  * [Named Middleware](/1.x/the-basics/middleware#named-middleware)
  * [Global Middleware](/1.x/the-basics/middleware#global-middleware)
  * [`waterfall([...])`](/1.x/the-basics/middleware#waterfall)
  * [\*\*Maintaining Code Readability](/1.x/the-basics/middleware#maintaining-code-readability)
* [Next Up...](/1.x/the-basics/middleware#next-up)

## Middleware

Sometimes, it becomes to recycle code to run on multiple routes. Angel allows for this in the form of *middleware*. Middleware are frequently used as authorization filters, or to serialize database data for use in subsequent routes. Middleware in Angel can be any route handler, whether a function or arbitrary data. You can also throw exceptions in middleware.

### Denying Requests via Middleware

A middleware should return either `true` or `false`. If `false` is returned, no further routes will be executed. If `true` is returned, route evaluation will continue. (more on request handler return values [here](/1.x/the-basics/requests-and-responses#return-values)).

As you can imagine, this is perfect for authorization filters.

### Declaring Middleware

You can call a router's `chain` method (**recommended!**), or assign middleware in the `middleware` parameter of a route method.

```dart
// Both ways ultimately accomplish the same thing

app
  .chain((req, res) {
    res.write("Hello, ");
    return true;
  }).get('/', 'world!');

app.get('/', 'world!', middleware: [someListOfMiddleware]);
```

### Named Middleware

`Router` instances allow you to assign names to middleware via `registerMiddleware`. After registering a middleware, you can include it in a route just by passing its name into the `middleware` array. If you are `mount`-ing another `Routable` or `Angel` instance, you can map all its middleware into a namespace by passing it to the `use` call.

```dart
app.registerMiddleware('deny', (req, res) async => false);
app.get('/no', 'This will never show', middleware: ['deny']);

// Using annotation
@Middleware(const ['deny'])
Future never(RequestContext req, ResponseContext res) async {
  return "This will never show either";
}

app.get('/yes', never);

// Using a middleware namespace
Angel parent = new Angel();
parent.use('/child', app, middlewareNamespace: 'child');
parent.get('/foo', 'Never shown', middleware: ['child.deny']);
```

### Global Middleware

To add a handler that handles *every* request, call `app.use`. This is equivalent to calling `app.all('*', <handler>)`. (more info on request lifecycle [here](/1.x/the-basics/request-lifecycle)).

```dart
app.use((req, res) async => res.end());
```

For more complicated middleware, you can also create a class:

```dart
class MyMiddleware {
  Future<bool> call(Angel app) async {
    // Do something...
  }
}
```

Canonically, when using a class as a request handler, it should provide a `handleRequest(RequestContext, ResponseContext)` method. This pattern is seen throughout many Angel plugins, such as `VirtualDirectory` or `Proxy`.

The reason for this is that a name like `handleRequest` makes it very clear to anyone reading the code what it is supposed to do. This is the same rationale behind [controllers](/1.x/the-basics/controllers) providing a `configureServer` method.

```dart
class MyCanonicalHandler {
 Future<bool> handleRequest(RequestContext req, ResponseContext res) async {
  // Do something cool...
 }
}

app.use(new MyCanonicalHandler().handleRequest);
```

### waterfall

You can chain middleware (or any request handler together), if you do not feel like making multiple `chain` calls, or if it is impossible to call chain multiple times, using the [`waterfall`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/waterfall.html) function:

```dart
app.chain(waterfall([
  banIp('127.0.0.1'),
  'auth',
  ensureUserHasAccess(),
  (req, res) async => true,
  takeOutTheTrash()
])).get(...);
```

### Maintaining Code Readability

Note that a cleaner representation is:

```dart
app.get('/the-route', waterfall([
  banIp('127.0.0.1'),
  'auth',
  ensureUserHasAccess(),
  (req, res) async => true,
  takeOutTheTrash()
  (req, res) {
   // Your route handler here...
  }
]));
```

In general, consider it a code smell to stack multiple handlers onto a route like this; it hampers readability, and in general just doesn't look good.

Instead, when you have multiple handlers, you can split them into multiple `waterfall` calls, assigned to variables, which have the added benefit of communicating what each set of middleware does:

```dart
var authorizationMiddleware = waterfall([
 banIp('127.0.0.1'),
 requireAuthentication(),
 ensureUserHasAccess(),
]);

var someOtherMiddleware = waterfall([
 (req, res) async => true,
 takeOutTheTrash(),
]);

var theActualRouteHandler = (req, res) async {
 // Handle the request...
};

app.get('/the-route', waterfall([
 authorizationMiddleware,
 someOtherMiddleware,
 theActualRouteHandler,
]);
```

**Tip**: Prefer using named functions as handlers, rather than anonymous functions, or concrete objects.

## Next Up...

Take a good look at [controllers](/1.x/the-basics/controllers) in Angel!


# Controllers

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

## 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](https://en.wikipedia.org/wiki/Model–view–controller) format. You can also use the [`group()`](/1.x/the-basics/basic-routing#route-groups) method of any [`Router`](https://www.dartdocs.org/documentation/angel_common/latest/angel_framework/Router-class.html).

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.x/the-basics/dependency-injection).

```dart
import 'package:angel_framework/angel_framework.dart';

@Expose("/todos")
class TodoController extends Controller {

  @Expose("/:id")
  getTodo(id) async {
    return await someAsyncAction();
  }

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

main() async {
  Angel app = new Angel();
  await app.configure(new TodoController().configureServer);
}
```

Rather than extending from `Routable`, controllers act as [plugins](https://github.com/angel-dart/angel/wiki/Using-Plug-ins) when called. This pseudo-plugin will wire all your routes for you.

### @Expose()

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

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

  const Expose(Pattern this.path,
      {String this.method: "GET",
      List this.middleware: const [],
      String this.as: null,
      List<String> 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: 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.

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

main() async {
  Angel app = new Angel();

  app.get("/some/path", (req, res) async => 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](/1.x/the-basics/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.

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

### Transforming Data

You can use [middleware](/1.x/the-basics/middleware) to de/serialize data to be processed in a controller method.

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

  return true;
}

@Expose("/user", middleware: const [deserializeUser])
class UserController extends Controller {

  @Expose("/:id/name")
  Future<String> getUserName(User user) async {
    return user.username;
  }

}

main() async {
  Angel app = new Angel();
  await app.configure(new UserController().configureServer);
}
```

## Next Up...

1. How to [handle file uploads](https://medium.com/@thosakwe/building-a-simple-file-upload-app-with-angel-64938d4ddc61) with Angel
2. [Using Angel Plug-ins](https://github.com/angel-dart/gitbook/tree/b6d2c930acc83e9dbcb3f5f9248e250fe180c2b0/the-basics/using-plug-ins.md)


# Using Plug-ins


# Rendering Views

* [Rendering Views](/1.x/the-basics/rendering-views#rendering-views)
  * [Example](/1.x/the-basics/rendering-views#example)
  * [`ViewGenerator` typedef](/1.x/the-basics/rendering-views#viewgenerator)
* [Next Up...](/1.x/the-basics/rendering-views#next-up)

## Rendering Views

Just like `res.render` in Express, Angel's `ResponseContext` exposes a `Future` called `render`. This invokes whichever function is assigned to your server's `viewGenerator`.

There is a Mustache templating plug-in for Angel available: <https://github.com/angel-dart/mustache>

However, it is strongly recommended that you use [Jael](https://github.com/angel-dart/jael), the only actively-developed HTML templating engine for Dart.

Angel support for Jael is provided through [`package:angel_jael`](https://pub.dartlang.org/packages/angel_jael).

### Example

```dart
app.get('/view', (req, res) async => await res.render('hello', {'locals': ['foo', 'bar']});
```

### ViewGenerator

Angel declares the following typedef:

```dart
/// A function that asynchronously generates a view from the given path and data.
typedef Future<String> ViewGenerator(String path, [Map data]);
```

A templating plug-in can assign one of these to `app.viewGenerator` to set itself up:

```dart
import 'dart:io';
import 'package:angel_framework/angel_framework.dart';

Future plugin(Angel app) async {
  app.viewGenerator = (String path, [Map data]) async {
    return "Requested view $path with locals: $data";
  };
}

main() async {
  Angel app = new Angel();
  await app.configure(plugin);
  await app.startServer();
}
```

## Next Up...

1. Explore Angel's isomorphic [client library](https://github.com/angel-dart/client).
2. Find out how to [test Angel applications](https://github.com/angel-dart/gitbook/tree/a01c5d4d8f4ee5af51a98f770c765ff9e05ead1f/the-basics/testing.md).


# Testing

* [Testing](/1.x/the-basics/testing#testing)
  * [`connectTo(...)`](/1.x/the-basics/testing#connectto)
  * [`isJson(..)`](/1.x/the-basics/testing#isjson)
  * [`hasStatus(...)`](/1.x/the-basics/testing#hasstatus)
  * [More Matchers...](/1.x/the-basics/testing#more-matchers)
* [Next Up...](/1.x/the-basics/testing#next-up)

## Testing

Dart already has fantastic testing support, through a library of [testing helpers](https://github.com/angel-dart/test) that will make test writing faster. The following functions are exported by [`package:angel_test`](https://github.com/angel-dart/test), and will make your testing much easier.

### connectTo

[Full definition](https://www.dartdocs.org/documentation/angel_test/latest/angel_test/connectTo.html)

This function will start `app` on an available port, and return a `TestClient` instance (based on [`package:angel_client`](https://github.com/angel-dart/client)) configured to send requests to the server. The client also supports session manipulation.

```dart
main() {
  TestClient client;

  setUp(() async {
    client = await connectTo(myApp);
  });

  // Shut down server, and cancel pending requests
  tearDown(() => client.close());

  test('hello', () async {
    // The server URL is automatically prepended to paths.
    // This returns an http.Response. :)
    var response = await client.get('/hello');
  });
}
```

### isJson

A `Matcher` that asserts that the given `http.Response` equals `value` when decoded as JSON. This uses `test.equals` internally, so anything that would pass that matcher passes this one.

### hasStatus

A `Matcher` that asserts the given `http.Response` has the given `status` code.

### More Matchers

The complete set of `angel_test` Matchers can be found [here](https://www.dartdocs.org/documentation/angel_test/latest/angel_test/angel_test-library.html).

## Next Up...

1. Find out how to [handle errors](/1.x/the-basics/error-handling) in an Angel application.
2. Learn how to use the handy [Angel CLI](https://github.com/angel-dart/cli).


# Error Handling

* [Error Handling](/1.x/the-basics/error-handling#error-handling)
* [Next Up...](/1.x/the-basics/error-handling#next-up)

## Error Handling

Error handling is one of the most important concerns in building Web applications. The easiest way to throw an HTTP exception is to actually `throw` one. Angel provides an `AngelHttpException` class to take care of this.

```dart
app.get('/this-page-does-not-exist', (req, res) async {
  // 404 Not Found
  throw new AngelHttpException.notFound();
});
```

Of course, you will probably want to handle these errors, and potentially render views upon catching them.

Fortunately, Angel runs every request in its own [`zone`](https://api.dartlang.org/stable/dart-async/Zone-class.html). This enables Angel to catch errors on every request, and not crash the server. Unhandled errors are wrapped in instances of `AngelHttpException`, which can be handled as follows.

To provide custom error handling logic:

```dart
// Typically, you want to preserve the old error handler, unless you are
// completely replacing the functionality.
var oldErrorHandler = app.errorHandler;

app.errorHandler = (AngelHttpException e, RequestContext req, ResponseContext res) {
  if (someCondition) {
    // Do something else special...
  } else {
    // Otherwise, use the default functionality.
    return oldErrorHandler(e, req, res);
  }
}
```

## Next Up...

Congratulations! You have completed the basic Angel tutorials. Take what you've learned on a spin in a small side project, and then move on to learning about [services](/1.x/services/service-basics).


# Pattern Matching and Parameter

As of `1.1.0`, `package:angel_framework` has nice support for injecting values from HTTP headers, query string, and session/cookie values, as well as pattern-matching for request handlers.

These act as a clean shorthand for commonly-used functionality.

Here is a simple example of each of them in action:

```dart
app.get('/cookie', (@CookieValue('token') String jwt) {
    return jwt;
});

app.get('/header', (@Header('x-foo') String header) {
    return header;
});

app.get('/query', (@Query('q') String query) {
    return query;
});

app.get('/session', (@Session('foo') String foo) {
    return foo;
});

app.get('/match', (@Query('mode', match: 'pos') String mode) {
    return 'YES $mode';
});

app.get('/match', (@Query('mode', match: 'neg') String mode) {
    return 'NO $mode';
});

app.get('/match', (@Query('mode') String mode) {
    return 'DEFAULT $mode';
});
```

## `@Header()`

A simple parameter annotation to inject the value of a sent HTTP header. Throws a 400 if the header is absent.

## `@Query()`

Searches for the value of a query parameter.

## `@Session()`

Fetches a value from the session.

## `@CookieValue()`

Gets the value of a cookie.

## `@Parameter()`

The base class driving the above matchers.

Supports:

* `defaultValue`
* `required`
* custom `error` message

<https://www.dartdocs.org/documentation/angel_framework/1.1.1/angel_framework/Parameter-class.html>


# Command Line

The [Angel CLI](https://github.com/angel-dart/cli) is a friendly command line tool enabling quick scaffolding of common project constructs.

To install it:

```bash
$ pub global activate angel_cli
```

You'll then be able to run:

```bash
$ angel --help
```

The above will print documentation about each available command.

## Scaffolding

### New Projects

Bootstrapping a new Angel project, complete, CORS, hot-reloading, and more, is as easy as running:

```bash
$ angel init <dirname>
```

You'll be ready to go after this!

### Project Files

Use `angel make` to scaffold common Dart files:

* `angel make service` - Generate an in-memory, MongoDB, RethinkDB, file-based, or other [service](/1.x/services/service-basics).
* `angel make test`
* `angel make plugin`
* `angel make model`
* `angel make controller`

## Renaming the Project

To rename your project, and fix all references, run:

```bash
$ angel rename <new-name>
```


# Flutter


# Services


# Service Basics

* [Services](/1.x/services/service-basics#services)
  * [Service Parameters and Middleware](/1.x/services/service-basics#service-parameters-and-middleware)
  * [Mounting Services](/1.x/services/service-basics#mounting-services)
* [Next Up...](/1.x/services/service-basics#next-up)

## Services

One of the main concepts within Angel, which is borrowed from FeathersJS, is a *service*. You more than likely have already dealt with another implementation of the service concept. In Angel, a *service* is a class that acts as a Web interface and exposes CRUD actions operating on a set of data. Angel services extend `Routable`, and thus can be mounted on a certain path and become REST endpoints.

The Angel core includes the `Service` base class, as well as two in-memory service classes. Database adapter packages, such as [`package:angel_mongo`](https://github.com/angel-dart/mongo) include service classes that let you interact with a database without writing complex code yourself.

Services can also be filtered or reacted to with [service hooks](/1.x/services/hooks).

A service looks like this:

```dart
class MyService extends Service {
  // GET /
  // Fetch all resources. Usually returns a List.
  @override
  Future index([Map params]);

  // GET /:id
  // Fetch one resource, by its ID
  @override
  Future read(id, [Map params]);

  // POST /
  // Create a resource. This endpoint should return
  // the created resource.
  @override
  Future create(data, [Map params]);

  // PATCH /:id
  // Modifies a resource. Clients can submit only the data
  // they want to change, and the corresponding resource will
  // have only those fields changed. This endpoint should return
  // the modified resource.
  @override
  Future modify(id, data, [Map params]);

  // POST /:id
  // Overwrites a resource. The existing resource is completely
  // replaced by the new data. This endpoint should return the
  // new resource.
  @override 
  Future update(id, data, [Map params]);

  // DELETE /:id
  // Deletes a resource. This endpoint should return the
  // deleted resource.
  @override
  Future remove(id, [Map params]);
}
```

### Service Parameters and Middleware

You might notice that each service method accepts an optional `Map` of parameters. When accessed via HTTP (i.e., not over Websockets), `req.query` or `req.body` is passed here (`query` for `index`, `read` and `delete`, `body` for `create`, `update` and `modify`). To pass custom parameters to a service, you should create a middleware to do so. `@Middleware` annotations can be prepended to service classes or service methods. For example, the following will pass `foo='bar'` to every method in the service:

```dart
Future<bool> myMiddleware(RequestContext req, res) async {
  req.query['foo'] = 'bar';
  return true;
}

@Middleware(const [myMiddleware])
class MyService extends Service {
  // Responds with "['bar']"
  @override index([Map params]) async => [params['query']['foo']];
}
```

Additionally, when accessed by a client, `params` will contain a field called `provider`.

```dart
class MyService extends Service {
  @override
  create(data, [Map params]) async {
    if (params == null || params['provider'] == null) {
       // Accessed via server
    }
  }
}
```

`provider` will be a `Providers` class, whose `String via` will tell you where the service is being accessed from, i.e. `'rest'` or `'websocket'`.

### Mounting Services

As mentioned above, services extend `Routable`, so you can simply `app.use()` them. You can also supplement them with additional routes or middleware, placed *before* the mounting of a service:

```dart
app.get("/user/:id/todos", (id) => fetchUserTodos(id)));

// Another way to apply a middleware to a service
app.all("/user/*", 'some middleware', middleware: ['some', 'more', 'middleware']);

app.use('/user', new TypedService<User>(new MongoService(db.collection("users"))));

// Make a service global without exposing it to REST
app.services['secret'] = new SecretService();

// Access app services. Returns a HookedService if there is one, otherwise just the plain service.
// Leading and trailing slashes are ignored.
var service = app.service('user'); // The user service
var service = app.service('secret'); // Not exposed to REST, but can still be used easily
```

## Next Up...

Reflectively serialize and deserialize data within services by wrapping them in a [`TypedService`](/1.x/services/typedservice).


# TypedService

* [`TypedService`](/1.x/services/typedservice#typedservice)
* [Next Up...](/1.x/services/typedservice#next-up)

## TypedService

The vast majority of database adapters for Angel never touch any Dart objects other than Maps. This is good because you are not forced to run reflective code on every query, so you won't wind up creating any inescapable bottlenecks.

However, oftentimes, you will want to serialize and deserialize data in the form of a model class. A `TypedService<T>` performs this for you, and can wrap any other service. Just ensure that your `T` type extends `Model`, found in `package:angel_framework/common.dart`. Combined with the general service pattern, this serves as a sort of mini-ORM that is also database agnostic.

```dart
// foo.dart
class Foo extends Model {
  String bar;

  Foo({this.bar});
}

// foo_service.dart
app.use('/foo', new TypedService<Foo>(new RethinkService(conn, r.table('foo')));

// blah_blah_blah.dart
Foo foo = await app.service('foo').create({'bar': 'baz'});
Foo otherFoo = await app.service('foo').create(new Foo(bar: 'quux'));
```

As a bonus, `Model` classes can be used on the client and server sides of your application. Hurrah!

## Next Up...

See how the `MapService` class lets you manage data [in-memory](https://github.com/angel-dart/angel/wiki/In-Memory).


# In-Memory

* [In-Memory Services](/1.x/services/in-memory#in-memory-services)
* [Next Up...](/1.x/services/in-memory#next-up)

## In-Memory Services

The simplest data store to set up is an in-memory one, as it does not require external database setup. It only stores Maps, but it can be wrapped in a [`TypedService`](/1.x/services/typedservice).

```dart
// routes.dart
app.use('/todos', new TypedService<Todo>(new MapService()));

// todo.dart
class Todo extends Model {
  String title;
  bool completed;

  Todo({String id, this.title, this.completed : false}) {
    this.id = id;
  }
}
```

## Next Up...

Learn how to implement your own [custom services](/1.x/services/custom-services).


# Custom Services

* [Custom Services](/1.x/services/custom-services#custom-services)
  * [`AnonymousService`](/1.x/services/custom-services#anonymousservice)
* [Next Up...](/1.x/services/custom-services#next-up)

## Custom Services

Assuming you have already read [Service Basics](/1.x/services/service-basics), the process of implementing your own service is very straightforward. Simply implement the methods you want to expose.

By default, a service will throw a `405 Method Not Allowed` error if you haven't written any logic to handle a given method. This means you only need to write handlers for operations you plan to actually have carried out.

Do make sure to invoke the `super` constructor in any of your constructors, as that's where services set up their routes. Without it, your service will not be accessible to the Internet, as it will not have any front-facing routes set up at all.

```dart
class MyService extends Service {
  MyService():super() {
    // Feel free to add your own constructor, just don't
    // neglect the `super`...
  }
}
```

Alternatively, consider using [service hooks](/1.x/services/hooks). They are the preferred method of modifying Angel services because they do not depend on service implementations.

*Note*: The convention for the `remove` method on services is that if `id == null`, *all entries in the store should be removed*. Obviously, this does not work very well in production, so only allow this to occur on the server side. Common service providers will disable this for clients, unless you explicitly set a flag dictating so.

### AnonymousService

If you only need to implement a small selection of the common service methods, consider using an `AnonymousService`. They are the functional equivalent of creating a new service class. **Please do not use anonymous services in library packages.**

```dart
app.use('/todos', new AnonymousService(index: ([params]) => somehowFetchTodos()));
```

## Next Up...

Find out how to filter and react to service events with [hooks](/1.x/services/hooks).


# Hooks

* [Hooks](/1.x/services/hooks#hooks)
* [Bundled Hooks](/1.x/services/hooks#bundled-hooks)
* [Next Up...](/1.x/services/hooks#next-up)

## Hooks

Another concept borrowed from FeathersJS is the concept of *hooking services*. This is a mechanism that allows you to separate concerns within your application. For example, many sites send their users confirmation e-mails after successful registration. The logic to do this is often included in the same place as the code to create the user. Hooks allow you to keep the logic for these two tasks, which are more or less unrelated, in two separate places. And what's more, this frees you up to change your service code without having to update the confirmation code in multiple places. For example, you can easily use an in-memory user store in development, and a MongoDB one in production, and use the same confirmation code for each service. So, let's take a look.

When you `use` a service class, Angel can optionally wrap it in a `HookedService` class. A `HookedService` fires events before and after its inner service runs. This opens the opportunity for events to be canceled, or have parameters modified. `use` takes a named parameter `{bool hooked: true}`. You can also affix a `@Hooked` annotation to your service class for the same effect.

This is similar to middleware, but whereas middleware only runs before requests, hooks can run before and after.

```dart
class HookedService extends Service {
  HookedServiceEventDispatcher beforeIndexed;
  HookedServiceEventDispatcher afterIndexed;

  // And so on...
}
```

A `HookedServiceEventDispatcher` has one key method you will use: `listen`. In a way, this is similar to a broadcast stream, but it has a few catches. These dispatch `HookedServiceEvent` instances, which look like this:

```dart
/// Fired when a hooked service is invoked.
class HookedServiceEvent {
  static const String indexed = "indexed";
  static const String read = "read";
  static const String created = "created";
  static const String modified = "modified";
  static const String updated = "updated";
  static const String removed = "removed";

  /// The inner service whose method was hooked.
  Service service;

  /// The name of the event being fired. This class exposes
  /// some constant Strings you can check for, to prevent typos.
  String eventName;

  /// Read-only: The `id` passed to this event, if any.
  var id;

  /// Same as `id`.
  var data;

  /// Same as `id`. Keep in mind, although this is read-only,
  /// you can still assign values within it.
  Map params;

  /// Read-only. After an event completes, this will hold whatever
  /// value the service method returned.
  var result;

  /// If you call this, no further event callbacks will be fired.
  /// If called on a 'before' hook, no further 'before' events will fire.
  /// Same for an 'after' hook.
  ///
  /// If you call this on a 'before' hook, the actual service method
  /// will never be called. Instead, `result` will be returned as the
  /// response, and any 'after' hooks will see this value as the `result`.
  ///
  /// This is very useful, and allows another way to filter or deny access to
  /// services than traditional middleware.
  void cancel(result);
}
```

```dart
var service = app.service('api/todos') as HookedService;

service.afterCreated.listen((HookedServiceEvent e) {
  // In an `after` hook, `e.result` would be the created data.
  //In this case, it is a Todo object.
  if (!e.result.completed) {
    // Use `cancel` to prematurely end an event. In this case,
    // the following response will be given, rather than a
    // JSON-serialized Todo instance:
    e.cancel({'error': 'Hey, you still have to ${e.text}!'});
  }
});
```

Alternatively, the `Hooks` annotation can be used to assign hooks to service methods.

```dart
helloHook(e) => print('Hello, world!');
fooHook(e) => print('Bar');

@Hooks(before: const [helloHook])
class MyService extends Service {

  @Hooks(before: const [fooHook])
  index([params]) async {
    return ['world'];
  }
}
```

## Bundled Hooks

There are several hooks shipped with the Angel framework: <https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework.hooks/angel_framework.hooks-library.html>

```dart
import 'package:angel_framework/hooks.dart` as hooks;

main() {
  // ...
  service.listen(hooks.disable());
}
```

## Next Up...

Congratulations! Not only have you gotten through the basic Angel tutorials, but you've also completed the service tutorials! However, there's still a lot more to Angel for you to explore. Check out the sidebar for more! ***Happy coding!***


# Database Adapters


# Plug-ins


# Middleware/Finalizers


# PostgreSQL ORM


# Deployment


# Running in Isolates

How to run Angel in multiple isolates.

The concept is pretty simple. A normal server would look like this:

```dart
var app = new Angel();
```

If you use the `Angel.custom` constructor, you can provide a custom `ServerGenerator`, which is a typedef for a function that binds an HTTP server:

```dart
typedef Future<HttpServer> ServerGenerator(InternetAddress address, int port);
```

With this in mind, you can start a server passing the `shared` argument to `HttpServer.bind`:

```dart
new Angel.custom((address, port) => HttpServer.bind(address, port, shared: true));
```

`startShared` is a function that accomplishes this for you, since it's commonly-used functionality:

```dart
new Angel.custom(startShared);
```

## Multiple Isolates

To run in multiple isolates, the concept is simple as well:

```dart
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'package:angel_framework/angel_framework.dart';

main(List<String> args) async {
  int concurrency = Platform.numberOfProcessors;

  // Start child isolates...
  for (int i = 1; i < concurrency; i++) {
    Isolate.spawn(serverMain, i);
  }

  // Spawn a server in the main isolate.
  serverMain(concurrency);
}

void serverMain(int id) {
  // Start shared!!!
  var app = new Angel();
  var http = new AngelHttp.custom(app, startShared);

  app.get('/json', () => {'hello': 'world'});

  app.get('/db', () async {
    // Run a query...
    var connection = new PostgreSQLConnection(
        '127.0.0.1', 5432, 'wrk_benchmark',
        username: 'postgres', password: 'password');
    await connection.open();
    var rows = await connection.query('SELECT id, text from notes;');
    return rows.map((row) => {'id': row[0], 'text': row[1]});
  });

  http.startServer(InternetAddress.ANY_IP_V4, 3000).then((server) {
    print(
        'Instance #$id listening at http://${server.address.address}:${server.port}');
  });
}
```


# Configuring SSL

The `AngelHttp.secure` and `AngelHttp.fromSecurityContext` constructors allow you to run servers that listen to HTTPS requests, which is great in cases where your application handles sensitive data.

You'll need a public and private key, in PEM format:

```dart
var context = new SecurityContext()
    ..useCertificateChain('keys/server.crt')
    ..usePrivateKey('keys/server.key');
var http = new AngelHttp.fromSecurityContext(context);
```

However, a single AngelHttp instance only corresponds to one `HttpServer` instance. To handle secure requests, while also redirecting insecure users to our HTTPS server, you'll need to have a server listening at port 80.

The easiest way to do this is to use the `forceHttps()` function from `package:angel_multiserver`. This returns a [middleware](/1.x/the-basics/middleware) that sends `302` redirects from plain HTTP URL's to their HTTPS counterparts.

```dart
/// Redirect HTTP URL's to their HTTPS counterparts...
enforceHttps() async {
  var enforcer = new Angel()..use(forceHttps());
  var http = new AngelHttp(enforcer);
  var server = await http.startServer('0.0.0.0', 80);
  print(
      'HTTPS enforcer listening at http://${server.address.address}:${server.port}');
}
```

An example of this setup can be found here: <https://github.com/angel-example/ssl_multiserver/blob/master/bin/server.dart>


# Ubuntu and nginx

This is pretty simple, and doesn't require much in the way of DevOps.

[![YouTube thumbnail](https://i.ytimg.com/vi/7tpO9vhUhf4/hqdefault.jpg)](https://www.youtube.com/watch?v=7tpO9vhUhf4\&t=986s\&list=PLl3P3tmiT-frEV50VdH_cIrA2YqIyHkkY\&index=6)

Watch the video tutorial [here](https://www.youtube.com/watch?v=7tpO9vhUhf4\&t=986s\&list=PLl3P3tmiT-frEV50VdH_cIrA2YqIyHkkY).

1. Create unprivileged user `web`

   a. Can only operate in `/home/web`, where we'll host the application.
2. Install Dart for `web`
3. Set `ANGEL_ENV=production` in `web` account
4. Sync changes with the server

   a. Use SFTP

   b. Or, sync from a private Git repo

   c. Host a local Git server to sync changes

   d. Git version histories take up more space, so probably just use SFTP for this guide.
5. Set up `ufw` for `80`, `443`, `ssh`
6. Use `systemd` (comes with Ubuntu) to start server on system boot, and restart if it crashes

   a. <https://askubuntu.com/questions/919054/how-do-i-run-a-single-command-at-startup-using-systemd>
7. Basic nginx setup with `proxy_pass`
   * Don't run your application server as `root`
   * Serve static files via `nginx` instead of Angel
     * Even though `CachingVirtualDirectory` is extremely simple to use, it would be served via proxy
     * It's faster for `nginx` to serve your static files directly.


# AppEngine

You can use [`package:appengine`](https://pub.dartlang.org/packages/appengine) with Angel easily, just by passing it your app's `handleRequest` method:

```dart
import 'package:angel_framework/angel_framework.dart';
import 'package:appengine/appengine.dart';

void main() async {
  var app = new Angel();
  var http = new AngelHttp(app);
  // ...

  await runAppEngine(http.handleRequest);
}
```


# Production Mode

Angel can optionally run in "production mode," where several optimizations are applied to the base server, such as running reflective dependency injection before server startup, and flattening the server's route tree.

Production mode is considered a global setting.

`angel_configuration` will load a `config/production.yaml` file to read configuration.

To run your application in production mode, set `ANGEL_ENV` in your environment to `production`. If you are writing a plug-in with production mode-specific code, query its value as follows:

```dart
if (app.isProduction) {
  // Do some production-only stuff...
}
```


# Front-end


# Jael template engine

**Jael** is a simple, yet powerful, server-side HTML templating engine for Dart. Although it can be used in any application, it comes with first-class support for the [Angel](https://angel-dart.github.io) framework.

Though its syntax is but a superset of HTML, it supports features such as:

* **Custom elements**
* Loops
* Conditionals
* Template inheritance
* Block scoping
* `switch` syntax
* Interpolation of any Dart expression

## Small Example

```markup
<!-- layout.jl -->
<html>
    <head>
        <title>{{ title }} - My App</title>
    </head>
    <body>
        <block name="content"></block>
        <div class="footer">
          <!-- Footer content... -->
        </div>
    </body>
</html>

<!-- user-info.jl -->
<element name="user-info">
    <img src=user.avatar ?? "http://example.com/img/default-avatar">
    Hello, {{ user.name }}!
</element>

<!-- hello.jl -->
<extend src="layout.jl">
  <include src="user-info.jl" />
  <block name="content">
    <user-info @user=getCurrentlyAuthenticatedUserSomehow() />
  </block>
</extend>
```

The typical flow of a full-stack Dart application is to develop two separate apps:

* The server
* The client, an entire SPA

However, the truth is, many projects will never reach great scale, or are not extensive Web applications, and thus do not need the added complexity of an SPA. In such a case, creating an SPA will consume much excess time.

Jael allows developers to create a frontend for their application without having to worry about push state, increased development time, or having to find complex ways to achieve "server-side rendering."

Rather than forcing you to learn an entire DSL, Jael's syntax is one you already know - HTML. All directives take the form of HTML elements, and are applied either by the preprocessor or at runtime. Jael's AST is simple to patch, so it is relatively straightforward to patch it to add new features.

Jael can easily be used in any application with the following two packages:

* `package:jael`
* `package:jael_preprocessor`

However, [Angel](https://angel-dart.github.io) users only need install `package:angel_jael` to include templating in their server-side applications. One of Angel's goals is to make Web development faster, and having a tool like Jael at its disposal only brings that goal even closer to fruition.


# Basics

* [Interpolation](/1.x/front-end/jael/basics#interpolation)
* [Attributes](/1.x/front-end/jael/basics#attributes)
  * [Attribute Values](/1.x/front-end/jael/basics#attribute-values)
  * [Quoted Attribute Names](/1.x/front-end/jael/basics#quoted-attribute-names)
  * [Unescaped Attributes](/1.x/front-end/jael/basics#unescaped-attributes)

Jael syntax is a superset of HTML. The following is valid both in HTML and Jael:

```markup
<!DOCTYPE html>
<html>
  <head>
    <title>Title</title>
  </head>
  <body>
    <h1>Hello!</h1>
  </body>
</html>
```

However, Jael adds two major changes.

## Interpolation

Firstly, text blocks can contain *interpolations*, which are merely Dart expression contained in double curly braces (`{{ }}`). The value within the braces, once evaluated will be HTML escaped, to prevent XSS. To achieve unescaped output, append a hyphen (`-`) to the first brace (`{{- }}`).

```markup
<div>
  {{ user.name }}
</div>

<!-- Do not HTML escape this: -->
<div>
  {{- raw.data.will.not.be('escaped') }}
</div>
```

## Attributes

Secondly, whereas in HTML, the values of attributes can only be strings, Jael allows for their values to be any Dart expression:

```markup
<img src=profile.avatar ?? "http://example.com/img/avatars/default.png">
<a class=['btn', 'ban-default', 'btn-lg']>Link</a>
<p style={'color': 'red'}></p>
```

### Attribute Values

Values are handled as such:

* Maps: Serialized as though they were `style` attributes.
* Iterables: Joined by a space, like `class` attributes.
* Anything else: `toString()` is invoked.

### Quoted Attribute Names

In case the name of your attribute is not a valid Dart identifier, you can wrap it with quotes, and it will still be processed as per normal:

```markup
<button "(click)"="myEventHandler($event)" />
```

### Unescaped Attributes

These will also be HTML escaped; however, you can replace `=` with `!=` to print unescaped text:

```markup
<img src!="<SCARY XSS STRING BEWARE!!!>" />
```


# Custom Elements

HTML is good for its purpose, because each element (ex. `div`, `a`, `ul`), has its own purpose, and when invoked, reproduces specific functionality.

The goal of proposals like Web Components, and frameworks like React, Vue, and Angular, is to let developers create custom components that encapsulate data and can be called to reproduce specific output.

Jael also supports defining elements; in fact, they are analogous to defining functions in Dart code.

The benefit of defining custom elements in Jael as opposed to in a client-side framework is that they build directly to standard HTML, and require no additional features in an end-user's browser.

## Defining Elements

To define your own element, simply use the `<element>` tag:

```markup
<element name="todo-item">
    <input type="checkbox" checked=todo.completed disabled>
    {{ todo.text }}
</element>
```

The best practice is to define elements in their own file, so that they can be imported into the scope using an  tag:

```markup
<extend src="layout.jl">
    <block name="content">
        <include src="todo-item.jl" />
        <todo-item for-each=todos @todo=item />
    </block>
</extend>
```

## Passing Data

You might have noticed that in the earlier example, some attributes of the `todo-item` were prefixed with an arroba (`@`), while others were not. There is, of course, a reason for this.

When rendering a custom element, attributes with the `@` are injected into the custom element's scope. This is analogous to passing arguments to a function.

Attributes without the `@` are passed to the root of the created element. Thus, you can pass attributes like `class` and `style` to custom elements, and therefore apply visual effects, etc.

Directives like `if` and `for-each` also work with custom elements, of course.

## Specifying a Tag Name

By default, custom elements are replaced with a `div`. There may be times you wish to override this, for example, to render a `todo-item` as an `a` element.

Use the special `as` attribute to facilitate this:

```markup
<todo-item as="a" for-each=todos @todo=item />
```

## Emitting without a Tag Name

There may be times when you need to emit the contents of an element, *without* a container element. In such a case, pass `as=false`, and the contents will be rendered in the current context, rather than in a new element.


# Strict Resolution

Dart is an imperative language, where you have the agency to cast values to other types, to execute multiple statements, and ultimately create a program by explicitly declaring every action that should be taken.

HTML, and subseqently, Jael, are declarative markup languages, and thus give you considerably less control over the flow of data and type information. Functionality like type checks, which are manageable in Dart, are both unintuitive and verbose in a markup language.

To compensate, Jael can enable or disable what can be referred to as *strict resolution*. `package:angel_jael` by default disables strict resolution, and `strictResolution` is available as a parameter to both the `jael` function in Angel, and the `Render()` constructor in Jael.

Jael's expression parser is **not** the one from `package:analyzer`, so the evaluation of expressions at runtime is up to the `Renderer` class. When strict resolution is on, all referenced identifiers **must** be present in the scope, and the only values allowed for `if`, conditionals, and similar expressions are `bool`.

For example, take the following snippet:

```markup
<ul if=user?.name?.isNotEmpty>
  <li>
    Talk to @{{ user.name }}
  </li>
</ul>
```

If strict resolution is **on**:

* If `user` is not in the scope of values passed to the renderer, an error will be thrown.
* If the expression `user?.name?.isNotEmpty` is `null`,

  then an error will be thrown.

If strict resolution is **off**:

* If `user` is not in the scope of values, Jael will just substitute it with `null`.
* If `user?.name` is `null`, Jael will substitute the expression with `null`.
* If the expression `user?.name?.isNotEmpty` does not evaluate to `true`

  (that is to say, it *can* be `null`!), then the `ul` will simply not be rendered.

Overall, strict resolution should likely be off for most cases, as type checking is not often that important when writing HTML templates.


# Directive: declare

Use a `declare` tag to *create* named variables within a block scope. This is analogous to a variable declaration in Dart.

This Dart code:

```dart
var one = 1, two = 2, three = null;
```

Becomes this Jael:

```markup
<declare one=1 two=2 three>
 // Scoped content...
</declare>
```

Another example (this is actually the test for `declare` functionality):

```markup
<div>
 <declare one=1 two=2 three=3>
   <ul>
    <li>{{one}}</li>
    <li>{{two}}</li>
    <li>{{three}}</li>
   </ul>
   <ul>
    <declare three=4>
      <li>{{one}}</li>
      <li>{{two}}</li>
      <li>{{three}}</li>
    </declare>
   </ul>
 </declare>
</div>
```

Which yields:

```markup
<div>
  <ul>
    <li>
      1
    </li>
    <li>
      2
    </li>
    <li>
      3
    </li>
  </ul>
  <ul>
    <li>
      1
    </li>
    <li>
      2
    </li>
    <li>
      4
    </li>
  </ul>
</div>
```


# Directive: for-each

To render content for each member of an `Iterable`, use the `for-each` directive:

```markup
<ul>
  <li for-each=artists as="artist">
    <a href="/artist/" + artist.id>
      {{ artist.name }}
    </a>
  </li>
</ul>
```

Use an `as` attribute to specify the name each member of the iterable will be scoped as. If it is not provided, it defaults to `item`:

```markup
<ul>
  <li for-each=[1, 2, 3]>
    {{ item }} takes {{ item.bitLength }} bit(s) to store.
  </li>
</ul>
```


# Directive: extend

Jael supports template inheritance by means of `extend` and `block`.

Note the following example:

```markup
<!-- layout.jl -->
<html>
    <head>
        <title>{{ title }} - My App</title>
    </head>
    <body>
        <block name="content"></block>
        <div class="footer">
          <!-- Footer content... -->
        </div>
    </body>
</html>

<!-- hello.jl -->
<extend src="layout.jl">
  <block name="content">
    <img src=user.avatar ?? "http://example.com/img/default-avatar">
    Hello, {{ user.name }}!
  </block>
</extend>
```

To extend a layout, instead of the file containing an `<html>` node, create a file with an `<extend>` node. The `src` attribute should point to the correct file. Then, add `<block>` tags that will replace the corresponding `<block>` tags declared in the parent file.


# Directive: if

Similar to `*ngIf` in Angular, Jael supports a simple `if` directive. Use `if` to only an element if a certain condition is `true`:

```markup
<i if=user.locale == 'en'>
  Hello, {{ user.name }}!
</i>
<i if=user.locale == 'jp'>
  こんにちは, {{ user.name }}!
</i>
```


# Directive: include

Use an `include` tag to copy in the contents of another template into the current one. The path, specified with a `src` attribute, will be resolved relative to the path of the current file.

This set-up:

```markup
<!-- components/todo.jl -->
<div class="list-item">
  <div class="title">{{ todo.title }}</div>
</div>

<!-- todo_list.jl -->
<div class="list">
  <div for-each=todos as="todo">
    <include src="components/todo.jl" />
  </div>
</div>
```

Will be renderered as:

```markup
<div class="list">
  <div>
    <div class="list-item">
      <div class="title">Clean your room</div>
    </div>
  </div>
  <div>
    <div class="list-item">
      <div class="title">Do the dishes</div>
    </div>
  </div>
</div>
```


# Directive: switch

Jael's `switch` directive is similar to a Dart `switch` statement. It takes a `value` as input, and evaluates an infinite number of `case` tags, only evaluating the first whose value matches the one in question. A `default` tag can be provided as a fallback.

```markup
<switch value=account.isDisabled>
  <case value=true>
    Good riddance!
  </case>
  <case value=false>
    You are in good standing.
  </case>
  <default>
    Weird...
  </default>
</switch>
```


# Advanced


# Writing a Plugin

[Guidelines](/1.x/advanced/writing-a-plugin#guidelines)

Writing a [plug-in](https://github.com/angel-dart/gitbook/tree/b6d2c930acc83e9dbcb3f5f9248e250fe180c2b0/the-basics/using-plug-ins/README.md) is easy. You can provide plug-ins as either functions, or classes:

```dart
AngelConfigurer awesomeify() => (Angel app) async {
  app.before.add((req, res) async {
    req.write('This request was intercepted by an awesome plug-in.');
    return false;
  });
}

class MyAwesomePlugin extends AngelPlugin {
  @override
  Future call(Angel app) async {
    app.responseFinalizers.add((req, res) async {
      res.headers['Be-Awesome'] = 'All the time';
    });
  }
}
```

## Guidelines

* Plugins should only do one thing, or serve one purpose.
* Functions are preferred to classes.
* Always need to be well-documented and thoroughly tested.
* Make sure no other plugin already serves the purpose.
* Use the provided Angel API's whenever possible. This will help your plugin resist breaking change in the future.
* Try to get it [added to main organization](https://github.com/angel-dart/roadmap/blob/master/CONTRIBUTING.md).
* Plugins should generally be small.
* Plugins should *NEVER* modify app configuration!!!
  * i.e. Do *NOT* set `app.lazyParseBodies`, `app.storeOriginalBuffer`, etc.
* Stay away from `req.io` and `res.io` if possible. Using these will doom your plugin to a life of only working on HTTP servers. Future versions of Angel may be server-agnostic, and this will keep your plugin firmly lodged in the past.
* If your plugin is development-only or production-only, it should automatically configure itself. Prefer [`app.isProduction`](https://www.dartdocs.org/documentation/angel_framework/latest/angel_framework/Angel/isProduction.html) to manually checking the environment for `ANGEL_ENV`.
* Use `req.lazyBody()`, `req.lazyFiles()`, etc. if you are running in an `async` context. Otherwise, your plugin may crash applications that lazy-parse request bodies.
* If you use `req.lazyQuery()`, refrain from using `forceParse`. Never force any additional side effects on the user.

Finally, your plugin should expose common options in a simple way. For example, the (deprecated) [compress](https://github.com/angel-dart/compress) plugin has a shortcut function, `gzip`, to set up GZIP compression, whereas for any other codec, you would manually have to specify additional options.

```dart
main() {
  var app = new Angel();

  // Calling gzip()
  app.responseFinalizers.add(gzip());

  // Easier than:
  app.responseFinalizers.add(compress('gzip', GZIP));
}
```


# Introduction

[![The Angel Framework](https://angel-dart.github.io/assets/images/logo.png)](https://angel-dart.github.io)

[![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg)](https://gitter.im/angel_dart/discussion) [![Pub](https://img.shields.io/pub/v/angel_framework.svg)](https://pub.dartlang.org/packages/angel_framework) [![Build status](https://travis-ci.org/angel-dart/framework.svg?branch=master)](https://travis-ci.org/angel-dart/framework) ![License](https://img.shields.io/github/license/angel-dart/framework.svg)

This is the documentation for [Angel](https://angel-dart.dev), a backend framework in the Dart language. This website consists of multiple guides and pages about features within the framework, as well as external links to YouTube videos, Pub packages, and Github repositories providing supplemental information.

New to Angel? Read the getting started guide, and you'll be well on your way:

<https://docs.angel-dart.dev/v/2.x/guides/getting-started>


# Migration from Angel 1.1.x


# Rationale - Why a new Version?

TODO


# 2.0.0 Migration Guide

Based on [this discussion](https://github.com/angel-dart/angel/issues/49).

Based on the changelog, up to `1.1.0`: <https://pub.dartlang.org/packages/angel_framework/versions/1.1.1#-changelog-tab->

## Main Points

* `angel_diagnostics` is deprecated - instead just pass a `Logger` and set it as `app.logger`.
* Removed `AngelFatalError`, and subsequently `fatalErrorStream`.
  * Errors are automatically create `500`. Set `app.logger` to see output.
  * `angel_errors` is no longer useful.
* Removed all `@deprecated` members.
* Removed @Hooked, beforeProcessed, and afterProcessed.
* Made injections in RequestContext private.
* Renamed properties in AngelBase to configuration.
* Added support for pattern matching and other injections via `@Parameter()`
* Officially deprecated properties in Angel.
* Fixed a bug where cached routes would not heed the request method. #173
* Reworked error handling logic; now, errors will not automatically default to sending JSON.
* Removed the onController stream from Angel.
* Controllers now longer use call, which has now been renamed to configureServer.

### Notes

Aside from these points, there are several things to note.

Migration in itself will be pretty easy to achieve. Plugins and services haven't really changed, it's just the HTTP server itself.

## What should I use instead of `X`?

In 1.1.0, the following were completely removed:

* `Angel.after`,
* `Angel.before`
* `Angel.justBeforeStart`
* `Angel.justBeforeStop`
* `Angel.fatalErrorStream`
  * There is no replacement for `before`/`after`. This way, it is easier to keep track of the order request handlers run. responseFinalizers are still in place.
  * `justBeforeStart`, `justBeforeStop` => `startupHooks`, `shutdownHooks`
  * `fatalErrorStream` is no longer necessary; you can just set `app.errorHandler`. Fatal errors will be wrapped in a 500 response.

## How should I define global middleware?

`app.use((req, res) => ...)`

Much cleaner in `1.1.0`. 😄


# ORM


# About

Angel, like many other Web server frameworks, features support for object-relational mapping, or *ORM*. ORM tools allow for conversion from database results to Dart classes.

Angel's ORM uses Dart's `build` system to generate query builder classes from your `Model` classes, and takes advantage of Dart's strong typing to prevent errors at runtime.

Take, for example, the following class:

```dart
@orm
abstract class _Pokemon extends Model {
    String get nickName;

    int get level;

    int get experiencePoints;

    @belongsTo
    PokemonTrainer get trainer;

    @belongsTo
    PokemonSpecies get species;

    @belongsTo
    PokemonAttack get attack0;

    @belongsTo
    PokemonAttack get attack2;

    @belongsTo
    PokemonAttack get attack3;

    @belongsTo
    PokemonAttack get attack4;
}
```

`package:angel_orm_generator` will generate code that lets you do the following:

```dart
app.get('/trainer/int:id/first_moves', (req, res) async {
    var id = req.params['id'] as int;
    var executor = req.container.make<QueryExecutor>();
    var trainer = await findTrainer(id);
    var query = PokemonQuery()..where.trainerId.equals(id);
    var pokemon = await query.get(executor);
    return pokemon.map((p) => p.attack0.name).toList();
});
```

This section of the Angel documentation consists mostly of guides, rather than technical documentation.

For more in-depth documentation, see the actual `angel_orm` project on Github:

<https://github.com/angel-dart/orm>


# Basic Functionality

Before starting with the ORM, it is highly recommended to familiar one's self with `package:angel_serialize`, as it is the foundation for `package:angel_orm`:

<https://github.com/angel-dart/serialize>

To enable the ORM for a given model, simply add the `@orm` annotation to its definition:

```dart
@orm
@serializable
abstract class _Todo {
    bool get isComplete;

    String get text;

    @Column(type: ColumnType.long)
    int get score;
}
```

The generator will produce a `TodoQuery` class, which contains fields corresponding to each field declared in `_Todo`. Each of `TodoQuery`'s fields is a subclass of `SqlExpressionBuilder`, corresponding to the given type. For example, `TodoQuery` would look *something* like:

```dart
class TodoQuery extends Query<Todo, TodoQueryWhere> {
    BooleanSqlExpressionBuilder get isComplete;

    StringSqlExpressionBuilder get text;

    NumericSqlExpressionBuilder<int> get score;
}
```

Thus, you can query the database using plain-old-Dart-objects (*PODO's*):

```dart
Future<List<Todo>> leftToDo(QueryExecutor executor) async {
    var query = TodoQuery()..where.isComplete.isFalse;
    return await query.get(executor);
}

Future<void> markAsComplete(Todo todo, QueryExecutor executor) async {
    var query = TodoQuery()
        ..where.id.equals(todo.idAsInt)
        ..values.isComplete = true;

    await query.updateOne(executor);
}
```

The glue holding everything together is the `QueryExecutor` interface. To support the ORM for any arbitrary database, simply extend the class and implement its abstract methods.

Consumers of a `QueryExecutor` typically inject it into the app's [dependency injection](https://github.com/angel-dart/gitbook/tree/e9d526478e563b918b4172f7cee31471132f4321/dependency-injection.md) container:

```dart
app.container.registerSingleton<QueryExecutor>(PostgresExecutor(...));
```

*At the time of this writing*, there is only support for PostgreSQL, though more databases may be added eventually.


# Relations

Relational modeling is one of the most commonly-used features of sql databases - after all, it *is* the namesake of the term "relational database."

Angel supports the following kinds of relations by means of annotations on fields:

* `@hasOne` (one-to-one)
* `@hasMany` (one-to-many)
* `@belongsTo` (one-to-one)
* `@manyToMany` (many-to-many)

By default, the keys for columns are inferred automatically. In the following case:

```dart
@orm
@serializable
abstract class _Wheel extends Model {
  @belongsTo
  Car get car;
}
```

The local key defaults to `car_id`, and the foreign key defaults to `id`. You can manually override these:

```dart
@BelongsTo(localKey: 'carId', foreignKey: 'licenseNumber')
Car get car;
```

The ORM computes relationships by performing `JOIN`s, so that even complex relationships can be fetched using just one query, rather than multiple.

## Many-to-many Relationships

A very common situation that occurs when using relational databases is where two tables may be bound to multiple copies of each other. For example, in a school database, each student could be registered to multiple classes, and each class could have multiple students taking it.

This is typically handled by creating a third table, which joins the two together. In the Angel ORM, this is relatively straightforward:

```dart
@orm
@serializable
abstract class _Class extends Model {
  String get courseName;

  @ManyToMany(_Enrollment)
  List<_Student> get students;
}

@orm
@serializable
abstract class _Student extends Model  {
  String get name;
  int get year;

  @ManyToMany(_Enrollment)
  List<_Class> get classes;
}

@orm
@serializable
abstract class _Enrollment {
    @belongsTo
    _Student get student;

    @belongsTo
    _Class get class_;
}
```




---

[Next Page](/llms-full.txt/1)

