In-depth
The tour demonstrates many of Conduit's features.

Command-Line Interface (CLI)

The conduit command line tool creates, runs and documents Conduit applications; manages database migrations; and manages OAuth client identifiers. Install by running pub global activate conduit on a machine with Dart installed.
Create and run an application:
1
conduit create my_app
2
cd my_app/
3
conduit serve
Copied!

Initialization

A Conduit application starts at an ApplicationChannel. You subclass it once per application to handle initialization tasks like setting up routes and database connections. An example application looks like this:
1
import 'package:conduit/conduit.dart';
2
3
class TodoApp extends ApplicationChannel {
4
ManagedContext context;
5
6
@override
7
Future prepare() async {
8
context = ManagedContext(...);
9
}
10
11
@override
12
Controller get entryPoint {
13
final router = Router();
14
15
router
16
.route("/projects/[:id]")
17
.link(() => ProjectController(context));
18
19
return router;
20
}
21
}
Copied!

Routing

A router determines which controller object should handle a request. The route specification syntax is a concise syntax to construct routes with variables and optional segments in a single statement.
1
@override
2
Controller get entryPoint {
3
final router = Router();
4
5
// Handles /users, /users/1, /users/2, etc.
6
router
7
.route("/projects/[:id]")
8
.link(() => ProjectController());
9
10
// Handles any route that starts with /file/
11
router
12
.route("/file/*")
13
.link(() => FileController());
14
15
// Handles the specific route /health
16
router
17
.route("/health")
18
.linkFunction((req) async => Response.ok(null));
19
20
return router;
21
}
Copied!

Controllers

Controllers handle requests. A controller handles a request by overriding its handle method. This method either returns a response or a request. If a response is returned, that response is sent to the client. If the request is returned, the linked controller handles the request.
1
class SecretKeyAuthorizer extends Controller {
2
@override
3
Future<RequestOrResponse> handle(Request request) async {
4
if (request.raw.headers.value("x-secret-key") == "secret!") {
5
return request;
6
}
7
8
return Response.badRequest();
9
}
10
}
Copied!
This behavior allows for middleware controllers to be linked together, such that a request goes through a number of steps before it is finally handled.
All controllers execute their code in an exception handler. If an exception is thrown in your controller code, a response with an appropriate error code is returned. You subclass HandlerException to provide error response customization for application-specific exceptions.

ResourceControllers

ResourceControllers are the most often used controller. Each operation - e.g. POST /projects, GET /projects and GET /projects/1 - is mapped to methods in a subclass. Parameters of those methods are annotated to bind the values of the request when the method is invoked.
1
import 'package:conduit/conduit.dart'
2
3
class ProjectController extends ResourceController {
4
@Operation.get('id')
5
Future<Response> getProjectById(@Bind.path("id") int id) async {
6
// GET /projects/:id
7
return Response.ok(...);
8
}
9
10
@Operation.post()
11
Future<Response> createProject(@Bind.body() Project project) async {
12
// POST /project
13
final inserted = await insertProject(project);
14
return Response.ok(inserted);
15
}
16
17
@Operation.get()
18
Future<Response> getAllProjects(
19
@Bind.header("x-client-id") String clientId,
20
{@Bind.query("limit") int limit: 10}) async {
21
// GET /projects
22
return Response.ok(...);
23
}
24
}
Copied!

ManagedObjectControllers

ManagedObjectController<T>s are ResourceControllers that automatically map a REST interface to database queries; e.g. POST inserts a row, GET gets all row of a type. They do not need to be subclassed, but can be to provide customization.
1
router
2
.route("/users/[:id]")
3
.link(() => ManagedObjectController<Project>(context));
Copied!

Configuration

An application's configuration is written in a YAML file. Each environment your application runs in (e.g., locally, under test, production, development) has different values for things like the port to listen on and database connection credentials. The format of a configuration file is defined by your application. An example looks like:
1
// config.yaml
2
database:
3
host: api.projects.com
4
port: 5432
5
databaseName: project
6
port: 8000
Copied!
Subclass Configuration and declare a property for each key in your configuration file:
1
class TodoConfig extends Configuration {
2
TodoConfig(String path) : super.fromFile(File(path));
3
4
DatabaseConfiguration database;
5
int port;
6
}
Copied!
The default name of your configuration file is config.yaml, but can be changed at the command-line. You create an instance of your configuration from the configuration file path from your application options:
1
import 'package:conduit/conduit.dart';
2
3
class TodoApp extends ApplicationChannel {
4
@override
5
Future prepare() async {
6
var options = TodoConfig(options.configurationFilePath);
7
...
8
}
9
}
Copied!

Running and Concurrency

Conduit applications are run with the conduit serve command line tool. You can attach debugging and instrumentation tools and specify how many threads the application should run on:
1
conduit serve --observe --isolates 5 --port 8888
Copied!
Conduit applications are multi-isolate (multi-threaded). Each isolate runs a replica of the same web server with its own set of services like database connections. This makes behavior like database connection pooling implicit.

PostgreSQL ORM

The Query<T> class configures and executes database queries. Its type argument determines what table is to be queried and the type of object you will work with in your code.
1
import 'package:conduit/conduit.dart'
2
3
class ProjectController extends ResourceController {
4
ProjectController(this.context);
5
6
final ManagedContext context;
7
8
@Operation.get()
9
Future<Response> getAllProjects() async {
10
final query = Query<Project>(context);
11
12
final results = await query.fetch();
13
14
return Response.ok(results);
15
}
16
}
Copied!
Configuration of the query - like its WHERE clause - are configured through a fluent, type-safe syntax. A property selector identifies which column of the table to apply an expression to. The following query fetches all project's due in the next week and includes their tasks by joining the related table.
1
final nextWeek = DateTime.now().add(Duration(days: 7));
2
final query = Query<Project>(context)
3
..where((project) => project.dueDate).isLessThan(nextWeek)
4
..join(set: (project) => project.tasks);
5
final projects = await query.fetch();
Copied!
Rows are inserted or updated by setting the statically-typed values of a query.
1
final insertQuery = Query<Project>(context)
2
..values.name = "Build an conduit"
3
..values.dueDate = DateTime(year, month);
4
var newProject = await insertQuery.insert();
5
6
final updateQuery = Query<Project>(context)
7
..where((project) => project.id).equalTo(newProject.id)
8
..values.name = "Build a miniature conduit";
9
newProject = await updateQuery.updateOne();
Copied!
Query<T>s can perform sorting, joining and paging queries.
1
final overdueQuery = Query<Project>(context)
2
..where((project) => project.dueDate).lessThan(DateTime().now())
3
..sortBy((project) => project.dueDate, QuerySortOrder.ascending)
4
..join(object: (project) => project.owner);
5
6
final overdueProjectsAndTheirOwners = await query.fetch();
Copied!
Controllers will interpret exceptions thrown by queries to return an appropriate error response to the client. For example, unique constraint conflicts return 409, missing required properties return 400 and database connection failure returns 503.

Defining a Data Model

To use the ORM, you declare your tables as Dart types and create a subclass of ManagedObject<T>. A subclass maps to a table in the database, each instance maps to a row, and each property is a column. The following declaration will map to a table named _project with columns id, name and dueDate.
1
class Project extends ManagedObject<_Project> implements _Project {
2
bool get isPastDue => dueDate.difference(DateTime.now()).inSeconds < 0;
3
}
4
5
class _Project {
6
@primaryKey
7
int id;
8
9
@Column(indexed: true)
10
String name;
11
12
DateTime dueDate;
13
}
Copied!
Managed objects have relationships to other managed objects. Relationships can be has-one, has-many and many-to-many. A relationship is always two-sided - the related types must declare a property that references each other.
1
class Project extends ManagedObject<_Project> implements _Project {}
2
class _Project {
3
...
4
5
// Project has-many Tasks
6
ManagedSet<Task> tasks;
7
}
8
9
class Task extends ManagedObject<_Task> implements _Task {}
10
class _Task {
11
...
12
13
// Task belongs to a project, maps to 'project_id' foreign key column
14
@Relate(#tasks)
15
Project project;
16
}
Copied!
ManagedObject<T>s are serializable and can be directly read from a request body, or encoded as a response body.
1
class ProjectController extends ResourceController {
2
@Operation.put('id')
3
Future<Response> updateProject(@Bind.path('id') int projectId, @Bind.body() Project project) async {
4
final query = Query<Project>(context)
5
..where((project) => project.id).equalTo(projectId)
6
..values = project;
7
8
return Response.ok(await query.updateOne());
9
}
10
}
Copied!

Database Migrations

The CLI will automatically generate database migration scripts by detecting changes to your managed objects. The following, when ran in a project directory, will generate and execute a database migration.
1
conduit db generate
2
conduit db upgrade --connect postgres://user:[email protected]:5432/database
Copied!
You can edit migration files by hand to alter any assumptions or enter required values, and run conduit db validate to ensure the changes still yield the same schema. Be sure to keep generated files in version control.

OAuth 2.0

An OAuth 2.0 server implementation handles authentication and authorization for Conduit applications. You create an AuthServer and its delegate as services in your application. The delegate is configurable and manages how tokens are generated and stored. By default, access tokens are a random 32-byte string and client identifiers, tokens and access codes are stored in your database using the ORM.
1
import 'package:conduit/conduit.dart';
2
import 'package:conduit/managed_auth.dart';
3
4
class AppApplicationChannel extends ApplicationChannel {
5
AuthServer authServer;
6
ManagedContext context;
7
8
@override
9
Future prepare() async {
10
context = ManagedContext(...);
11
12
final delegate = ManagedAuthDelegate<User>(context);
13
authServer = AuthServer(delegate);
14
}
15
}
Copied!
Built-in authentication controllers for exchanging user credentials for access tokens are named AuthController and AuthCodeController. Authorizers are middleware that require a valid access token to access their linked controller.
1
Controller get entryPoint {
2
final router = Router();
3
4
// POST /auth/token with username and password (or access code) to get access token
5
router
6
.route("/auth/token")
7
.link(() => AuthController(authServer));
8
9
// GET /auth/code returns login form, POST /auth/code grants access code
10
router
11
.route("/auth/code")
12
.link(() => AuthCodeController(authServer));
13
14
// ProjectController requires request to include access token
15
router
16
.route("/projects/[:id]")
17
.link(() => Authorizer.bearer(authServer))
18
.link(() => ProjectController(context));
19
20
return router;
21
}
Copied!
The CLI has tools to manage OAuth 2.0 client identifiers and access scopes.
1
conduit auth add-client \
2
--id com.app.mobile \
3
--secret foobar \
4
--redirect-uri https://somewhereoutthere.com \
5
--allowed-scopes "users projects admin.readonly"
Copied!

Logging

All requests are logged to an application-wide logger. Set up a listener for the logger in ApplicationChannel to write log messages to the console or another medium.
1
class WildfireChannel extends ApplicationChannel {
2
@override
3
Future prepare() async {
4
logger.onRecord.listen((record) {
5
print("$record");
6
});
7
}
8
}
Copied!

Testing

Conduit tests start a local version of your application and execute requests. You write expectations on the responses. A TestHarness manages the starting and stopping of an application, and exposes a default Agent for executing requests. An Agent can be configured to have default headers, and multiple agents can be used within the same test.
1
import 'harness/app.dart';
2
3
void main() {
4
final harness = TestHarness<TodoApp>()..install();
5
6
test("GET /projects returns all projects" , () async {
7
var response = await harness.agent.get("/projects");
8
expectResponse(response, 200, body: every(partial({
9
"id": greaterThan(0),
10
"name": isNotNull,
11
"dueDate": isNotNull
12
})));
13
});
14
}
Copied!

Testing with a Database

Conduit's ORM uses PostgreSQL as its database. Before your tests run, Conduit will create your application's database tables in a local PostgreSQL database. After the tests complete, it will delete those tables. This allows you to start with an empty database for each test suite as well as control exactly which records are in your database while testing, but without having to manage database schemas or use an mock implementation (e.g., SQLite).
This behavior, and behavior for managing applications with an OAuth 2.0 provider, are available as harness mixins.

Documentation

OpenAPI documents describe your application's interface. These documents can be used to generate documentation and client code. A document can be generated by reflecting on your application's codebase, just run the conduit document command.
The conduit document client command creates a web page that can be used to configure issue requests specific to your application.
Last modified 4mo ago