# README

[![Angel3 Framework](https://2900905803-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fl1R0hxZkV8Vsgv2bppWi%2Fuploads%2Fgit-blob-1da098e94fcbea11c6d0b1cc1d07da8d4c5309b9%2Fangel3_logo.png?alt=media)](https://github.com/dart-backend/angel)

![Pub Version (including pre-releases)](https://img.shields.io/pub/v/angel3_framework?include_prereleases) [![Null Safety](https://img.shields.io/badge/null-safety-brightgreen)](https://dart.dev/null-safety) [![Discord](https://img.shields.io/discord/1060322353214660698)](https://discord.gg/3X6bxTUdCM) [![License](https://img.shields.io/github/license/dart-backend/angel)](https://github.com/dart-backend/angel/blob/master/LICENSE)

This is the documentation site for [Angel3](https://github.com/dart-backend/angel), a Dart backend framework. It contains tutorials and development guides, as well as links to the packages of the Angel3 framework. It covers Angel3 10.0.0, which requires Dart SDK 3.13 or later.

New to Angel3? Read the getting started [Tutorial](https://angel3-docs.dukefirehawk.com/tutorial/getting-started), and you'll be well on your way.


# Foreword

Angel3 is a fork of archived Angel framework migrated to support null-safety, which started with Dart SDK 2.12.x. Angel3 10.x requires Dart SDK 3.13 or later. It is a full-stack Web framework in Dart that aims to streamline development by providing many common features out-of-the-box in a consistent manner. One of the main goal is to enable developers to build both frontend and backend in the same language, Dart. Angel3 framework is designed as a collections of plugins that enable developers to pick and choose the parts needed for their projects. A series of starter templates are also provided for quick start and trial run with Angel3 framework.


# Tutorial


# Getting Started

In this first tutorial, we will:

* Download the `angel3_framework` package from `pub.dev`.
* Launch `Angel3` as backend server.
* Add some basic routing.
* Add a 404 error handler.

The source code for this example can be found at: <https://github.com/dart-backend/belatuk-examples/tree/master/docs_examples/getting_started>

## Prerequisite

* This tutorial uses command line interface. If you are not well-versed working with it, just copy/paste the code snippets while going through this tutorial.
* The Dart SDK version 3.13 or later is required. Please follow the instructions on the [official dart site](https://dart.dev/get-dart) to download and install it.
* The [`curl`](https://curl.haxx.se/download.html) tool will be used to send requests to the backend server.
* Note that some steps will mention Unix-specific programs, like `vim`. 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
environment:
    sdk: ^3.13.0
dependencies:
    angel3_framework: ^10.0.0
```

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

```bash
Resolving dependencies...
Downloading packages...
+ angel3_container 10.0.0
+ angel3_framework 10.0.1
+ angel3_http_exception 10.0.0
(... more output omitted)
Changed 38 dependencies!
```

## Launching the Backend Server

`Angel3` 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:

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

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

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

void void 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`. It prints a message that no `reflector` was passed to the `Angel` constructor: this tutorial does not need one, as the [Dependency Injection](/under-the-hood/dependency-injection#enabling-dart-mirrors-or-other-reflection) guide explains. 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 see a `404 Not Found` error, as JSON:

```bash
{"is_error":true,"status_code":404,"message":"404 Not Found","errors":[]}
```

The server has no routes yet, but the fact that it *answered* means that it 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 add 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:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';

void 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`, `get`, `post`, `put`, `patch`, `delete`, `head`) 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 see the `404 Not Found` error again, because there is no route mounted corresponding to the path `'/foo'`. (A browser, which asks for HTML, gets a `404 Not Found` page instead of JSON.)

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:

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

`Angel3` 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.');
```

Angel3 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 Angel3 backend 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 `angel3_*` packages on the [Pub.dev](https://pub.dev) site, and read the documentation found in their respective `README` files.

Don't forget that for discussion and support, you can either file a Github issue, or join the [Discord server](https://discord.gg/3X6bxTUdCM).


# Minimal Setup

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

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

```yaml
environment:
    sdk: ^3.13.0
dependencies:
    angel3_framework: ^10.0.0
```

You might also want to install packages such as `angel3_static`, `angel3_cache`, `angel3_jael`, and `angel3_cors`.

Next, run `dart 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 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';

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

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

  await http.startServer('localhost', 3000);
  print('Angel3 server listening at ${http.uri}');
}
```

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

* `var app = Angel()` - The base Angel3 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 Angel3 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](/under-the-hood/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](/under-the-hood/basic-routing) 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:

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

The app uses no `dart:mirrors`, so it can also be compiled to a native executable:

```bash
dart compile exe bin/main.dart -o hello_angel
./hello_angel
```


# Application Setup

The [Getting Started](/tutorial/getting-started) tutorial built a server from scratch. A real application also needs configuration, views, static files, logging and a production server. The starter templates set these up for you.

## Prerequisite

* The Dart SDK version 3.13 or later. Follow the instructions on the [official dart site](https://dart.dev/get-dart) to download and install it.
* The [Angel3 CLI](/command-line-interface/cli-setup):

  ```bash
  dart pub global activate angel3_cli
  ```

## Creating a project

Run:

```bash
angel3 init hello
```

and choose a template:

| Template              | Description                                                                                                                                                |
| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Basic                 | A basic web application with Jael views and static files                                                                                                   |
| ORM for PostgreSQL    | The basic application, with the Angel3 ORM and migrations on PostgreSQL                                                                                    |
| ORM for MySQL/MariaDB | The basic application, with the Angel3 ORM and migrations on MySQL or MariaDB                                                                              |
| GraphQL               | A to-do list served over GraphQL, stored in PostgreSQL with the Angel3 ORM                                                                                 |
| MongoDB               | The basic application, with a REST API of a MongoDB collection (`angel3_mongo`)                                                                            |
| RethinkDB             | The basic application, with a REST and WebSocket API of a RethinkDB table, which pushes its changefeed to clients (`angel3_rethinkdb`, `angel3_websocket`) |
| Sembast               | The basic application, with a REST API of a store in Sembast, a database in one file that needs no server (`angel3_sembast`)                               |
| Kelicap               | A full-stack application: an Angel3 REST API and a [Kelicap](/templates-and-views/kelicap) web client                                                      |

For this tutorial, choose `Basic`. `angel3 init` copies the template into `hello`, names the package `hello`, generates new JWT secrets in `config/`, and runs `dart pub get`.

Instead of the CLI, you can also clone a template from the [boilerplates](https://github.com/dart-backend/boilerplates) repository, under `templates/`. Run `dart pub get` in it, and replace the `jwt_secret` values in `config/` before deploying.

## Running the server

From the project's root, start the server in development mode:

```bash
cd hello
dart --observe bin/dev.dart
```

Open <http://localhost:3000>, and you'll see the template's home page. The `--observe` flag enables hot reloading: change a file under `lib/` or `config/`, and the server reloads it without restarting.

Each template's `README.md` describes how to set up its database, if it has one.

## Next Up

Continue to [Project Layout](/tutorial/project-layout) to see what each file of the project does.


# Project Layout

A project created from the `Basic` template looks like this:

```bash
hello
├── bin
│   ├── dev.dart          # Development server, with hot reloading
│   └── prod.dart         # Production server
├── config
│   ├── default.yaml      # Configuration of every environment
│   ├── development.yaml  # Overrides for development
│   └── production.yaml   # Overrides for production
├── lib
│   ├── hello.dart        # configureServer: sets up the app
│   └── src
│       ├── config
│       │   ├── config.dart          # Loads configuration and the view engine
│       │   └── plugins
│       │       └── plugins.dart     # Your own plug-ins
│       ├── routes
│       │   ├── routes.dart          # Routes, static files and error handling
│       │   └── controllers
│       │       └── controllers.dart # Controllers
│       └── services
│           └── services.dart        # Services
├── test
│   └── all_test.dart     # Tests, with angel3_test
├── views                 # Jael templates
│   ├── error.jael
│   ├── hello.jael
│   └── layout.jael
├── web                   # Static files: stylesheets, images
├── Containerfile         # Container image, for Podman
├── contrib/deployment    # Podman Compose file
└── pubspec.yaml
```

## Entry points

`bin/dev.dart` and `bin/prod.dart` both create an `Angel` app, and configure it with the `configureServer` function of `lib/hello.dart`:

* `bin/dev.dart` runs it with a `HotReloader` of [`angel3_hot`](https://github.com/dart-backend/angel/tree/master/packages/hot), which reloads the app when the files of `lib/` or `config/` change. Run it with `dart --observe bin/dev.dart`.
* `bin/prod.dart` runs it with the `Runner` of [`angel3_production`](https://github.com/dart-backend/angel/tree/master/packages/production), which can run several isolates, and re-spawns crashed ones. See [Deploy to Production](/tutorial/deploy-production).

## Configuring the app

`lib/hello.dart` applies three plug-ins in order:

```dart
Future configureServer(Angel app) async {
  var fs = const LocalFileSystem();

  await app.configure(configuration.configureServer(fs));
  await app.configure(services.configureServer);
  await app.configure(routes.configureServer(fs));
}
```

A plug-in is a function that takes the `Angel` app, and adds to it. See [Using Plug-ins](/extensions-and-plugins/using-plug-ins).

* **`src/config/config.dart`** loads the files of `config/` with [`angel3_configuration`](https://github.com/dart-backend/angel/tree/master/packages/configuration), sets up Jael for `views/`, and applies the plug-ins of `src/config/plugins/plugins.dart`, where your own go.
* **`src/services/services.dart`** mounts [services](/under-the-hood/service-basics), with `app.use`.
* **`src/routes/routes.dart`** mounts the [controllers](/under-the-hood/controllers) of `controllers/controllers.dart`, adds routes, serves the files of `web/`, and renders an error page for errors in HTML requests.

## Configuration

`config/default.yaml` holds the configuration of every environment. The `ANGEL_ENV` environment variable selects the environment: `development` unless it is set, or `production`. The file of the environment, such as `config/production.yaml`, is loaded over the default one, and overrides its values. A `config/.env` file, if present, sets environment variables first.

The configuration is a `Map`, as `app.configuration`:

```dart
var port = app.configuration['port'] as int? ?? 3000;
```

## Next Up

Continue to [Templates and Views](/tutorial/templates-views) to render pages of your own.


# Templates and Views

The `Basic` template renders HTML pages with [Jael](/templates-and-views/jael3/about), a template engine built for Angel3. Its templates are in `views/`.

## Rendering a view

`res.render` renders a template of `views/`, and sends it as HTML. The template's home page route, in `lib/src/routes/routes.dart`, is:

```dart
app.get('/', (req, res) => res.render('hello'));
```

`'hello'` is `views/hello.jael`:

```html
<extend src="layout.jael">
    <block name="content">
        <div class="title">Angel</div>
    </block>
</extend>
```

It [extends](/templates-and-views/jael3/directive-extend) `views/layout.jael`, which holds the page's `<html>`, `<head>` and stylesheet, and fills its `content` block. Every page of the app can share the layout this way.

## Passing data to a view

Pass a `Map` to `res.render`, and use its values in the template between `{{ }}`. Add this route to `routes.dart`, before the `app.fallback` calls:

```dart
app.get('/greet/:name', (req, res) {
  return res.render('greet', {
    'title': 'Greeting',
    'name': req.params['name'],
  });
});
```

and create `views/greet.jael`:

```html
<extend src="layout.jael">
    <block name="content">
        <div class="title">Hello, {{ name }}!</div>
    </block>
</extend>
```

Open <http://localhost:3000/greet/Bob>, and you'll see `Hello, Bob!`. The layout's `<title>` is `{{ title ?? 'Angel' }}`, so this page's title is `Greeting`.

`{{ }}` escapes HTML, so a value from the request cannot inject markup into the page. Use `{{- }}` only for HTML you trust.

Jael also has [conditionals](/templates-and-views/jael3/directive-if), [loops](/templates-and-views/jael3/directive-for-each), [includes](/templates-and-views/jael3/directive-include) and [custom elements](/templates-and-views/jael3/custom-elements).

To pass an object of your own, rather than a `Map`, Jael reads its fields by name, which needs reflection: mark its class `@injectable`, and generate its reflection data, as [Running without `dart:mirrors`](/under-the-hood/running-without-mirrors) describes. Or pass `toJson()` of the object.

## Static files

The files of `web/`, such as `web/css/site.css`, are served at the root of the site, as `/css/site.css`, by a `CachingVirtualDirectory` of [`angel3_static`](https://github.com/dart-backend/angel/tree/master/packages/static). In production, it also sends caching headers.

## Error pages

When a request that accepts HTML fails, the template renders `views/error.jael` with the error's message. Other requests, such as those of an API, get the error as JSON.

## Other template engines

Jael is not the only choice. See [Server Side Rendered Views](/templates-and-views/rendering-views) for Mustache, Jinja and Markdown, and [Full-stack with Kelicap](/templates-and-views/kelicap) for a client-side web app.

## Next Up

Continue to [Configure ORM](/tutorial/configure-orm) to store data in a database.


# Configure ORM

The [Angel3 ORM](/databases/object-relational-mapping-orm/about) stores your models in PostgreSQL, MySQL or MariaDB, with queries generated from the model classes. This tutorial uses the `ORM for PostgreSQL` template, which is the `Basic` template with the ORM set up.

## Creating the project

```bash
angel3 init hello_orm
```

and choose `ORM for PostgreSQL`. The template includes a `Greeting` model, in `lib/src/models/greeting.dart`, with a `message`, and `GET` and `POST` routes for `/greetings`.

## Setting up the database

1. Install PostgreSQL 16 or later.
2. Create a user, and a database that it owns, with `psql`:

   ```sql
   postgres=# create user appuser with encrypted password 'App1970#';
   postgres=# create database appdb owner appuser;
   ```

   The user must own the database to create the tables of the migrations: since PostgreSQL 15, only the owner of a database can create tables in its `public` schema.
3. Set them in the `postgres` section of `config/default.yaml`:

   ```yaml
   postgres:
     host: localhost
     port: 5432
     database_name: appdb
     username: appuser
     password: App1970#
     use_ssl: false
     time_zone: UTC
   ```

   The `POSTGRES_HOST`, `POSTGRES_USERNAME` and `POSTGRES_PASSWORD` environment variables, if set, override `host`, `username` and `password`, so they need not be kept in a file.
4. Create the tables, with the migrations:

   ```bash
   dart bin/migrate.dart up
   ```

   This creates the `greetings` table, and a `migrations` table that records which migrations have run. `rollback` undoes the last batch, `reset` undoes all of them, and `refresh` resets and runs them again. See [Migrations](/databases/object-relational-mapping-orm/migrations).

## Trying it out

Start the server with `dart --observe bin/dev.dart`, and add a greeting:

```bash
curl -H "Content-Type: application/json" -X POST -d '{"message":"Hello"}' http://localhost:3000/greetings
```

Then list them:

```bash
curl http://localhost:3000/greetings
```

## How it fits together

* **`lib/src/config/plugins/orm.dart`** connects to PostgreSQL with the configuration, and registers a `PostgreSqlExecutor` in the app's container as the `QueryExecutor`. See [PostgreSQL](/databases/object-relational-mapping-orm/postgresql).
* **`bin/migrate.dart`** runs the migrations with a `PostgresMigrationRunner`.
* **`lib/src/routes/routes.dart`** reads the `QueryExecutor` from the container, and queries the greetings with `GreetingQuery`:

  ```dart
  app.get('/greetings', (req, res) {
    var executor = req.container!.make<QueryExecutor>();
    return GreetingQuery().get(executor);
  });
  ```

## Adding a model

1. Create the model, such as `lib/src/models/todo.dart`. Its class name ends with `Entity`, and the generated class takes the name without it:

   ```dart
   import 'package:angel3_migration/angel3_migration.dart';
   import 'package:angel3_orm/angel3_orm.dart';
   import 'package:angel3_serialize/angel3_serialize.dart';
   import 'package:optional/optional.dart';

   part 'todo.g.dart';

   @serializable
   @orm
   abstract class TodoEntity extends Model {
     String? get text;

     bool? get completed;
   }
   ```

   Export it from `lib/models.dart`.
2. Generate its code:

   ```bash
   dart run build_runner build --delete-conflicting-outputs
   ```

   This generates `Todo`, its serializer, `TodoQuery`, and `TodoMigration`. See [Serialization](/under-the-hood/serialization) and [Basic Functionality](/databases/object-relational-mapping-orm/basic-functionality).
3. Add `TodoMigration()` to the `migrations` of `bin/migrate.dart`, and run `dart bin/migrate.dart up`.
4. Query it in your routes or services:

   ```dart
   var query = TodoQuery()..where!.completed.isFalse;
   List<Todo> todos = await query.get(executor);
   ```

   [`angel3_orm_service`](https://github.com/dart-backend/angel/tree/master/packages/orm/orm_service) can also serve a model as a REST [service](/under-the-hood/service-basics).

For MySQL or MariaDB, choose the `ORM for MySQL/MariaDB` template instead, whose `README.md` describes its setup.

## Next Up

Continue to [Deploy to Production](/tutorial/deploy-production).


# Deploy to Production

## Before deploying

Check the `jwt_secret` in `config/default.yaml` and `config/production.yaml`: it signs the app's tokens. `angel3 init` generates new ones for a new project. If one is still `INSECURE_DEFAULT_SECRET`, as in a template cloned by hand, generate new ones with:

```bash
angel3 key
```

Keep the secrets out of public repositories, as anyone who knows one can sign tokens the app accepts.

Set `ANGEL_ENV=production` wherever the server runs. In [production mode](/deployment/production-mode), the app loads `config/production.yaml`, flattens its route tree and caches resolved routes, and its static files are sent with caching headers.

## Running the production server

```bash
ANGEL_ENV=production dart bin/prod.dart
```

`bin/prod.dart` runs the app with the `Runner` of [`angel3_production`](https://github.com/dart-backend/angel/tree/master/packages/production). Its options include:

| Option                | Description                                                             |
| --------------------- | ----------------------------------------------------------------------- |
| `-a`, `--address`     | The address to listen on                                                |
| `-p`, `--port`        | The port to listen on                                                   |
| `-j`, `--concurrency` | The number of isolates to spawn                                         |
| `--[no-]respawn`      | Re-spawn crashed isolates, on by default                                |
| `--ssl`, `--http2`    | Listen for HTTPS, or HTTP/2, with `--certificate-file` and `--key-file` |

`dart bin/prod.dart --help` lists all of them. See [Running in Isolates](/deployment/running-in-isolates).

## Compiling to a native executable

The templates run without `dart:mirrors`, so the server can be compiled into a native executable, which starts faster, and needs no Dart SDK to run:

```bash
dart compile exe bin/prod.dart -o server
ANGEL_ENV=production ./server -p 3000
```

Run it from the project directory, as the server reads `config/`, `views/` and `web/` from there. To deploy the executable, copy those directories with it.

If your app uses controllers with `@Expose`, or other features that need reflection, see [Running without `dart:mirrors`](/under-the-hood/running-without-mirrors).

## Running in a container

Each template has a `Containerfile`, which builds the native executable into a minimal image:

```bash
podman build -t hello .
podman run --rm -p 3000:3000 hello
```

See [Running in a Container with Podman](/deployment/podman), which also covers Podman Compose.

## Behind a reverse proxy

On a server of your own, run the app as an unprivileged user, keep it running with systemd, and put nginx in front of it, to terminate TLS and serve static files. The CLI generates both configurations:

```bash
angel3 deploy systemd -o hello.service
angel3 deploy nginx -o hello.conf
```

See [Deploying under nginx](/deployment/ubuntu-and-nginx) and [Configuring SSL](/deployment/configuring-ssl).

## Next Up

Congratulations, you've built and deployed an Angel3 application! Read the guides under "Under the hood" to learn more about each part of the framework.


# Command Line Interface


# Setup

Installing `angel3_cli` installs a command line dart application in your local environment. Executed from the terminal, it provides access to a set of useful commands for working with [Angel3](https://pub.dev/packages/angel3_framework). The `--help` option gives more information about the available options.

## Installation

* Prerequisite: [Dart SDK](https://dart.dev/get-dart) must be installed
* Open a terminal screen and run the following command.

  ```bash
    dart pub global activate angel3_cli
  ```

### Creating a New Project

* Creating a new project, `hello`, in the current directory, run:

  ```bash
    angel3 init hello
  ```
* Initializing a project within a directory, `hello`, run:

  ```bash
    angel3 init
  ```
* Follows the instructions given to complete setting up the new project. Choose from one of the available [Angel3 templates](https://github.com/dart-backend/boilerplates) to best represents what you would like your backend server to do. A well structured project will be generated and ready for development.

### Starting Backend Server

* Running the server in development mode:

  ```bash
    # Use the `--observe` flag to enable hot reloading in Angel3.
    dart --observe bin/dev.dart
  ```
* Running the server in production mode:

  ```bash
    dart bin/prod.dart
  ```


# Commands

Run these from the root of your project. To install the CLI, see [Setup](/command-line-interface/cli-setup).

| Command                  | Description                                                                                                                                   |
| ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `angel3 init [<folder>]` | Creates a project from a [starter template](/tutorial/application-setup)                                                                      |
| `angel3 make controller` | Generates a controller class (`-w` for a WebSocket controller)                                                                                |
| `angel3 make service`    | Generates a service                                                                                                                           |
| `angel3 make model`      | Generates a model class, serializable and with a migration by default (`--no-serializable`, `--no-migration`), and with ORM code with `--orm` |
| `angel3 make migration`  | Generates a migration class                                                                                                                   |
| `angel3 make plugin`     | Generates a plug-in                                                                                                                           |
| `angel3 make test`       | Generates a test                                                                                                                              |
| `angel3 deploy nginx`    | Generates an NGINX configuration for a reverse proxy and static server                                                                        |
| `angel3 deploy systemd`  | Generates a systemd service that keeps your server running                                                                                    |
| `angel3 key`             | Generates new JWT secrets in `config/default.yaml` and `config/production.yaml`                                                               |
| `angel3 doctor`          | Checks that your system has what Angel3 needs                                                                                                 |

For the options of a command:

```bash
angel3 help
angel3 help make model
```

## `angel3 init`

`angel3 init` asks for a template, then:

1. downloads the templates from the [boilerplates](https://github.com/dart-backend/boilerplates) repository, and caches them in `~/.angel3/boilerplates` for a day
2. copies the chosen template into the folder, and names the package after it
3. generates new JWT secrets in `config/default.yaml` and `config/production.yaml`
4. runs `dart pub get`, and `dart run build_runner build` for the templates that need code generation

| Option                 | Description                                                       |
| ---------------------- | ----------------------------------------------------------------- |
| `-n`, `--project-name` | The name of the project, instead of the folder's                  |
| `--refresh`            | Download the latest templates, even if the cached ones are recent |
| `--offline`            | Use the cached templates only, and skip `dart pub get`            |
| `--no-pub-get`         | Skip `dart pub get` and code generation                           |

If the download fails, `angel3 init` uses the cached templates when there are any.

## Deployment helpers

`angel3 deploy` writes its configuration to the standard output, or to a file with `-o`:

```bash
angel3 deploy nginx -o my_app.conf
angel3 deploy systemd -o my_app.service
```

Review the generated files, then install them, as [Deploying under nginx](/deployment/ubuntu-and-nginx) describes.


# Templates and Views


# Server Side Rendered Views

* [Rendering Views](#rendering-views)
  * [Example](#example)
  * [`ViewGenerator` typedef](#viewgenerator)

## Rendering Views

Just like `res.render` in Express, Angel3'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/dart-backend/angel/tree/master/packages/mustache>

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

Angel support for Jael is provided through [`package:angel3_jael`](https://github.com/dart-backend/angel/tree/master/packages/jael/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://github.com/dart-backend/angel/tree/master/packages/jinja>

### Example

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

With Jael, for example:

```dart
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_jael/angel3_jael.dart';
import 'package:file/local.dart';

Future<void> configureServer(Angel app) async {
  var fileSystem = const LocalFileSystem();
  await app.configure(jael(fileSystem.directory('views')));
}
```

### ViewGenerator

Angel3 declares the following typedef:

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

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

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

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

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


# JAEL3


# About

**Jael3** 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 [Angel3](https://github.com/dart-backend/angel) 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

```html
<!-- 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:jael3`
* `package:jael3_preprocessor`

However, [Angel3](https://github.com/dart-backend/angel) users only need install `package:angel3_jael` to include templating in their server-side applications. One of Angel3'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.

```yaml
dependencies:
  angel3_jael: ^10.0.0
```

## Members of Values

Since 10.0.0, Jael does not use `dart:mirrors`, so an app that renders templates can be compiled with `dart compile exe`. In a template, `{{ user.name }}` reads `name` from a `Map`, a common member of a core type, or a key of the value's `toJson()`, such as that of a model generated by `angel3_serialize`. With `angel3_jael`, members of your own classes are also read through the app's reflector: `MirrorsReflector` on the Dart VM, or, in an app compiled with `dart compile exe`, a `StaticReflector` of classes marked `@injectable`. See [Enabling `dart:mirrors` or other Reflection](/under-the-hood/dependency-injection#enabling-dart-mirrors-or-other-reflection).


# Basics

* [Basic](#basic)
  * [Interpolation](#interpolation)
  * [Attributes](#attributes)
    * [Attribute Values](#attribute-values)
    * [Quoted Attribute Names](#quoted-attribute-names)
    * [Unescaped Attributes](#unescaped-attributes)

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

```html
<!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 (`{{- }}`).

```html
<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:

```html
<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:

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

### Unescaped Attributes

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

```html
<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:

```html
<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 [include](/templates-and-views/jael3/directive-include) tag:

```html
<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:

```html
<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 subsequently, 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:angel3_jael` by default disables strict resolution, and `strictResolution` is available as a parameter to both the `jael` function in Angel3, and the `render` method of the `Renderer` class 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:

```html
<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` has no `name` member, or `user` is `null`, Jael will substitute `user.name` with `null`.
* As in Dart, `?.` makes the rest of the chain `null`, so `user?.name?.isNotEmpty` is `null` if `user` is.
* 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:

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

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

```html
<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:

```html
<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:

```html
<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`:

```html
<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:

```html

<!-- 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`:

```html
<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:

```html
<!-- 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:

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

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


# Jinja

[`angel3_jinja`](https://github.com/dart-backend/angel/tree/master/packages/jinja) renders [Jinja](https://jinja.palletsprojects.com/) templates as views, with [jinja.dart](https://github.com/ykmnkmi/jinja.dart), a port of Jinja to Dart by Olzhas Suleimen.

```yaml
dependencies:
  angel3_jinja: ^10.0.0
```

## Usage

Configure the app with `jinja`, and the path of the views directory. `res.render` then renders a template of it:

```dart
import 'dart:io';

import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
import 'package:angel3_jinja/angel3_jinja.dart';
import 'package:path/path.dart' as p;

void main() async {
  var app = Angel();
  var http = AngelHttp(app);
  var viewsDir = p.join(p.dirname(p.fromUri(Platform.script)), 'views');

  // Enable Jinja views
  await app.configure(jinja(path: viewsDir));

  app
    ..get('/', (req, res) => res.render('index.html'))
    ..get('/hello/:name', (req, res) => res.render('hello.html', req.params));

  app.fallback((req, res) => throw AngelHttpException.notFound());

  await http.startServer('127.0.0.1', 3000);
  print('Listening at ${http.uri}');
}
```

## Escaping

Values are not HTML-escaped. Escape every value that is not trusted HTML, such as one from the request, with the `e` (or `escape`) filter:

```html
<p>hello {{ name | e }}!</p>
```

## Views

A view name that resolves outside the views directory (`../secret.html`, an absolute path, a symbolic link out of it), that has none of the extensions in `ext`, or that does not exist, is a 404. In production, templates are kept parsed, so changes to them are seen only after the app restarts; otherwise they are read again on every render.


# SEO

[`angel3_seo`](https://github.com/dart-backend/angel/tree/master/packages/seo) inlines the stylesheets and scripts of HTML pages into the pages themselves, so the browser can show a page without further requests. Pages load faster, which search engines reward.

```yaml
dependencies:
  angel3_seo: ^10.0.0
```

## Inlining rendered pages

`inlineAssets` is a [response finalizer](/under-the-hood/request-lifecycle) that patches any `text/html` response, including those of a template engine such as Jael. The `link` and `script` elements that point to files of the given directory are replaced with the contents of those files:

```dart
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_seo/angel3_seo.dart';
import 'package:file/local.dart';

Future configureServer(Angel app) async {
  var fs = const LocalFileSystem();
  app.responseFinalizers.add(inlineAssets(fs.directory('web')));
}
```

Only internal resources are inlined: URIs without a scheme or host, such as `/site.css` or `foo/bar.js`, of a file in the directory. A path out of it (`../secret`) is never inlined.

## Inlining static pages

`inlineAssetsFromVirtualDirectory` wraps a `VirtualDirectory` of `angel3_static`, so it inlines the `.html` and `.htm` files it serves. The caching of a `CachingVirtualDirectory` still applies to them:

```dart
var vDir = inlineAssetsFromVirtualDirectory(
  CachingVirtualDirectory(app, fs, source: fs.directory('web')),
);

app.fallback(vDir.handleRequest);
```

## What is inlined

* A stylesheet keeps its `media`.
* A script that is `async`, or `defer` but not a module, stays external, as an inline script runs at once.
* An element marked `data-no-inline`, or without a valid `href` or `src`, is left as it is:

  ```html
  <script src="main.dart.js" data-no-inline></script>
  ```

The page is sent as UTF-8.


# Full-stack with Kelicap

[Kelicap](https://github.com/dukefirehawk/kelicap) is a Dart web framework derived from AngularDart, which compiles to HTML and JavaScript. With Kelicap for the web client and Angel3 for the server, both are written in Dart, and share the same model classes.

The client calls the server's services with [`angel3_client`](https://pub.dev/packages/angel3_client), whose `browser.dart` compiles to JavaScript with `dart2js`.

## Starting a project

Create a project from the [Kelicap template](https://github.com/dart-backend/boilerplates/tree/master/templates/basic_kelicap), with the [CLI](/command-line-interface/cli-setup):

```bash
angel3 init my_app
```

and choose `Kelicap`. The project is a [pub workspace](https://dart.dev/tools/pub/workspaces) of three packages:

| Directory | What it is                                                            |
| --------- | --------------------------------------------------------------------- |
| `.`       | The Angel3 server: the API under `/api`, which also serves the client |
| `shared/` | The models of both, made with `angel3_serialize`                      |
| `client/` | The Kelicap client: its pages, routes and services                    |

The server and the client have one origin, the server's. In development, the server forwards the pages to the client's `build_runner serve`; in production, it serves the client as built. So the client needs no CORS, and cookies work.

## Development

1. In `client/`, build the client, and rebuild it as its files change, on port 8080:

   ```bash
   cd client
   dart run build_runner serve web:8080
   ```
2. In another terminal, from the project's root, start the server, hot-reloaded on file changes:

   ```bash
   dart --observe bin/dev.dart
   ```
3. Open <http://localhost:3000>, the server's port, not the client's.

## Production

Build the client, optimized, into `client/build`, then run the server, which serves it:

```bash
cd client
dart run build_runner build --release -o web:build
cd ..
ANGEL_ENV=production dart bin/prod.dart
```

The template's `Containerfile` builds the client and the server together, to run them with [Podman](/deployment/podman).

## Calling the server

The client reaches a service of the server through `angel3_client`:

```dart
import 'package:angel3_client/browser.dart';
import 'package:shared/shared.dart';

Angel app = Rest(window.location.origin);

// The service, whose methods take and give the `Greeting` of shared/.
var greetings = app.service<String, Greeting>(
  'api/greetings',
  deserializer: (map) => GreetingSerializer.fromMap(map as Map),
);

await greetings.index();                              // GET    /api/greetings
await greetings.create(Greeting(message: 'Hi'));      // POST   /api/greetings
await greetings.remove(id);                           // DELETE /api/greetings/:id
```

An error of the server is thrown as an `AngelHttpException`, with its status code and message. `app.authenticate(...)` logs in with `angel3_auth`, after which the client sends its token with each request. A `ServiceList` keeps a list of a service's records, which updates itself as the service is called.

For live updates, use the WebSocket client of [`angel3_websocket`](https://pub.dev/packages/angel3_websocket), whose services work the same way.

## Sharing models

Keep the models in `shared/`, and generate their serializers there with `dart run build_runner build`. `shared/` is compiled to JavaScript for the client, so keep `dart:io`, `angel3_framework` and other server packages out of it. ORM models, annotated with `@orm`, belong to the server.

See the [Kelicap documentation](https://github.com/dukefirehawk/kelicap-docs) for the client side.


# Authentication


# About

`angel3_auth` is, in many ways, a port of Passport to the Angel3 Framework. It authenticates users with JSON Web Tokens (JWTs), and comes with a local strategy, which also supports HTTP Basic authentication.

```yaml
dependencies:
  angel3_auth: ^10.0.0
```

## Usage

```dart
import 'package:angel3_auth/angel3_auth.dart';
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';

void main() async {
  var app = Angel();

  // Of course, create an instance.
  //
  // A `jwtKey` is not required, but without a pre-established secret,
  // JWT's will automatically be invalidated whenever the server restarts.
  //
  // If `allowCookie` is `true` (`true` by default), then JWT's can also be carried within
  // a `token` cookie.
  var auth = AngelAuth<User>(
    jwtKey: 'MY_SECRET',
    // The following two functions de/serialize a user from a JWT.
    serializer: (user) => user.id ?? '',
    deserializer: (id) => fetchAUserByIdSomehow(id),
  );

  // This adds a global middleware to decode JWT's and deserialize them,
  // and also creates a route to refresh JWT's.
  await app.configure(auth.configureServer);

  // Strategies are used to implement authentication methods
  auth.strategies['local'] = LocalAuthStrategy((username, password) async {
    // Return the user if the credentials are valid, or `null` otherwise.
    return await findCorrespondingUser(username, password);
  });

  // Use `authenticate` to log users in
  app.post('/auth/local', auth.authenticate('local'));

  await AngelHttp(app).startServer('127.0.0.1', 3000);
}

class User {
  String? id, username, password;
}
```

After a user is logged in, later requests that send the JWT, in an `Authorization: Bearer` header or the `token` cookie, are authenticated. Read the user with `req.container!.make<User>()`, and protect routes with the `requireAuthentication<User>()` middleware.

## Security Defaults

* A JWT expires after a day (`jwtLifeSpan`, in milliseconds).
* `POST /auth/token` exchanges a JWT that is still valid for a new one; an expired one only within `reviveGracePeriod` (default: none).
* The `token` cookie is `HttpOnly`, `Secure` and `SameSite=Lax` (`cookieSameSite`), and is set when a user logs in. `logout` expires it.
* A JWT in the query string (`?token=`) is ignored unless `allowTokenInQuery` is `true`.

These changed in 10.0.0; see the [README of `angel3_auth`](https://pub.dev/packages/angel3_auth) for how to upgrade.


# Strategies

Just like in Passport, strategies implement authentication via a specific provider. To create your own strategy, you need to implement the `AuthStrategy` class.

All strategies must implement `authenticate(req, res, [options])`.

## authenticate

This method should only have two possible results.

**Possibility #1:** Return a user

This signifies that the user was successfully authenticated. The user is serialized with the `serializer` of `AngelAuth`, and a JWT is issued for it.

**Possibility #2:** Return `null`

This represents an authentication failure, and will throw a `401 Not Authenticated` error, unless another strategy given to `authenticate` succeeds.

```dart
import 'dart:async';

import 'package:angel3_auth/angel3_auth.dart';
import 'package:angel3_framework/angel3_framework.dart';

class MyStrategy extends AuthStrategy<User> {
  @override
  Future<User?> authenticate(RequestContext req, ResponseContext res,
      [AngelAuthOptions<User>? options]) async {
    await req.parseBody();
    return await login(
        req.bodyAsMap['username'] as String?, req.bodyAsMap['password'] as String?);
  }
}
```

Register it with `auth.strategies['my'] = MyStrategy();`, and use it with `auth.authenticate('my')`.

## Other Strategies

* [Local](/authentication/local-auth), with and without HTTP Basic authentication, is part of `angel3_auth`.
* [OAuth2](https://pub.dev/packages/angel3_auth_oauth2), for providers such as Google or GitHub.
* [Twitter](https://github.com/dart-backend/angel/tree/master/packages/auth_twitter), with OAuth 1.0a.


# Local

`LocalAuthStrategy` authenticates users by a username and a password, sent in the request body, or, with `allowBasic: true`, in an HTTP Basic `Authorization` header:

```dart
auth.strategies['local'] = LocalAuthStrategy<User>(
  (username, password) async => await findCorrespondingUser(username, password),
  allowBasic: true,
);

app.post('/auth/local', auth.authenticate('local'));
```

See the [docs](https://pub.dev/documentation/angel3_auth/latest/angel3_auth/LocalAuthStrategy-class.html).


# Databases


# Object Relational Mapping (ORM)


# About

Angel3, 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.

Angel3'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. It supports PostgreSQL 16 or later, MySQL 8 or later, and MariaDB 10.2 or later.

Take, for example, the following class:

```dart
@serializable
@orm
abstract class PokemonEntity extends Model {
    String? get nickName;

    int? get level;

    int? get experiencePoints;

    @belongsTo
    PokemonTrainerEntity? get trainer;

    @belongsTo
    PokemonSpeciesEntity? get species;

    @belongsTo
    PokemonAttackEntity? get attack0;

    @belongsTo
    PokemonAttackEntity? get attack2;

    @belongsTo
    PokemonAttackEntity? get attack3;

    @belongsTo
    PokemonAttackEntity? get attack4;
}
```

`package:angel3_orm_generator` will generate a `Pokemon` model and a `PokemonQuery` class that let 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 query = PokemonQuery()..where!.trainerId.equals(id);
    var pokemon = await query.get(executor);
    return pokemon.map((p) => p.attack0?.name).toList();
});
```

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

For more in-depth documentation, see the actual `angel3_orm` project on GitHub:

<https://github.com/dart-backend/angel/tree/master/packages/orm>


# Basic Functionality

Before starting with the ORM, it is highly recommended to familiarize oneself with `package:angel3_serialize`, as it is the foundation for `package:angel3_orm`. See [Serialization](/under-the-hood/serialization).

Add the ORM, its generator, and the package of your database to your `pubspec.yaml`:

```yaml
dependencies:
  angel3_orm: ^10.0.0
  angel3_orm_postgres: ^10.0.0 # or angel3_orm_mysql for MySQL and MariaDB
  angel3_migration: ^10.0.0
  angel3_serialize: ^10.0.0
  optional: ^6.1.0
dev_dependencies:
  angel3_orm_generator: ^10.0.0
  build_runner: ^2.6.0
```

To enable the ORM for a given model, simply add the `@orm` annotation to its definition. The name of the model ends with `Entity`, which the generated classes are named without:

```dart
import 'package:angel3_migration/angel3_migration.dart';
import 'package:angel3_orm/angel3_orm.dart';
import 'package:angel3_serialize/angel3_serialize.dart';
import 'package:optional/optional.dart';

part 'todo.g.dart';

@serializable
@orm
abstract class TodoEntity extends Model {
    bool? get isComplete;

    String? get text;

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

Then run `dart run build_runner build`. The generator will produce a `Todo` model, a `TodoMigration`, and a `TodoQuery` class, which contains fields corresponding to each field declared in `TodoEntity`. 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> {
    TodoQueryWhere? get where;

    TodoQueryValues get values;
}

class TodoQueryWhere extends QueryWhere {
    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);
}
```

`get` returns a `List`, and `getOne`, `insert`, `updateOne` and `deleteOne` return an `Optional` of a record, from `package:optional`.

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. `QueryExecutor.transaction` runs queries in a transaction, which is rolled back if its callback throws:

```dart
var todo = await executor.transaction((tx) async {
    var query = TodoQuery()..values.text = 'Clean your room';
    return (await query.insert(tx)).value;
});
```

Consumers of a `QueryExecutor` typically inject it into the app's [dependency injection](/under-the-hood/dependency-injection) container:

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

The ORM supports PostgreSQL, through [`angel3_orm_postgres`](/databases/object-relational-mapping-orm/postgresql), and MySQL and MariaDB, through [`angel3_orm_mysql`](/databases/object-relational-mapping-orm/mysql).


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

Angel3 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
@serializable
abstract class WheelEntity extends Model {
  @belongsTo
  CarEntity? 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')
CarEntity? get car;
```

The ORM fetches `@hasOne` and `@belongsTo` relations with `JOIN`s, in the same query as the records, as each record is still one row. `@hasMany` and `@manyToMany` relations are loaded after the records, with one query for all of them (`WHERE car_id IN (...)`), so `limit` and `offset` count records rather than the rows of a join. In Angel3 9.x and earlier, these were joined too.

## 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 Angel3 ORM, this is relatively straightforward:

```dart
@serializable
abstract class ClassEntity extends Model {
  String? get courseName;

  @ManyToMany(EnrollmentEntity)
  List<StudentEntity> get students;
}

@serializable
abstract class StudentEntity extends Model  {
  String? get name;
  int? get year;

  @ManyToMany(EnrollmentEntity)
  List<ClassEntity> get classes;
}

@serializable
abstract class EnrollmentEntity {
    @belongsTo
    StudentEntity? get student;

    @belongsTo
    ClassEntity? get class_;
}
```

In short:

1. Make a pivot table, C, between two tables, table A and B.
2. C should `@belongsTo` both A and B. C *should not* extend `Model`.
3. A should have a field: `@ManyToMany(CEntity) List<BEntity> get b;`
4. B should have a field: `@ManyToMany(CEntity) List<AEntity> get a;`


# Migrations

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

An example is shown below:

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

class UserMigration extends 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 or drop database tables; altering a table is not supported.

`defaultsTo` takes the default of a column as a value, which is written as a literal: a `String` is quoted and escaped, so it is never run as SQL. For SQL, such as the current time, give a `RawSql` of `package:angel3_orm`, such as `currentTimestamp`:

```dart
table.timeStamp('created_at').defaultsTo(currentTimestamp);
```

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

<https://github.com/dart-backend/angel/tree/master/packages/orm/migration>

If you use `angel3_orm_generator`, then a migration will be generated by default for each class annotated with `@orm`, such as `UserMigration` for `UserEntity`.

To disable this:

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

## Running Migrations

Using `package:angel3_migration_runner`, we can create executables, such as `bin/migrate.dart`, that run our database migrations. Use `PostgresMigrationRunner` for PostgreSQL, and `MySqlMigrationRunner` or `MariaDbMigrationRunner` for MySQL and MariaDB:

```dart
import 'package:angel3_migration_runner/angel3_migration_runner.dart';
import 'package:angel3_migration_runner/postgres.dart';
import 'package:postgres/postgres.dart';

import 'package:my_app/models.dart';

void main(List<String> args) async {
  var connection = await Connection.open(
    Endpoint(
      host: 'localhost',
      database: 'demo',
      username: 'demouser',
      password: 'demo123',
    ),
    settings: ConnectionSettings(sslMode: SslMode.disable),
  );

  var runner = PostgresMigrationRunner(
    connection,
    migrations: [UserMigration(), TodoMigration()],
  );

  // `dart bin/migrate.dart up`, `rollback`, `reset` or `refresh`
  await runMigrations(runner, args);
}
```

`runMigrations` closes the runner, even when a migration fails. For MySQL and MariaDB, use `MySqlMigrationRunner` and `MariaDbMigrationRunner`.

Running this file without a command will produce output like the following:

```bash
Executes Angel3 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. Each migration is recorded by its `name`, which defaults to the name of its class. Override `name` to keep it stable when the class is renamed, or the app is compiled with `--obfuscate`:

```dart
class CreateUsersMigration extends Migration {
  @override
  String get name => 'create_users';
  ...
}
```

On PostgreSQL, each migration runs, and is recorded, in one transaction. MySQL and MariaDB commit each change of a table on its own.

Versions before 10.0.0 recorded a migration by its source file and class name. The runner renames those records on its first run; see the [README of `angel3_migration_runner`](https://pub.dev/packages/angel3_migration_runner) for the cases it cannot rename.


# PostgreSQL

PostgreSQL 16 or later is supported by way of `package:angel3_orm_postgres`, which uses version 3 of [`package:postgres`](https://pub.dev/packages/postgres). The `PostgreSqlExecutor` implements `QueryExecutor`, and takes care of running prepared queries, and passing values to the database server.

```yaml
dependencies:
  angel3_orm_postgres: ^10.0.0
  postgres: ^3.5.20
```

The [PostgreSQL ORM template](https://github.com/dart-backend/boilerplates/tree/master/templates/basic_postgres_orm) includes helpers like this to load app configuration into a database connection:

```dart
import 'dart:async';
import 'dart:io';

import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_orm/angel3_orm.dart';
import 'package:angel3_orm_postgres/angel3_orm_postgres.dart';
import 'package:postgres/postgres.dart';

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

    // Given the endpoint and settings, the executor opens a new connection
    // when this one breaks, as when the database restarts.
    var executor = PostgreSqlExecutor(
      connection,
      endpoint: postgresEndpoint(app.configuration),
      settings: postgresSettings(app.configuration),
      logger: app.logger,
    );

    // The executor closes the connection it uses, which may be a new one.
    app
      ..container.registerSingleton<QueryExecutor>(executor)
      ..shutdownHooks.add((_) => executor.close());
  } catch (e) {
    app.logger.severe("Failed to connect to PostgreSQL. ORM disabled.", e);
  }
}

// PostgreSQL connection, of the `postgres` section of the configuration.
Future<Connection> connectToPostgres(Map configuration) => Connection.open(
  postgresEndpoint(configuration),
  settings: postgresSettings(configuration),
);

// The PostgreSQL server, of the `postgres` section of the configuration. The
// POSTGRES_HOST, POSTGRES_USERNAME and POSTGRES_PASSWORD environment variables
// override its `host`, `username` and `password`, as in a container, so they
// need not be kept in a file.
Endpoint postgresEndpoint(Map configuration) {
  var postgresConfig = configuration['postgres'] as Map? ?? {};
  return Endpoint(
    host:
        Platform.environment['POSTGRES_HOST'] ??
        postgresConfig['host'] as String? ??
        'localhost',
    port: postgresConfig['port'] as int? ?? 5432,
    database:
        postgresConfig['database_name'] as String? ??
        Platform.environment['USER'] ??
        Platform.environment['USERNAME'] ??
        '',
    username:
        Platform.environment['POSTGRES_USERNAME'] ??
        postgresConfig['username'] as String?,
    password:
        Platform.environment['POSTGRES_PASSWORD'] ??
        postgresConfig['password'] as String?,
  );
}

// The settings of a connection, of the `postgres` section of the
// configuration.
ConnectionSettings postgresSettings(Map configuration) {
  var postgresConfig = configuration['postgres'] as Map? ?? {};
  var useSsl = postgresConfig['use_ssl'] as bool? ?? false;
  return ConnectionSettings(
    sslMode: useSsl ? SslMode.require : SslMode.disable,
    timeZone: postgresConfig['time_zone'] as String? ?? 'UTC',
    connectTimeout: Duration(
      seconds: postgresConfig['timeout_in_seconds'] as int? ?? 30,
    ),
  );
}
```

Typically, you'll want to use app configuration to create the connection, rather than hard coding values. The template also lets the `POSTGRES_HOST`, `POSTGRES_USERNAME` and `POSTGRES_PASSWORD` environment variables override the configuration, as in a container, so they need not be kept in a file.

## Connection Pools

To run queries on several connections, give a `Pool` of `package:postgres` to a `PostgreSqlPoolExecutor`:

```dart
var pool = Pool.withEndpoints(
  [Endpoint(host: 'localhost', database: 'demo', username: 'demouser', password: 'demo123')],
  settings: PoolSettings(maxConnectionCount: 10, sslMode: SslMode.disable),
);
var executor = PostgreSqlPoolExecutor(pool);
```

## Transactions

`transaction` runs its callback in a transaction, which is committed if the callback completes, and rolled back if it throws. Use the executor given to the callback:

```dart
var car = await executor.transaction((tx) async {
  var query = CarQuery()..values.make = 'Ferrari';
  return (await query.insert(tx)).value;
});
```

PostgreSQL does not nest transactions, so `transaction` on the executor the callback is given runs in a savepoint instead. What it does is rolled back if it throws, even when the outer callback catches the error, and committed with the outer transaction otherwise:

```dart
await executor.transaction((tx) async {
  await insertOrder(tx);
  try {
    await tx.transaction((inner) => sendInvoice(inner));
  } on InvoiceException {
    // Only the savepoint is rolled back; the order is kept.
  }
});
```

See the [README of `angel3_orm_postgres`](https://pub.dev/packages/angel3_orm_postgres) for more.


# MySQL and MariaDB

MySQL 8 or later, and MariaDB 10.2 or later, are supported by way of `package:angel3_orm_mysql`, which uses the [`mysql_dart`](https://pub.dev/packages/mysql_dart) driver. It provides two executors, which implement `QueryExecutor`:

* `MySqlExecutor`, for MySQL, which stores a `DateTime` as local time.
* `MariaDbExecutor`, for MariaDB, which stores a `DateTime` as UTC.

```yaml
dependencies:
  angel3_orm_mysql: ^10.0.0
  mysql_dart: ^3.0.3
```

```dart
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_orm/angel3_orm.dart';
import 'package:angel3_orm_mysql/angel3_orm_mysql.dart';
import 'package:mysql_dart/mysql_dart.dart';

Future<void> configureServer(Angel app) async {
  var connection = await MySQLConnection.createConnection(
    host: 'localhost',
    port: 3306,
    databaseName: 'orm_test',
    userName: 'test',
    password: 'test123',
    secure: true,
  );
  await connection.connect(timeoutMs: 10000);

  app
    ..container.registerSingleton<QueryExecutor>(
        MySqlExecutor(connection, logger: app.logger))
    ..shutdownHooks.add((_) => connection.close());
}
```

For MariaDB, use `MariaDbExecutor(connection)` instead. Run the migrations with `MySqlMigrationRunner` or `MariaDbMigrationRunner` of `package:angel3_migration_runner`; see [Migrations](/databases/object-relational-mapping-orm/migrations).

## Transactions

`transaction` runs its callback in a transaction, which is committed if the callback completes, and rolled back if it throws. The queries of a connection run one at a time, and a transaction holds the connection until it ends, so use the executor given to the callback, and await its queries. MySQL and MariaDB do not nest transactions.

```dart
var car = await executor.transaction((tx) async {
  var query = CarQuery()..values.make = 'Ferrari';
  return (await query.insert(tx)).value;
});
```

## Known Limitations

* `Blob` data type mapping is not supported.
* A `timestamp` column is read and written as a `datetime` one is, and the migration runner creates `timeStamp` columns as `datetime`.
* A `datetime` column has no time zone, so use one executor for a database, or run the application at UTC. Give the date of a `date` column as a `DateTime` of the time zone of the executor: UTC for `MariaDbExecutor`, and local time for `MySqlExecutor`.

See the [README of `angel3_orm_mysql`](https://pub.dev/packages/angel3_orm_mysql) for more.


# 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 database, 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:angel3_serialize`, this is pretty easy:

```dart
@serializable
abstract class GreetingEntity extends Model {
    String? get text;

    double? get attachedMoney;
}

var service = MongoService(db.collection('greetings'));
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]);
```

Angel3 has services for several NoSQL databases: [MongoDB](https://pub.dev/packages/angel3_mongo), [RethinkDB](https://pub.dev/packages/angel3_rethinkdb), [Redis](https://pub.dev/packages/angel3_redis) and [Sembast](https://pub.dev/packages/angel3_sembast), as well as a [JSON file](https://pub.dev/packages/angel3_file_service) for development.


# Sembast

[Sembast](https://pub.dev/packages/sembast) is a NoSQL database that runs in the server, and keeps its data in one file: there is no database server to install. [`angel3_sembast`](https://github.com/dart-backend/angel/tree/master/packages/sembast) serves a store of it as a [service](/under-the-hood/service-basics).

```yaml
dependencies:
  angel3_sembast: ^10.0.0
  sembast: ^3.1.1
```

The `Sembast` [starter template](/tutorial/application-setup) is set up with it.

## Usage

Open the database, and mount a `SembastService` of one of its stores:

```dart
import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_sembast/angel3_sembast.dart';
import 'package:sembast/sembast_io.dart';

Future configureServer(Angel app) async {
  var db = await databaseFactoryIo.openDatabase('todos.db');

  app
    ..use('/api/todos', SembastService(db, store: 'todos'))
    ..shutdownHooks.add((_) => db.close());
}
```

The `id` of a record is its key in the store.

## Querying

Query a service with the query string:

```bash
curl 'http://localhost:3000/api/todos?title=Clean'
```

A record must match every field of the query, and `id` matches the key of the record. Values of the query string are strings, so they only match string fields; query other types from Dart.

Sort with `$sort`: a field name sorts by it in ascending order, and a map of field names to `1` (ascending) or `-1` (descending) sorts by each of them:

```dart
await service.index({
  'query': {r'$sort': {'title': -1}},
});
```

You can also pass a Sembast `Finder` as `query`:

```dart
var queried = await service.index({
  'query': Finder(filter: Filter.equals('completed', false)),
});
```

To map records to your own model classes, see [NoSQL](/databases/nosql).


# Extensions and Plugins


# Using Plug-ins

* [Using Plug-ins](#using-plug-ins)
  * [Execution Order](#execution-order)
  * [Writing a Plug-in](/extensions-and-plugins/writing-a-plugin)
* [Next Up...](#next-up)

## Using Plug-ins

Angel3 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 may 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 AngelConfigurer = FutureOr<void> Function(Angel app);
```

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

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

Future<void> plugin(Angel app) async {
  print('Do stuff here');
}

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

### 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](/under-the-hood/service-basics) already being mounted. You can set aside a plug-in to be run just before server startup by adding it to `app.startupHooks`, instead of directly calling `app.configure()`.

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

Likewise, you can add hooks that run when the app is shut down, via `Angel.shutdownHooks`. They run once, after the requests in progress have finished, and before the services are closed.

## Next Up

Learn how to generate content for clients by [rendering views](/templates-and-views/rendering-views).


# Writing a Plugin

[Guidelines](#guidelines)

Writing a [plug-in](/extensions-and-plugins/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 {
  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 Angel3 API's whenever possible. This will help your plugin resist breaking change in the future.
* 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, a compression plugin could have 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
void main() {
  var app = Angel();

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

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


# Under the hood


# Basic Routing

* [Routing](#routing)
* [Route Parameters](#route-parameters)
  * [Parsing Parameters](#parsing-parameters)
* [`RegExp` Routes](#regexp-routes)
* [Mounting Routers](#mounting-routers)
* [Route Groups](#route-groups)
* [Extended Documentation](#extended-documentation)
* [Next Up...](#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.put('<path>', requestHandler);
app.patch('<path>', requestHandler);
app.delete('<path>', requestHandler);
app.head('<path>', requestHandler);
```

Your `requestHandler` should take the following form:

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

Your `requestHandler` can return any Dart value, whether a function, or an object. See the [Requests and Responses](/under-the-hood/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`. A typed parameter matches only a number, so `/add/abc` is not routed to the handler below:

```dart
app
  ..get('/add/int:number', (req, res) => (req.params['number'] as int) * 3)
  ..get('/multiply/double:number', (req, res) => (req.params['number'] as double) * 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])?)', ...);
```

## Mounting Routers

You can `mount` routers, and their routes are added under the given path. Services are mounted with `use`, as [Service Basics](/under-the-hood/service-basics#mounting-services) describes.

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

var subRouter = Router<RequestHandler>()..get('/', (req, res) => 'Subroute');
app.mount('/sub', subRouter);
// Now, you can visit /sub and receive the message "Subroute"
```

## Route Groups

Routes can also be grouped together. Route parameters, and the group's `middleware`, will be applied to sub-routes automatically. Route groups can be nested as well.

```dart
app.group('/user/:id', (router) {
  router
    ..get('/messages', (req, res) => fetchUserMessages(req.params['id']))
    ..group('/nested', (nested) {
      // ...
    });
}, middleware: [requireAuthentication]);
```

## Extended Documentation

For more documentation on the router, see [Angel3 Route Repository](https://github.com/dart-backend/angel/tree/master/packages/route). [`angel3_route`](https://pub.dev/packages/angel3_route) has no `dart:io` or `dart:mirrors` dependency, and it also supports browser use (both hash and push state).

## Next Up

Learn how [Requests and Responses](/under-the-hood/requests-and-responses) work, and then how [Middleware](/under-the-hood/middleware) lets you reuse functionality across your entire routing setup.


# Requests & Responses

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

## Requests and Responses

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

* [`RequestContext`](https://pub.dev/documentation/angel3_framework/latest/angel3_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.
* [`ResponseContext`](https://pub.dev/documentation/angel3_framework/latest/angel3_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`, or nothing: Request handling will end, as if you returned `false`. Return `true` from a middleware that lets the request through. The response is sent as the handler left it, such as after `res.write()`. Some response methods, such as [`res.redirect()`](https://pub.dev/documentation/angel3_framework/latest/angel3_framework/ResponseContext/redirect.html) or [`res.serialize()`](https://pub.dev/documentation/angel3_framework/latest/angel3_framework/ResponseContext/serialize.html), automatically close the response.
* A `RequestHandler`: the returned handler will be executed.
* Another function: it will be called with its parameters injected, which needs a [reflector](/under-the-hood/dependency-injection#enabling-dart-mirrors-or-other-reflection).
* 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.dev/documentation/angel3_framework/latest/angel3_framework/Angel/serializer.html) on your Angel instance. The default serializer is `json.encode`, which handles JSON-compatible Dart objects, like Maps and Lists, and objects with a `toJson` method.

### Buffered and Streamed Responses

By default, what a handler writes is streamed to the client. Call `res.useBuffer()` to buffer the response instead, so that it can still be changed, for example by `responseFinalizers`, until the request ends. A buffered response is sent with a `Content-Length` header; set `res.chunked = true` to send it with chunked transfer encoding.

### Other Parameters

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

### Queries, Files and Bodies

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

Consult the [body parsing documentation](/under-the-hood/body-parsing) to understand how to handle user input.

For more information, see the API docs:

[RequestContext](https://pub.dev/documentation/angel3_framework/latest/angel3_framework/RequestContext-class.html)

[ResponseContext](https://pub.dev/documentation/angel3_framework/latest/angel3_framework/ResponseContext-class.html)

## Next Up

Now, let's learn about Angel3's [Request Lifecycle](/under-the-hood/request-lifecycle).


# Request Lifecycle

Requests in the Angel3 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. `angel3_route` is used to match the request path to a list of request handlers.
5. Each handler is executed. Each handler must return `true` for the next one to run.
6. If the response is streamed (the default), rather than buffered (`res.useBuffer()`), skip to step 9.
7. All `responseFinalizers` are run.
8. All headers, the status code and the response buffer are sent through the actual `HttpResponse`, with a `Content-Length` header, unless `res.chunked` is `true`.
9. The `HttpResponse` is closed.

When the server shuts down, `AngelHttp.close()` stops accepting requests, lets those in progress finish, within `closeTimeout`, and then runs the app's `shutdownHooks`.

If at any point an error occurs, Angel3 will catch it. See the [error handling](/under-the-hood/error-handling) docs for more.

## Next Up

Continue reading to learn about [Dependency Injection](/under-the-hood/dependency-injection).


# Dependency Injection

Angel3 uses a [container hierarchy](https://github.com/dart-backend/angel/tree/master/packages/container/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 `container` 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 = req.container!.findByName<Db>('database');
var collection = db.collection('pets');
```

Registering and reading instances, as above, needs no reflection.

## In Routes and Controllers

In Angel3, by wrapping a function in a call to `ioc`, you can automatically inject the dependencies of any route handler. Reflecting on the function needs a reflector (see [below](#enabling-dart-mirrors-or-other-reflection)); without one, describe its parameters with `injection:`:

```dart
app.get('/greet/:name', ioc(
  (Greeter greeter, String name) => greeter.greet(name),
  injection: InjectionRequest.constant(required: [Greeter, ['name', String]]),
));
```

With a reflector:

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

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

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

  @Expose("/baz")
  baz({Foo? optionalInjection}) => 'baz';
}
```

`ioc` finds the parameters of the function with the app's reflector. Without one, as in an app compiled with `dart compile exe`, list them in an `InjectionRequest`; a parameter given as `[name, type]` is read from the route parameters:

```dart
app.get('/greet/:name', ioc(
  (Greeter greeter, String name) => greeter.greet(name),
  injection: InjectionRequest.constant(required: [Greeter, ['name', String]]),
));
```

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

```dart
Future<void> 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')
  Future 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 extends Controller {
  final AngelAuth auth;
  final Db db;

  MyController(this.auth, this.db);

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

void main() async {
  var app = Angel(reflector: MirrorsReflector());

  // 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()` has no reflector, so that it can be used where `dart:mirrors` is not available, such as in apps compiled with `dart compile exe` and in Flutter. Without a reflector, these features are unavailable:

* `@Expose` on controller methods
* The `@Middleware` and `@Hooks` annotations, which are ignored
* Dependency injection into **constructors**, whether in controllers or plain `container.make` calls
* `ioc` without `injection:`

To use them, pass a reflector to the app:

* On the Dart VM, `MirrorsReflector` of `package:angel3_container_mirrors` uses `dart:mirrors`:

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

  var app = Angel(reflector: MirrorsReflector());
  ```
* To compile with `dart compile exe`, mark the classes with `@injectable`, generate their reflection data with `package:angel3_container_generator` and `dart run build_runner build`, and pass it to `StaticReflector`. Each library gets one variable named after its file, such as `servicesReflection` for `services.dart`:

  ```dart
  var app = Angel(reflector: StaticReflector.combine([servicesReflection]));
  ```

Mark controllers, services with `@Hooks` or `@Middleware`, and top-level functions used as handlers with `@injectable`. A closure cannot be described, so `ioc((Foo foo) => ...)` still needs `injection:` with generated data. The [`angel3_container_generator` README](https://pub.dev/packages/angel3_container_generator) lists its limitations.

## Next Up

Continue reading to learn about [Middleware](/under-the-hood/middleware).


# Running without dart:mirrors

`dart compile exe` and Flutter do not support `dart:mirrors`. An Angel3 app can still be compiled into a native executable, which starts faster, and needs no Dart SDK to run:

```bash
dart compile exe bin/prod.dart -o server
ANGEL_ENV=production ./server
```

There are two ways to do this: run the app without a reflector, or give it reflection data generated at build time.

## Without a reflector

`Angel()` has no reflector by default, so it runs with reflection disabled. Routes, services, hooks added with `listen`, and types registered in the container work as usual:

```dart
var app = Angel(); // no reflector

app.container.registerSingleton(Greeter());   // register what you inject
app.use('/api/todos', MapService());           // services work as usual

// Inject with an explicit InjectionRequest instead of reflecting on the closure.
app.get('/greet/:name', ioc(
  (Greeter greeter, String name) => greeter.greet(name),
  injection: InjectionRequest.constant(required: [Greeter, ['name', String]]),
));

// Controllers take their mount path from `expose` and add routes in `configureRoutes`.
class HealthController extends Controller {
  HealthController() : super(expose: const Expose('/health'));

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

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

Without reflection, these features are unavailable:

* `@Expose` on controller methods
* The `@Middleware` and `@Hooks` annotations, which are ignored
* Dependency injection into constructors, in controllers or `container.make`
* `ioc` without `injection:`

The app logs a warning at startup that says so. The [`no_mirrors.dart` example](https://github.com/dart-backend/angel/blob/master/packages/framework/example/no_mirrors.dart) is a complete app.

## With generated reflection data

To keep those features in a compiled app, generate the reflection data they need with [`angel3_container_generator`](https://pub.dev/packages/angel3_container_generator):

1. Add the generator to `pubspec.yaml`:

   ```yaml
   dependencies:
     angel3_container: ^10.0.0
   dev_dependencies:
     angel3_container_generator: ^10.0.0
     build_runner: ^2.4.0
   ```
2. Mark the classes with `@injectable`, and add a `part` directive:

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

   part 'controller.g.dart';

   @injectable
   @Expose('/greet')
   class GreetController extends Controller {
     // GET /greet/hello/:name
     String getHello(String name) => 'Hello, $name!';

     // GET /greet/shout?text=...
     @Expose('/shout')
     String shout(@Query('text') String text) => text.toUpperCase();
   }
   ```
3. Run `dart run build_runner build`. Each library gets one variable named after its file, here `controllerReflection`.
4. Pass the data to the app:

   ```dart
   var app = Angel(reflector: StaticReflector.combine([controllerReflection]));
   await app.configure(GreetController().configureServer);
   ```

Mark with `@injectable`:

* Controllers, so their `@Expose` methods are routed
* Services with `@Hooks` or `@Middleware`
* Classes the container constructs, such as a controller with constructor parameters
* Models whose members are read by name, as in a Jael template
* Top-level functions used as handlers, so `@Middleware` on them applies, and `ioc(handler)` can inject their parameters

A closure cannot be described, so `ioc((Foo foo) => ...)` still needs `injection:`. The [generator's README](https://pub.dev/packages/angel3_container_generator) lists its other limitations.

## With `angel3_production`

The starter templates run their production server with the `Runner` of [`angel3_production`](https://github.com/dart-backend/angel/tree/master/packages/production), without a reflector, so `bin/prod.dart` can be compiled as it is. To use generated data, pass it to the `Runner`:

```dart
void main(List<String> args) => Runner(
  'Starter App',
  configureServer,
  reflector: StaticReflector.combine([controllerReflection]),
).run(args);
```

## On the Dart VM

When the app runs with `dart run`, `MirrorsReflector` of [`angel3_container_mirrors`](https://pub.dev/packages/angel3_container_mirrors) provides the same features with `dart:mirrors`, without generated code:

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

var app = Angel(reflector: MirrorsReflector());
```


# Middleware

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

## Middleware

Sometimes, it becomes necessary to recycle code to run on multiple routes. Angel3 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 Angel3 can be any route handler, whether a function or arbitrary data. You can also throw exceptions in middleware.

### Denying Requests via Middleware

A middleware must return `true` for the next handler to run. If it returns anything else, including nothing, no further handlers will be executed, whether they were given to a route or to `chain`. (more on request handler return values [here](/under-the-hood/requests-and-responses#return-values)).

A middleware that only sets a value must still return `true`:

```dart
app.get('/me', chain([
  (req, res) {
    req.params['user'] = 'me';
    return true;
  },
  (req, res) => req.params['user'],
]));
```

In Angel3 9.x and earlier, a handler given to `chain` that returned nothing let the next one run. Since 10.0.0, it stops the chain.

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) => true,
  (req, res) {
    return 'world!';
  },
]));

// The `middleware: ` parameter is used internally by `package:angel3_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 Angel3 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 by `package:angel3_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](/under-the-hood/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 Angel3 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](/under-the-hood/controllers) providing a `configureServer` method.

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

app.fallback(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(),
]);

Future theActualRouteHandler(RequestContext req, ResponseContext 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](/under-the-hood/controllers) in Angel3!


# Controllers

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

## Controllers

Angel3 has built-in support for controllers. This is yet another way to define routes in a manageable group, and can be leveraged to structure your application in the [MVC](https://en.wikipedia.org/wiki/Model–view–controller) format. You can also use the [`group()`](/under-the-hood/basic-routing#route-groups) method of any [`Router`](https://pub.dev/documentation/angel3_route/latest/angel3_route/Router-class.html).

Routing a controller's `@Expose` methods needs a reflector: `MirrorsReflector` of `angel3_container_mirrors` on the Dart VM, or reflection data generated by `angel3_container_generator` (see [Dependency Injection](/under-the-hood/dependency-injection#enabling-dart-mirrors-or-other-reflection)). The metadata on controller classes is processed via reflection *only once*, at startup. Do not believe that your controllers will be crippled by reflection during request handling, because that possibility is eliminated by [pre-injecting dependencies](/under-the-hood/dependency-injection).

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

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

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

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

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

### @Expose()

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

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

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

### Allowing Null Values

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

```dart
@Expose('/foo/:id?', allowNull: ['id'])
```

### Named Controllers and Actions

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

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

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

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

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

### Interacting with Requests and Responses

Controllers can also interact with [requests and responses](/under-the-hood/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<void> getIndex(ResponseContext res) async {
    await res.render('hello');
  }
}
```

### Transforming Data

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

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

  return true;
}

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

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

### Controllers without Reflection

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

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

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

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

## Next Up

1. How to [handle parse request bodies](/under-the-hood/body-parsing) with Angel3
2. [Using Angel3 Plug-ins](/extensions-and-plugins/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). Angel3 features built-in support for parsing request bodies with the following content types:

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

## Body Parsing

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, even when it is called again before the first call completes, 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, or the body is malformed, a `400 Bad Request` error will be thrown. After a failed parse, `bodyAsMap` and the other body getters are empty.

## Limiting the Size of Bodies

`parseBody` reads at most `app.maxBodySize` bytes, 10 MB by default, and answers larger requests with `413 Payload Too Large`. Raise the limit for one route by setting `req.maxBodySize` before the body is parsed, or set `app.maxBodySize = null` to remove it:

```dart
var app = Angel()..maxBodySize = 1024 * 1024; // 1 MB for the whole app

app.post('/upload', uploadHandler, middleware: [
  (req, res) {
    req.maxBodySize = 100 * 1024 * 1024; // 100 MB
    return true;
  },
]);
```


# Request Limits

## Body size

`req.parseBody()`, which services also use, reads at most `app.maxBodySize` bytes, 10 MB by default, and answers larger requests with `413 Payload Too Large`:

```dart
var app = Angel()..maxBodySize = 1024 * 1024; // 1 MB for the whole app

// Allow larger bodies on one route by raising the limit before parsing.
app.post('/upload', uploadHandler, middleware: [
  (req, res) {
    req.maxBodySize = 100 * 1024 * 1024; // 100 MB
    return true;
  },
]);
```

Set `app.maxBodySize = null` to remove the limit.

See [Parsing Request Bodies](/under-the-hood/body-parsing) for how bodies are parsed.

## Route cache

In production, resolved routes are cached per request path, so a path is only matched against the routes once. The cache holds at most `app.maxHandlerCacheSize` entries, 1024 by default, so requests to many different paths cannot grow it without bound. Set it to `0` to disable the cache:

```dart
var app = Angel()..maxHandlerCacheSize = 4096;
```

## Rate limiting

To limit the number of requests a client can make, use the rate limiters of [`angel3_security`](https://github.com/dart-backend/angel/tree/master/packages/security).


# Serialization

![Pub Version (including pre-releases)](https://img.shields.io/pub/v/angel3_serialize?include_prereleases) [![Null Safety](https://img.shields.io/badge/null-safety-brightgreen)](https://dart.dev/null-safety) [![Discord](https://img.shields.io/discord/1060322353214660698)](https://discord.gg/3X6bxTUdCM) [![License](https://img.shields.io/github/license/dart-backend/angel)](https://github.com/dart-backend/angel/tree/master/packages/serialize/serialize/LICENSE)

Source-generated serialization for Dart objects. This package uses `package:source_gen` to eliminate the time you spend writing boilerplate serialization code for your models. `package:angel3_serialize` also powers `package:angel3_orm`.

* [Angel3 Serialization](#angel3-serialization)
  * [Usage](#usage)
  * [Models](#models)
  * [Serialization](#serialization)
  * [Customizing Serialization](#customizing-serialization)
  * [Subclasses](#subclasses)
  * [Aliases](#aliases)
  * [Excluding Keys](#excluding-keys)
  * [Required Fields](#required-fields)
  * [Adding Annotations to Generated Classes](#adding-annotations-to-generated-classes)
  * [Custom Serializers](#custom-serializers)
  * [Nesting](#nesting)
  * [ID and Dates](#id-and-dates)
  * [Binary Data](#binary-data)
  * [TypeScript Definitions](#typescript-definitions)
  * [Constructor Parameters](#constructor-parameters)

## Usage

In your `pubspec.yaml`, you need to install the following dependencies:

```yaml
dependencies:
  angel3_serialize: ^10.0.0
dev_dependencies:
  angel3_serialize_generator: ^10.0.0
  build_runner: ^2.4.0
```

`angel3_serialize` exports `angel3_model`, so `Model` needs no other import. Build models anywhere in your project structure by running `dart run build_runner build`.

To tweak this: [Build Config](https://pub.dev/packages/build_config)

If you want to watch for file changes and re-build when necessary, replace the `build` call with a call to `watch`. They take the same parameters.

## Models

There are a few changes opposed to normal Model classes. You need to add a `@serializable` annotation to your model class to have it serialized, and a serializable model class's name should end with `Entity`. The generated class takes the name without the suffix. A leading underscore, such as `_Book`, still works, but `Entity` is the convention.

In addition, you may consider using an `abstract` class to ensure immutability of models.

Rather you writing the public class, `angel3_serialize` does it for you. This means that the main class can have its constructors automatically generated, in addition into serialization functions.

For example, say we have a `Book` model. Create a class named `BookEntity`:

```dart
import 'package:angel3_serialize/angel3_serialize.dart';
part 'book.g.dart';

@serializable
abstract class BookEntity extends Model {
  String? get author;

  @SerializableField(defaultValue: '[Untitled]')
  String? get title;

  String? get description;

  int? get pageCount;

  BookType? get type;
}

/// It even supports enums!
enum BookType {
  fiction,
  nonFiction
}
```

The following file will be generated:

* `book.g.dart`

Producing these classes:

* `Book`: Extends or implements `BookEntity`, with `copyWith`, `==` and `toJson`.
* `BookSerializer`: static functionality for serializing `Book` models.
* `BookFields`: The names of all fields from the `Book` model, statically-available.
* `BookEncoder`: Allows `BookSerializer` to extend `Codec<Book, Map>`.
* `BookDecoder`: Also allows `BookSerializer` to extend `Codec<Book, Map>`.

And the following other features:

* `bookSerializer`: A top-level, `const` instance of `BookSerializer`.
* `Book.toString`: Prints out all of a `Book` instance's fields.

## Serialization

You can use the generated files as follows:

```dart
myFunction() {
  var warAndPeace = Book(
    author: 'Leo Tolstoy',
    title: 'War and Peace',
    description: 'You will cry after reading this.',
    pageCount: 1225
  );

  // Easily serialize models into Maps
  var map = BookSerializer.toMap(warAndPeace);

  // Also deserialize from Maps
  var book = BookSerializer.fromMap(map);
  print(book.title); // 'War and Peace'

  // For compatibility with `jsonEncode`, a `toJson` method
  // is included that forwards to `BookSerializer.toMap`:
  expect(book.toJson(), map);

  // Generated classes act as value types, and thus can be compared.
  expect(BookSerializer.fromMap(map), equals(warAndPeace));
}
```

The generated output also includes information about the serialized names of keys on your model class.

```dart
void myOtherFunction() {
  // Relying on the serialized key of a field? No worries.
  map[BookFields.author] = 'Zora Neale Hurston';
}
```

## Customizing Serialization

Currently, these serialization methods are supported:

* to `Map`
* to JSON
* to TypeScript definitions

You can customize these by means of `serializers`, a list of the `Serializers` enum (since 10.0.0; it was a list of integers before):

```dart
@Serializable(serializers: [Serializers.map, Serializers.json])
abstract class MyClassEntity extends Model {}
```

## Subclasses

`angel3_serialize` pulls in fields from parent classes, as well as implemented interfaces, so it is extremely easy to share attributes among model classes:

```dart
import 'package:angel3_serialize/angel3_serialize.dart';
part 'subclass.g.dart';

@serializable
class AnimalEntity {
  @notNull
  String? genus;
  @notNull
  String? species;
}

@serializable
class BirdEntity extends AnimalEntity {
  @DefaultsTo(false)
  bool? isSparrow;
}

var saxaulSparrow = Bird(
  genus: 'Passer',
  species: 'ammodendri',
  isSparrow: true,
);
```

## Aliases

Whereas Dart fields conventionally are camelCased, most database columns tend to be snake\_cased. This is not a problem, because we can define an alias for a field.

By default `angel3_serialize` will transform keys into snake case. Use `alias` to provide a custom name, or pass `autoSnakeCaseNames`: `false` to the builder;

```dart
@serializable
abstract class SpyEntity extends Model {
  /// Will show up as 'agency_id' in serialized JSON.
  ///
  /// When deserializing JSON, instead of searching for an 'agencyId' key,
  /// it will use 'agency_id'.
  ///
  /// Hooray!
  String? agencyId;

  @SerializableField(alias: 'foo')
  String? someOtherField;
}
```

You can also override `autoSnakeCaseNames` per model:

```dart
@Serializable(autoSnakeCaseNames: false)
abstract class OtherCasingEntity extends Model {
  String? camelCasedField;
}
```

## Excluding Keys

In practice, there may be keys that you want to exclude from JSON. To accomplish this, simply annotate them with `@exclude`:

```dart
@serializable
abstract class WhisperEntity extends Model {
  /// Will never be serialized to JSON
  @SerializableField(exclude: true, isNullable: true)
  String? secret;
}
```

There are times, however, when you want to only exclude either serialization or deserialization, but not both. For example, you might want to deserialize passwords from a database without sending them to users as JSON.

In this case, use `canSerialize` or `canDeserialize`:

```dart
@serializable
abstract class WhisperEntity extends Model {
  /// Will never be serialized to JSON
  ///
  /// ... But it can be deserialized
  @SerializableField(exclude: true, canDeserialize: true, isNullable: true)
  String? secret;
}
```

## Required Fields

It is easy to mark a field as required:

```dart
@serializable
abstract class FooEntity extends Model {
  @SerializableField(isNullable: false)
  int? get myRequiredInt;

  @SerializableField(isNullable: false, errorMessage: 'Custom message')
  int? get myOtherRequiredInt;
}
```

The given field will be marked as `required` in the generated constructor, and serializers will check for its presence, throwing a `FormatException` if it is missing.

## Adding Annotations to Generated Classes

There are times when you need the generated class to have annotations affixed to it:

```dart
@Serializable(
  includeAnnotations: [
    Deprecated('blah blah blah'),
    pragma('something...'),
  ]
)
abstract class FooEntity extends Model {}
```

## Custom Serializers

`package:angel3_serialize` does not cover every known Dart data type; you can add support for your own. Provide `serializer` and `deserializer` arguments to `@SerializableField()` as you see fit.

They are typically used together. Note that the argument to `deserializer` will always be `dynamic`, while `serializer` can receive the data type in question.

In such a case, you might want to also provide a `serializesTo` argument. This lets the generator, as well as the ORM, apply the correct (de)serialization rules and validations.

```dart
DateTime? _dateFromString(s) => s is String ? HttpDate.parse(s) : null;
String? _dateToString(DateTime? v) => v == null ? null : HttpDate.format(v);

@serializable
abstract class HttpRequestEntity {
  @SerializableField(
    serializer: #dateToString,
    deserializer: #dateFromString,
    serializesTo: String)
  DateTime? date;
}
```

## Nesting

`angel3_serialize` also supports a few types of nesting of `@serializable` classes:

* As a class member, ex. `Book myField`
* As the type argument to a `List`, ex. `List<Book>`
* As the second type argument to a `Map`, ex. `Map<String, Book>`

In other words, the following are all legal, and will be serialized/deserialized. You can use either the name of a child model class (ex. `BookEntity`), or the generated class name (ex `Book`):

```dart
@serializable
abstract class AuthorEntity extends Model {
  List<BookEntity> get books;
  BookEntity? get newestBook;
  Map<String, BookEntity> get booksByIsbn;
}
```

If your model (`Author`) depends on a model defined in another file (`Book`), then you will need to generate `book.g.dart` before, `author.g.dart`, **in a separate build action**. This way, the analyzer can resolve the `Book` type.

## ID and Dates

This package will automatically generate `id`, `createdAt`, and `updatedAt` fields for you, in the style of an Angel3 `Model`. This will automatically be generated, **only** for classes extending `Model`. Generated classes also get `copyWith`, `==` and `hashCode`.

## Binary Data

`package:angel3_serialize` also handles `Uint8List` fields, by means of serialization to and from `base64` encoding.

## TypeScript Definitions

It is quite common to build frontends with JavaScript and/or TypeScript, so why not generate typings as well?

To accomplish this, add `Serializers.typescript` to your `@Serializable()` declaration:

```dart
@Serializable(serializers: [Serializers.map, Serializers.json, Serializers.typescript])
abstract class FooEntity extends Model {}
```

`Serializers.all` lists all three. An `AuthorEntity` with a required `name` and `age`, and a `LibraryEntity` with a `Map<String, BookEntity> get collection`, generate the following in a `.d.ts` file:

```typescript
interface Author {
  id?: string;
  created_at?: any;
  updated_at?: any;
  name: string;
  age: number;
  books?: Book[];
  newest_book?: Book;
}
interface Library {
  id?: string;
  created_at?: any;
  updated_at?: any;
  collection?: LibraryCollection;
}
interface LibraryCollection {
  [key: string]: Book;
}
```

Excluded fields, such as those with `@exclude` or `@SerializableField(exclude: true)`, will not be present in the TypeScript definition. The rationale for this is that if a field (i.e. `password`) will never be sent to the client, the client shouldn't even know the field exists.

## Constructor Parameters

Sometimes, you may need to have custom constructor parameters, for example, when using dependency injection frameworks. For these cases, `angel3_serialize` can forward custom constructor parameters.

The following:

```dart
@serializable
abstract class BookmarkEntity extends Model {
  @SerializableField(exclude: true)
  final BookEntity book;

  @SerializableField(isNullable: false)
  int? get page;

  String? get comment;

  BookmarkEntity(this.book);
}
```

Generates:

```dart
class Bookmark extends BookmarkEntity {
  Bookmark(
    BookEntity book, {
    this.id,
    this.createdAt,
    this.updatedAt,
    required this.page,
    this.comment,
  }) : super(book);

  @override
  String? id;

  // ...
}
```


# Service Basics

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

## Services

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

The Angel3 core library includes the `Service` base class, as well as two in-memory service classes. Database adapter packages, such as [`package:angel3_mongo`](https://github.com/dart-backend/angel/tree/master/packages/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](/under-the-hood/hooks).

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), the query string is passed in it as `params['query']`, and the body is passed as `data` to `create`, `update` and `modify`. To pass custom parameters to a service, you should create a middleware to do so. `@Middleware` annotations, which need a [reflector](/under-the-hood/dependency-injection#enabling-dart-mirrors-or-other-reflection), 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, ResponseContext res) async {
  req.queryParameters['foo'] = 'bar';
  return true;
}

@Middleware([myMiddleware])
class MyService extends Service {
  // Responds with "['bar']"
  @override
  Future<List> index([Map<String, dynamic>? params]) async => [params!['query']['foo']];
}
```

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

```dart
class MyService extends Service {
  @override
  Future create(data, [Map<String, dynamic>? params]) async {
    if (params == null || params['provider'] == null) {
       // Accessed via server
    }
    return data;
  }
}
```

`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", (req, res) => fetchUserTodos(req.params['id']));

// Another way to apply a middleware to a service; it must return `true`.
app.all('/user/*', someMiddleware);

// `map` turns a service of Maps into one of model classes.
app.use('/user', MongoService(db.collection('users')).map(UserSerializer.fromMap, UserSerializer.toMap));

// Access app services. Returns the HookedService that `use` mounted.
// Leading and trailing slashes are ignored.
var service = app.findService('user'); // The user service
var secrets = app.findServiceOf<String, Map<String, dynamic>>('secret');
```

A service deals with `Map`s. To work with model classes instead, `map` it with the serializer generated by [`angel3_serialize`](/under-the-hood/serialization):

```dart
var todos = app.findServiceOf<String, Map<String, dynamic>>('api/todos')!
    .map(TodoSerializer.fromMap, TodoSerializer.toMap);
Todo todo = await todos.read('1');
```

Ids are parsed from the URL to the service's `Id` type: a `Service<int, ...>` gets an `int`, and an id that cannot be parsed is a `400 Bad Request`.

## Additional Notes

Important things to consider when writing your own service:

* [mongo](https://github.com/dart-backend/angel/blob/master/packages/mongo/lib/mongo_service.dart) is a good reference implementation]
* Services need only worry about handling `Map`s. Object serialization should be handled by `angel3_serialize`, or another serializer, with `Service.map`.
* 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


# Hooks

* [Hooks](#hooks)
* [Next Up...](#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, Angel3 wraps it in a `HookedService` class, and returns it. A `HookedService` fires events before and after its inner service runs. This opens the opportunity for events to be canceled, or have parameters modified.

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

```dart
class HookedService<Id, Data, T extends Service<Id, Data>> extends Service<Id, Data> {
  final HookedServiceEventDispatcher<Id, Data, T> beforeIndexed;
  final HookedServiceEventDispatcher<Id, Data, T> afterIndexed;

  // And so on, for `Read`, `Created`, `Modified`, `Updated` and `Removed`...
}
```

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<Id, Data, T extends Service<Id, Data>> {
  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.
  T service;

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

  /// The `id` passed to this event, if any.
  Id? get id;

  /// The data passed to this event, if any.
  Data? data;

  /// The params of the service method. Although the getter is read-only,
  /// you can still assign values within it.
  Map get params;

  /// The request and response, when the service is called over HTTP.
  RequestContext? get request;
  ResponseContext? get response;

  /// After an event completes, this will hold whatever
  /// value the service method returned.
  dynamic 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([Object? result]);
}
```

```dart
var service = app.findHookedService<TodoService>('api/todos')!;

service.afterCreated.listen((e) {
  // In an `after` hook, `e.result` would be the created data.
  // In this case, it is a Todo object.
  var todo = e.result as Todo;
  if (todo.completed != true) {
    // 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 ${todo.text}!'});
  }
});
```

Alternatively, the `Hooks` annotation can be used to assign hooks to service methods. Annotations are read by reflection, so they need a reflector: `MirrorsReflector`, or generated reflection data with the service marked `@injectable` (see [Dependency Injection](/under-the-hood/dependency-injection#enabling-dart-mirrors-or-other-reflection)). Without one, they are ignored.

```dart
void helloHook(HookedServiceEvent e) => print('Hello, world!');
void fooHook(HookedServiceEvent e) => print('Bar');

@Hooks(before: [helloHook])
class MyService extends Service<String, String> {
  @override
  @Hooks(before: [fooHook])
  Future<List<String>> index([Map<String, dynamic>? params]) async {
    return ['world'];
  }
}
```

## Next Up

Congratulations! Not only have you gotten through the basic Angel3 tutorials, but you've also completed the service tutorials! However, there's still a lot more to Angel3 for you to explore. Check out the sidebar for more! ***Happy coding!***


# Caching

[`angel3_cache`](https://github.com/dart-backend/angel/tree/master/packages/cache) caches responses, and the data of services. [`angel3_redis`](https://github.com/dart-backend/angel/tree/master/packages/redis) stores the data of a service in Redis, which can serve as the cache.

```yaml
dependencies:
  angel3_cache: ^10.0.0
  angel3_redis: ^10.0.0
```

## Caching responses

`ResponseCache` keeps responses of matching paths in memory, and serves them again until they expire. Clients whose copy is still current get `304 Not Modified`, as it supports the `If-Modified-Since` header:

```dart
Future configureServer(Angel app) async {
  // Responses expire after `timeout` (10 minutes by default).
  var cache = ResponseCache(timeout: const Duration(days: 2));

  // Close the cache when the application closes.
  app.shutdownHooks.add((_) => cache.close());

  // The request paths to cache, as any `Pattern`.
  cache.patterns.addAll([
    '/robots.txt',
    RegExp(r'\.(png|jpg|gif|txt)$'),
    RegExp(r'^/public/'),
  ]);

  // REQUIRED: The middleware that serves cached responses
  app.fallback(cache.handleRequest);

  // REQUIRED: The response finalizer that saves responses to the cache
  app.responseFinalizers.add(cache.responseFinalizer);
}
```

Only responses that are safe to share are stored: those to `GET`, with status 200, no cookies, not marked `Cache-Control: no-store`, `no-cache` or `private`, no `Vary` other than `Accept-Encoding`, and at most `maxEntryBytes` (1 MB by default) long. Requests with an `Authorization` header or cookies bypass the cache, so a page of one user's session is not served to others. At most `maxEntries` responses (1024 by default) are kept.

The cache key is the request URI, with its query string. Call `cache.purge(key)` to remove a response from the cache.

## Caching a service

`CacheService` caches the data of one service (`database`) in another (`cache`), such as the results of a database query in Redis:

```dart
app.use(
  '/api/todos',
  CacheService(
    cache: MapService(autoIdAndDateFields: false),
    database: todoService,
    timeout: const Duration(minutes: 10),
  ),
);
```

* Cached results expire after `timeout`, 10 minutes by default.
* A cached read is reused only for the same query; set `ignoreParams: true` to reuse it regardless.
* `modify` and `update` write the new record through to `cache`, and `remove` evicts it, so several instances can share one cache.
* If `cache` fails, reads fall back to `database`.

## Redis

`RedisService` is a service of the records of a Redis database, stored as JSON. It takes a client of [`resp_client`](https://pub.dev/packages/resp_client), and a prefix for its keys:

```dart
import 'package:angel3_redis/angel3_redis.dart';
import 'package:resp_client/resp_client.dart';
import 'package:resp_client/resp_commands.dart';
import 'package:resp_client/resp_server.dart';

Future configureServer(Angel app) async {
  var connection = await connectSocket('localhost');
  var client = RespClient(connection);
  var service = RedisService(RespCommandsTier2(client), prefix: 'todos');

  app.use('/api/todos', service);
  app.shutdownHooks.add((_) => connection.close());
}
```

Redis is a flat key-value store, so give each service its own prefix, or they can overwrite one another's records. Prefixes must not nest: `index` on prefix `app` also returns the records of prefix `app:users`.

As the `cache` of a `CacheService`, a `RedisService` lets several instances of the app share one cache. See the [`angel3_redis` README](https://github.com/dart-backend/angel/tree/master/packages/redis) for how it handles ids and concurrent writes.

## Caching serialization

`cacheSerializationResults` caches the JSON of objects that are sent again and again, such as a precomputed list:

```dart
app.fallback(cacheSerializationResults(
  timeout: const Duration(minutes: 5),
  shouldCache: (req, res, value) => value is List,
));
```

Results are cached per object instance, and held weakly, so the objects can still be garbage-collected.


# HTTP/2

Angel3 serves HTTP/2 with `AngelHttp2`, of `package:angel3_framework/http2.dart`. The same `Angel` app can be served over HTTP/1.1 and HTTP/2, so routes, services and plug-ins need no change.

Browsers only speak HTTP/2 over TLS, so `AngelHttp2` needs a certificate, and ALPN to negotiate the `h2` protocol:

```dart
import 'dart:io';

import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';
import 'package:angel3_framework/http2.dart';

void main() async {
  var app = Angel();
  app.get('/', (req, res) => 'Hello HTTP/2!!!');
  app.fallback((req, res) => throw AngelHttpException.notFound());

  var ctx = SecurityContext()
    ..useCertificateChain('dev.pem')
    ..usePrivateKey('dev.key', password: 'dartdart')
    ..setAlpnProtocols(['h2'], true);

  var http1 = AngelHttp(app);
  var http2 = AngelHttp2(app, ctx);

  // Clients that do not negotiate HTTP/2 are served by `AngelHttp`.
  http2.onHttp1.listen(http1.handleRequest);

  await http2.startServer('127.0.0.1', 3000);
  print('Listening at ${http2.uri}');
}
```

Pass `allowHttp1: true` to `AngelHttp2` to serve HTTP/1.1 clients without an `AngelHttp` of your own.

With `angel3_production`, pass `--http2`, `--certificate-file` and `--key-file` to the `Runner` instead.

## Sessions

An HTTP/2 request gets a session, and the session cookie, only when `req.session` is first read. Code that expects the cookie on every response must read `req.session`.

Sessions are discarded after they have not been used for `sessionTimeout`, 20 minutes by default, like those of `dart:io`'s `HttpServer`:

```dart
var http2 = AngelHttp2(app, ctx, sessionTimeout: const Duration(hours: 1));
```

## Server push

With HTTP/2, the server can push resources that a page will request, before the browser asks for them. The response of an HTTP/2 request is an `Http2ResponseContext`:

```dart
// `streamFile` takes a `File` of `package:file`.
var fs = const LocalFileSystem();
var styleCss = fs.file('web/style.css');
var appJs = fs.file('web/app.js');
var indexHtml = fs.file('web/index.html');

app.get('/', (req, res) async {
  if (res is Http2ResponseContext && res.canPush) {
    await res.push('/style.css').streamFile(styleCss);
    await res.push('/app.js').streamFile(appJs);
  }

  await res.streamFile(indexHtml);
});
```

`canPush` is `false` when the client has disabled server push. The [HTTP/2 examples](https://github.com/dart-backend/angel/tree/master/packages/framework/example/http2) include body parsing and server push.


# Testing

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

## Testing

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

### connectTo

[Full definition](https://pub.dev/documentation/angel3_test/latest/angel3_test/connectTo.html)

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

```dart
void main() {
  late TestClient client;

  setUp(() async {
    var app = Angel()..get('/hello', (req, res) => {'hello': 'world'});
    client = await connectTo(app);
  });

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

  test('hello', () async {
    // This returns an http.Response. :)
    var response = await client.get(Uri.parse('/hello'));
    expect(response, allOf(hasStatus(200), isJson({'hello': 'world'})));
  });
}
```

### 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 `angel3_test` Matchers can be found [here](https://pub.dev/documentation/angel3_test/latest/angel3_test/angel3_test-library.html).

## Next Up

1. Find out how to [handle errors](/under-the-hood/error-handling) in an Angel3 application.
2. Learn how to use the handy [Angel3 CLI](/command-line-interface/cli-setup).


# Error Handling

* [Error Handling](#error-handling)
* [Next Up...](#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. Angel3 provides an `AngelHttpException` class to take care of this.

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

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

Fortunately, Angel3 runs every request in a `try`/`catch`, and gracefully intercepts exceptions. This enables Angel3 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.

Each driver, such as `AngelHttp` or `AngelHttp2`, runs each request in its own `Zone` by default; pass `useZone: false` to turn this off. Malformed requests, such as bad headers or bodies, are answered with a `400 Bad Request`. If a handler fails after the response's headers were sent (`res.headersSent`), the response is aborted, as its status can no longer be changed.

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 Angel3 tutorials. Take what you've learned on a spin in a small side project, and then move on to learning about [services](/under-the-hood/service-basics).


# Pattern Matching and Parameter

`package:angel3_framework` has nice support for injecting values from HTTP headers, query string, and session/cookie values, as well as pattern-matching for request handlers. The values can be of any type the value converts to, such as `int`.

The annotations are read with the app's reflector, so `ioc` handlers that use them need one; see [Enabling `dart:mirrors` or other Reflection](/under-the-hood/dependency-injection#enabling-dart-mirrors-or-other-reflection).

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

Here is a simple example of each of them in action. `ioc` reads the annotations by reflecting on the handler, so these examples need `MirrorsReflector` (see [Dependency Injection](/under-the-hood/dependency-injection#enabling-dart-mirrors-or-other-reflection)):

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

Without a reflector, pass the `Parameter`s to `ioc` in `injection:`, keyed by the name of the handler's parameter:

```dart
app.get('/query', ioc(
  (String query) => query,
  injection: InjectionRequest.constant(
    required: ['query'],
    parameters: {'query': Query('q')},
  ),
));
```

Supports:

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

<https://pub.dev/documentation/angel3_framework/latest/angel3_framework/Parameter-class.html>


# Deployment


# Production Mode

Angel3 can optionally run in "production mode," where several optimizations are applied to the base server, such as running reflective dependency injection before server startup, flattening the server's route tree, and caching the resolved routes of request paths, up to `app.maxHandlerCacheSize` entries.

Production mode is considered a global setting.

`angel3_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.environment.isProduction) {
  // Do some production-only stuff...
}
```

To run the application in several isolates, with respawning and graceful shutdown, use [`angel3_production`](https://pub.dev/packages/angel3_production); see [Running in Isolates](/deployment/running-in-isolates).


# Running in Isolates

A Dart isolate runs on one CPU core. To use more of them, run the server in several isolates, which share one port.

## With `angel3_production`

The `Runner` of [`angel3_production`](https://github.com/dart-backend/angel/tree/master/packages/production), which the starter templates use in `bin/prod.dart`, does this for you. Pass the number of isolates with `-j`:

```bash
dart bin/prod.dart -j 4
```

It also re-spawns isolates that crash, and handles shutdown. `dart bin/prod.dart --help` lists its options.

Each isolate has its own memory, so data kept in memory, such as in a `MapService`, is not shared between them. Keep shared data in a database, and use [`angel3_sync`](https://github.com/dart-backend/angel/tree/master/packages/sync) to share WebSocket events between isolates.

## By hand

To bind several servers to one port, start each with `startShared`, which passes `shared: true` to `HttpServer.bind`:

```dart
var http = AngelHttp.custom(app, startShared);
```

`startSharedSecure(securityContext)` does the same for HTTPS.

Then start a server in each isolate:

```dart
import 'dart:io';
import 'dart:isolate';

import 'package:angel3_framework/angel3_framework.dart';
import 'package:angel3_framework/http.dart';

void main() async {
  var concurrency = Platform.numberOfProcessors;

  // Start child isolates...
  for (var i = 1; i < concurrency; i++) {
    await Isolate.spawn(serverMain, i);
  }

  // ...and a server in the main isolate.
  await serverMain(0);
}

Future<void> serverMain(int id) async {
  var app = Angel();
  var http = AngelHttp.custom(app, startShared);

  app.get('/json', (req, res) => {'hello': 'world'});

  var server = await http.startServer(InternetAddress.anyIPv4, 3000);
  print('Instance #$id listening at http://${server.address.address}:${server.port}');
}
```


# Running in a Container with Podman

Each [starter template](/tutorial/application-setup) includes a `Containerfile`, which runs the app in a rootless container with [Podman](https://podman.io/), and a Compose file in `contrib/deployment/`.

## The image

The `Containerfile` compiles the server into a native executable, and copies it into a `scratch` image, with only the Dart runtime's libraries and the files the server reads:

```dockerfile
# Compile with the Dart SDK.
FROM docker.io/library/dart:stable AS build

WORKDIR /app
COPY pubspec.* ./
RUN dart pub get

COPY . .
RUN dart pub get --offline
RUN dart compile exe bin/prod.dart -o bin/server

# Run with only what the server needs.
FROM scratch
COPY --from=build /runtime/ /
COPY --from=build /app/bin/server /app/bin/server
COPY --from=build /app/config /app/config
COPY --from=build /app/views /app/views
COPY --from=build /app/web /app/web

WORKDIR /app
ENV ANGEL_ENV=production
EXPOSE 3000
# Use -j to set the number of isolates, as -j 4.
CMD ["/app/bin/server", "-p", "3000", "-a", "0.0.0.0"]
```

The server is compiled with `dart compile exe`, so the app must run without `dart:mirrors`, as the templates do. See [Running without `dart:mirrors`](/under-the-hood/running-without-mirrors).

Build and run it:

```bash
podman build -t my_app .
podman run --rm -p 3000:3000 my_app
```

## Podman Compose

`contrib/deployment/compose.yaml` builds the same image, and runs it with a read-only root filesystem, no Linux capabilities and `no-new-privileges`. The templates with a database also start the database, and run the migrations before the server.

It needs [`podman-compose`](https://github.com/containers/podman-compose), or Docker Compose with the Podman socket enabled (`systemctl --user enable --now podman.socket`). From the project's root:

```bash
# Build the image and start the server in the background
podman-compose -f contrib/deployment/compose.yaml up --build -d

# Follow its logs
podman-compose -f contrib/deployment/compose.yaml logs -f

# Stop and remove the container
podman-compose -f contrib/deployment/compose.yaml down
```

Then open <http://localhost:3000>. To publish on another host port, set `APP_PORT`:

```bash
APP_PORT=8080 podman-compose -f contrib/deployment/compose.yaml up --build -d
```

## Notes

* **Secrets**: the image includes `config/`, so its `jwt_secret` values. `angel3 init` generates new ones for a new project, and `angel3 key` generates new ones for an existing project. Keep `config/production.yaml` out of public repositories.
* **Static files**: the files of `web/` are built into the image, so rebuild it (`up --build`) after changing them.
* **Network**: the Compose file publishes the port on `127.0.0.1` only. Change `ports` to `"3000:3000"` to expose it on every interface, or put a reverse proxy, such as [nginx](/deployment/ubuntu-and-nginx), in front.
* **Databases on the host**: in a container, `localhost` is the container itself. For a database on the host machine, Podman names the host `host.containers.internal`. The PostgreSQL template reads it from the `POSTGRES_HOST` environment variable:

  ```bash
  podman run --rm -p 3000:3000 -e POSTGRES_HOST=host.containers.internal my_app
  ```


# 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 = SecurityContext()
    ..useCertificateChain('keys/server.crt')
    ..usePrivateKey('keys/server.key');
var http = AngelHttp.fromSecurityContext(app, context);
```

With `angel3_production`, pass `--ssl`, `--certificate-file` and `--key-file` to the `Runner` instead. To serve HTTP/2, see [HTTP/2](/under-the-hood/http2).

## Redirecting to HTTPS

A single `AngelHttp` instance only corresponds to one `HttpServer` instance. To handle secure requests, while also redirecting insecure users to your HTTPS server, you'll need another server listening at port 80, which redirects each request to its HTTPS counterpart:

```dart
/// Redirect HTTP URL's to their HTTPS counterparts...
Future<void> enforceHttps() async {
  var enforcer = Angel();
  enforcer.fallback((req, res) {
    // The `Host` header, without its port.
    var host = Uri.parse('http://${req.hostname}').host;
    return res.redirect('https://$host${req.uri}', code: 301);
  });

  var http = AngelHttp(enforcer);
  var server = await http.startServer('0.0.0.0', 80);
  print('HTTPS enforcer listening at http://${server.address.address}:${server.port}');
}
```

In production, a reverse proxy such as [nginx](/deployment/ubuntu-and-nginx) often terminates TLS, and redirects plain HTTP, instead of the app.


# Deploying under nginx

This is pretty simple, and doesn't require much in the way of DevOps.

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` a. Don't run your application server as `root` b. Serve static files via `nginx` instead of Angel3
   * 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.


# Deployment to AppEngine

You can use [`package:appengine`](https://pub.dev/packages/appengine) with Angel3 easily, just by passing it your app's `handleRequest` method:

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

void main() async {
  var app = Angel();
  var http = AngelHttp(app);
  // ...

  await runAppEngine(http.handleRequest);
}
```


# Angel Framework Migration


# Angel3 9.x to 10.0


# 10.0.0 Migration Guide

Angel3 10.0.0 requires Dart SDK 3.13 or later. All `angel3_*` packages are released as 10.0.0 together, so upgrade them at the same time.

**WARNING**, backup your existing code, or commit it, before proceeding with migration.

1. Change the SDK constraint in `pubspec.yaml` to `sdk: ^3.13.0`.
2. Change every `angel3_*` dependency to `^10.0.0`, and run `dart pub upgrade`.
3. If the app uses `MirrorsReflector`, add `angel3_container_mirrors: ^10.0.0` to its dependencies, and change the import:

   ```dart
   // 9.x
   import 'package:angel3_container/mirrors.dart';

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

   To compile the app with `dart compile exe` instead, see [Running without `dart:mirrors`](/under-the-hood/running-without-mirrors).
4. Regenerate the generated code, with `dart run build_runner build --delete-conflicting-outputs`. The generators of 10.0.0 write code that the 10.0.0 runtimes need.
5. Go through the breaking changes below, and those of each package the app uses.
6. Run the app's tests.

## Framework

These are the breaking changes of `angel3_framework` that need changes in an app. The [CHANGELOG](https://github.com/dart-backend/angel/blob/master/packages/framework/CHANGELOG.md) lists all of them.

### `chain` stops at the first handler that does not return `true`

Like the handlers of a route, each handler given to `chain` must return `true` for the next one to run. A handler that returns nothing, such as a middleware that only sets a value, now stops the chain:

```dart
// 9.x: `handler` ran after it
chain([(req, res) { req.params['user'] = 'me'; }, handler]);

// 10.0.0
chain([(req, res) { req.params['user'] = 'me'; return true; }, handler]);
```

### Buffered responses send `Content-Length`

A buffered response is sent with a `Content-Length` header instead of chunked transfer encoding. Set `res.chunked = true` to send it chunked.

### Default response headers

`AngelHttp.addResponseHeader` and `removeResponseHeader` take a `Map` of headers:

* `addResponseHeader` throws an `ArgumentError` for a header that cannot be sent, before it adds any of the call's headers.
* `removeResponseHeader` removes each value of a list, every value equal to a given one, and, if none matches exactly, those that match ignoring case, such as `sameorigin` for the `SAMEORIGIN` that `dart:io` adds. A `null` value removes the header whatever its values.

```dart
var http = AngelHttp(app);
http.removeResponseHeader({'X-FRAME-OPTIONS': 'SAMEORIGIN'});
http.removeResponseHeader({'X-XSS-PROTECTION': null});
http.addResponseHeader({'X-XSRF-TOKEN': 'a591a6d4...'});
```

### HTTP/2 sessions

An HTTP/2 request gets a session, and the session cookie, only when `req.session` is first read. Code that expects the cookie on every response must read `req.session`. See [HTTP/2](/under-the-hood/http2).

## Packages

Each package's `README.md` has a "Migrating from 9.x to 10.0.0" section with the changes that may need changes in an app:

| Area                        | Packages                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| --------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Dependency injection        | [container](https://github.com/dart-backend/angel/tree/master/packages/container/container#migrating-from-9x-to-1000), [container\_generator](https://github.com/dart-backend/angel/tree/master/packages/container/container_generator#migrating-from-9x-to-1000)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| Serialization               | [serialize](https://github.com/dart-backend/angel/tree/master/packages/serialize/serialize#migrating-from-9x-to-1000), [serialize\_generator](https://github.com/dart-backend/angel/tree/master/packages/serialize/serialize_generator#migrating-from-9x-to-1000), [model](https://github.com/dart-backend/angel/tree/master/packages/model#migrating-from-9x-to-1000)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ORM                         | [orm](https://github.com/dart-backend/angel/tree/master/packages/orm/orm#migrating-from-9x-to-1000), [orm\_generator](https://github.com/dart-backend/angel/tree/master/packages/orm/orm_generator#migrating-from-9x-to-1000), [orm\_postgres](https://github.com/dart-backend/angel/tree/master/packages/orm/orm_postgres#migrating-from-9x-to-1000), [orm\_mysql](https://github.com/dart-backend/angel/tree/master/packages/orm/orm_mysql#migrating-from-9x-to-1000), [migration](https://github.com/dart-backend/angel/tree/master/packages/orm/migration#migrating-from-9x-to-1000), [migration\_runner](https://github.com/dart-backend/angel/tree/master/packages/orm/migration_runner#migrating-from-9x-to-1000)                                                                                                                                                |
| Databases                   | [mongo](https://github.com/dart-backend/angel/tree/master/packages/mongo#migrating-from-9x-to-1000), [rethinkdb](https://github.com/dart-backend/angel/tree/master/packages/rethinkdb#migrating-from-9x-to-1000), [sembast](https://github.com/dart-backend/angel/tree/master/packages/sembast#migrating-from-9x-to-1000), [file\_service](https://github.com/dart-backend/angel/tree/master/packages/file_service#migrating-from-9x-to-1000), [redis](https://github.com/dart-backend/angel/tree/master/packages/redis#migrating-from-9x-to-1000)                                                                                                                                                                                                                                                                                                                      |
| Authentication and security | [auth](https://github.com/dart-backend/angel/tree/master/packages/auth#migrating-from-9x-to-1000), [auth\_oauth2](https://github.com/dart-backend/angel/tree/master/packages/auth_oauth2#migrating-from-9x-to-1000), [security](https://github.com/dart-backend/angel/tree/master/packages/security#migrating-from-9x-to-1000), [cors](https://github.com/dart-backend/angel/tree/master/packages/cors#migrating-from-9x-to-1000)                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| Views                       | [jael](https://github.com/dart-backend/angel/tree/master/packages/jael/jael#migrating-from-9x-to-1000), [jael\_preprocessor](https://github.com/dart-backend/angel/tree/master/packages/jael/jael_preprocessor#migrating-from-9x-to-1000), [angel\_jael](https://github.com/dart-backend/angel/tree/master/packages/jael/angel_jael#migrating-from-9x-to-1000), [mustache](https://github.com/dart-backend/angel/tree/master/packages/mustache#migrating-from-9x-to-1000), [jinja](https://github.com/dart-backend/angel/tree/master/packages/jinja#migrating-from-9x-to-1000), [markdown](https://github.com/dart-backend/angel/tree/master/packages/markdown#migrating-from-9x-to-1000), [html](https://github.com/dart-backend/angel/tree/master/packages/html#migrating-from-9x-to-1000)                                                                            |
| Clients and real time       | [client](https://github.com/dart-backend/angel/tree/master/packages/client#migrating-from-9x-to-1000), [websocket](https://github.com/dart-backend/angel/tree/master/packages/websocket#migrating-from-9x-to-1000)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| Other                       | [cache](https://github.com/dart-backend/angel/tree/master/packages/cache#migrating-from-9x-to-1000), [static](https://github.com/dart-backend/angel/tree/master/packages/static#migrating-from-9x-to-1000), [hot](https://github.com/dart-backend/angel/tree/master/packages/hot#migrating-from-9x-to-1000), [production](https://github.com/dart-backend/angel/tree/master/packages/production#migrating-from-9x-to-1000), [paginate](https://github.com/dart-backend/angel/tree/master/packages/paginate#migrating-from-9x-to-1000), [validate](https://github.com/dart-backend/angel/tree/master/packages/validate#migrating-from-9x-to-1000), [test](https://github.com/dart-backend/angel/tree/master/packages/test#migrating-from-9x-to-1000), [mock\_request](https://github.com/dart-backend/angel/tree/master/packages/mock_request#migrating-from-9x-to-1000) |


# Angel 2.x.x to Angel3


# Rationale - Why a new Version?

Starting with Dart SDK 2.12.0, NNBD support becomes mandatory in most of the packages. In order to keep up, Angel3 framework has to undergo a major refactoring to support NNBD.


# 3.0.0 Migration Guide

**WARNING**, backup your existing code before proceeding with migration as the process cannot be reversed. Angel project can be upgraded to Angel3 by following the steps below:

1. Run `dart pub outdated --mode=null-safety`. Make sure all the packages **except** `angel_*` are upgradable.
2. Check that all `angel_*` packages can be upgraded by referring to [Migrated Angel3 Packages](https://github.com/dart-backend/angel/wiki/Migrated-Angel3-Packages).
3. Upgrade all `angel_*` packages manually in `pubspec.yml` by referring to [Angel3 Basic Starter Template](https://github.com/dart-backend/boilerplates/blob/v6/angel3-basic/pubspec.yaml) or [Angel3 ORM Starter Template](https://github.com/dart-backend/boilerplates/blob/v6/angel3-orm/pubspec.yaml)
4. Run `dart pub upgrade --null-safety` to upgrade the rest of the packages automatically.
5. Run `dart migrate` to do the migration.
6. Fix and resolve NNBD related warnings and errors in the code.
7. Replace all `angel_*` packages in `pubspec.yml` with `angel3_*` equivalent by referring to [Migrated Angel3 Packages](https://github.com/dart-backend/angel/wiki/Migrated-Angel3-Packages).
8. Fix and resolve import errors in your project by updating them to `angel3_*` packages.


# Angel 1.x.x to 2.x.x


# 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.dev/packages/angel\\_framework/versions/1.1.1/changelog>

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


# Packages


# Dependency Injection


# Databases


# Templates and Views


# Caching


# Serialization


# Testing


# Resources


# Changelog

## 10.0.0

* Updated guides for Angel3 10.0.0 and Dart SDK 3.13 or later
* Updated code samples for `angel3_container_mirrors`, `StaticReflector`, `ioc` with `injection:`, `chain` and `Entity` models
* Updated ORM guides for `postgres` 3.x, MySQL and MariaDB, and relations loaded with a query each
* Updated links to `dart-backend` repositories, and rebuilt the package list
* Added the 10.0.0 migration guide, and guides for running without `dart:mirrors`, HTTP/2, request limits, hooks, caching, Jinja, SEO, Sembast, Kelicap and Podman
* Added the tutorial pages from application setup to deployment, and the CLI commands
* Updated deployment guides for isolates and SSL
* Updated the ORM guides for PostgreSQL 16 or later
* Updated the PostgreSQL sample to match the PostgreSQL ORM template: the executor reconnects when the database restarts, closes at shutdown, and the `POSTGRES_HOST`, `POSTGRES_USERNAME` and `POSTGRES_PASSWORD` environment variables override the configuration
* Updated the dependency snippets of the ORM guides to list `postgres` and `optional`, which the samples import
* Added the MySQL and MariaDB guide to the menu
* Fixed the controllers, ORM basics, migrations and PostgreSQL guides, which showed merge conflict markers

## 6.0.0

* Updated guides

## 4.0.0

* Updated guides to use `angel3_` packages


