Table of Contents
- Preface
- Introduction
- Conduit
- Contexts
- Getting started
-
Accounts
-
Register a user
- Building our first context
- Writing our first integration test
- Application structure
- Alternate structure
- Building our first aggregate
- Building our first command
- Building our first domain event
- Writing our first unit test
- Command dispatch and routing
- Writing our first read model projection
- Validating dispatched commands
- Testing user registration validation
- Enforce unique usernames
- Additional username validation
- Validating a user’s email address
- Hashing the user’s password
- Completing user registration
-
Register a user
- Authentication
-
Articles
- Publishing an article
- Listing articles
- Get an article
-
Favorite articles
- Favorite integration test
- Article routing
- Favorite article controller
- Favorite articles in Blog context
- Favorite commands and events
- Favorite article aggregate handling
- Unit testing favorites in the article aggregate
- Routing favorite commands
- Projecting favorite articles in the read model
- Favorite articles test
- Filter by favorite articles
- Tags
- Frequently asked questions
- Appendix I
- Notes
Preface
Welcome to Building Conduit.
In this book you will discover how to implement the Command Query Responsibility Segregation and event sourcing (CQRS/ES) pattern in an Elixir application.
This book will take you through the design and build, from scratch, of an exemplary Medium.com clone. The full source code is available to view and clone from GitHub. As each feature is developed, a link to the corresponding Git commit will be provided so you can browse the source code at each stage of development.
The application will be built as if it were a real world project. Including the specification of integration and unit tests to verify the functionality under development.
By the end of this book you should have a solid grasp of how to apply the CQRS/ES pattern to your own Elixir applications.
You will learn how to:
- Follow test-driven development to build an HTTP API exposing and consuming JSON data.
- Validate input data using command validation.
- Create a functional, event sourced domain model.
- Define a read model and populate it by projecting domain events.
- Authenticate a user using a JSON Web Token (JWT).
Introduction
Who is Building Conduit for?
This book is written for anyone who has an interest in CQRS/ES and Elixir.
It assumes the reader will already be familiar with the broad concepts of CQRS/ES. You will be introduced to the building blocks that comprise an application built following this pattern, and shown how to implement them in Elixir.
The reader should be comfortable reading Elixir syntax and understand the basics of its actor concurrency model, implemented as processes and message passing.
What does it cover?
You will learn an approach to implementing the CQRS/ES pattern in a real world Elixir application. You will build a Medium.com clone, called Conduit, using the Phoenix web framework. Conduit is a real world blogging platform allowing users to publish articles, follow authors, and browse and read articles.
The inspiration for this example web application comes from the RealWorld project:
See how the exact same Medium.com clone (called Conduit) is built using any of our supported frontends and backends. Yes, you can mix and match them, because they all adhere to the same API spec.
While most “todo” demos provide an excellent cursory glance at a framework’s capabilities, they typically don’t convey the knowledge & perspective required to actually build real applications with it.
RealWorld solves this by allowing you to choose any frontend (React, Angular 2, & more) and any backend (Node, Django, & more) and see how they power a real world, beautifully designed fullstack app called “Conduit”.
By building a backend in Elixir and Phoenix that adheres to the RealWorld API specs, you can choose to pair it with any of the available frontends. Some of the most popular current implementations are:
You can view a live demo of Conduit that’s powered by React and Redux with a Node.js backend, to get a feel for what we’ll be building.
Many thanks to Eric Simons for pioneering the idea and founding the RealWorld project.
Before we start building Conduit, let’s briefly cover some of the concepts related to command query responsibility segregation and event sourcing.
What is CQRS?
At its simplest, CQRS is the separation of commands from queries.
- Commands are used to mutate state in a write model.
- Queries are used to retrieve a value from a read model.
In a typical layered architecture you have a single model to service writes and reads, whereas in a CQRS application the read and write models are different. They may also be separated physically by using a different database or storage mechanism. CQRS is often combined with event sourcing where there’s an event store for persisting domain events (write model) and at least one other data store for the read model.
Commands
Commands are used to instruct an application to do something, they are named in the imperative:
- Register account
- Transfer funds
- Mark fraudulent activity
Commands have one, and only one, receiver: the code that fulfils the command request.
Domain events
Domain events indicate something of importance has occurred within a domain model. They are named in the past tense:
- Account registered
- Funds transferred
- Fraudulent activity detected
Domain events describe your system activity over time using a rich, domain-specific language. They are an immutable source of truth for the system. Unlike commands which are restricted to a single handler, domain events may be consumed by multiple subscribers - or potentially no interested subscribers.
Often commands and events come in pairs: a successful register account command results in an account registered event. It’s also possible that a command can be successfully executed and result in many or no domain events.
Queries
Domain events from the write model are used to build and update a read model. I refer to this process as projecting events into a read model projection.
The read model is optimised for querying therefore the data is often stored denormalized to support faster querying performance. You can use whatever technology is most appropriate to support the querying your application demands, and take advantage of multiple different types of storage as appropriate:
- Relational database.
- In-memory store.
- Disk-based file store.
- NoSQL database.
- Full-text search index.
What is event sourcing?
Any state changes within your domain are driven by domain events. Therefore your entire application’s state changes are modelled as a stream of domain events:
An aggregate’s state is built by applying its domain events to some initial empty state. State is further mutated by applying a created domain to the current state:
Domain events are persisted in order – as a logical stream – for each aggregate. The event stream is the canonical source of truth, therefore it is a perfect audit log.
All other state in the system may be rebuilt from these events. Read models are projections of the event stream. You can rebuild the read model by replaying every event from the beginning of time.
What are the costs of using CQRS?
Domain events provide a history of your poor design decisions and they are immutable.
It’s an alternative, and less common, approach to building applications than basic CRUD1. Modelling your application using domain events demands a rich understanding of the domain. It can be more complex to deal with the eventual consistency between the write model and the read model.
Recipe for building a CQRS/ES application in Elixir
- A domain model containing aggregates, commands, and events.
- Hosting of an aggregate root instance and a way to send it commands.
- An event store to persist the created domain events.
- A Read model store for querying.
- Event handlers to build and update the read model.
- An API to query the read model data and to dispatch commands to the write model.
An aggregate
An aggregate defines a consistency boundary for transactions and concurrency. Aggregates should also be viewed from the perspective of being a “conceptual whole”. They are used to enforce invariants in a domain model and to guard against business rule violations.
This concept fits naturally within Elixir’s actor concurrency model. An Elixir GenServer
enforces serialised concurrent access and processes communicate by sending messages (commands and events).
An event sourced aggregate
Must adhere to these rules:
- Public API functions must accept a command and return any resultant domain events, or an error.
- Its internal state may only be modified by applying a domain event to its current state.
- Its internal state can be rebuilt from an initial empty state by replaying all domain events in the order they were raised.
Here’s an example event sourced aggregate in Elixir:
It is preferable to implement aggregates using pure functions2. Why might this be a good rule to follow? Because a pure function is highly testable: you will focus on behaviour rather than state.
By using pure functions in your domain model, you also decouple your domain from the framework’s domain. Allowing you to build your application separately first, and layer the external interface on top. The external interface in our application will be the RESTful API powered by Phoenix.
Unit testing an aggregate
An aggregate function can be tested by executing a command and verifying the expected events are returned.
The following example demonstrates a BankAccount
aggregate being tested for opening an account:
Conduit
Conduit is a social blogging site: it is a Medium.com clone.
You can view a live demo at: demo.realworld.io
General functionality
As a blogging platform, Conduit’s functionality is based around authors publishing articles.
- Authenticate users via JWT3.
- Register, view, and update users.
- Publish, edit, view, and delete articles.
- Create, view, and delete comments on articles.
- Display paginated lists of articles.
- Favourite articles.
- Follow other users.
API specs
Conduit uses a custom REST API for all requests, including authentication.
We will be implementing a backend that must adhere to the Conduit API specs.
HTTP verb | URL | Action | |
---|---|---|---|
POST | /api/users/login | Login a user | |
POST | /api/users | Register a user | |
GET | /api/user | Get current user | |
PUT | /api/user | Update current user | |
GET | /api/profiles/:username | Get profile | |
POST | /api/profiles/:username/follow | Follow user | |
DELETE | /api/profiles/:username/follow | Unfollow user | |
GET | /api/articles | List articles | |
GET | /api/articles/feed | Feed articles | |
GET | /api/articles/:slug | Get an article | |
POST | /api/articles | Publish an article | |
PUT | /api/articles/:slug | Update an article | |
DELETE | /api/articles/:slug | Remove an article | |
POST | /api/articles/:slug/comments | Comment on an article | |
GET | /api/articles/:slug/comments | Get comments on an article | |
DELETE | /api/articles/:slug/comments/:id | Remove an comment | |
POST | /api/articles/:slug/favorite | Favorite an article | |
DELETE | /api/articles/:slug/favorite | Unfavorite an article | |
GET | /api/tags | Get tags |
The full API specs are detailed in Appendix I.
Contexts
Phoenix 1.3 introduces the concept of contexts. These are somewhat inspired by bounded contexts in domain-driven design. They provide a way of defining clear boundaries between parts of your application. A context defines a public API that should be consumed by the rest of the application.
Bounded Context is a central pattern in Domain-Driven Design. It is the focus of DDD’s strategic design section which is all about dealing with large models and teams. DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their interrelationships.
Contexts in Phoenix
When using the included phx.gen.*
generators you must provide an additional context argument for each resource you create. As an example, when generating a JSON resource:
The first argument is the context module followed by the schema module and its plural name (used as the schema table name). The context is an Elixir module that serves as an API boundary for the given resource. A context often holds many related resources. It is a module, with some implementation modules behind it, that exposes a public interface the rest of your application can consume.
This is powerful, because now you can define clear boundaries for your application domains. You’re now implementing your application, containing your business logic, separate from the Phoenix web interface. The web interface is merely one of the possible consumers of the API exposed by your application using a context module.4
The official Phoenix documentation has a guide detailing Contexts in further detail.5
Contexts in Conduit
Given the features that we plan to implement in Conduit specified in the previous chapter, we can define the following contexts to provide a boundary for each part of our application.
Accounts | Register users, find user by username. |
Auth | Authenticate users. |
Blog | Publish articles, browse a paginated list of articles, comment on articles, favourite articles. |
Why would we separate the Conduit functionality into three contexts? To keep the responsibilities cohesive within each context. For example the responsibility of our Accounts context is to manage users and their credentials, not handle publishing articles. Therefore we have a blog context, separate from accounts, to publish and list articles.
Contexts have their own folder within lib/conduit
which immediately shows at a high level what the Conduit app does and allows easy navigation to help locate modules and files related to a specific area of functionality.
lib/conduit/accounts
lib/conduit/auth
lib/conduit/blog
With this separation of concerns enforced at the directory structure, when I need to add a feature related to blogging, or fix a bug for articles, I can immediately focus on the lib/conduit/blog
folder and its contained modules. This reduces the cognitive load when working with the code.
These contexts would provide public API functions such as:
Accounts
Accounts.register_user/1
Auth
Auth.authenticate/2
Blog
Blog.publish_article/1
Blog.list_articles/1
Getting started
Let’s start building our Conduit web application. We’ll be using the latest version of the Phoenix Web framework, currently 1.3.
Before proceeding you will need to have Elixir v1.5 or later installed. Please follow the official installation guide to get Elixir running on your operating system. There are instructions for Windows, Mac OS X, Linux, Docker, and Raspberry Pi.
Installing Phoenix
Install the latest version of Phoenix using the mix
command:
Generating a Phoenix project
Once installed, you use the mix phx.new
command to create a new Phoenix 1.3 project:
A project in the conduit
directory will be created.
The application name and module name have been specified using the --app
and --module
flags respectively. The Conduit frontend will be provided by one of the existing frameworks so we omit Phoenix’s HTML and static asset support, provided by Brunch, by appending --no-brunch --no-html
to the generator command.
We will temporarily comment out the Ecto repo, Conduit.Repo
, in the main Conduit application, to allow the server to be started without a database. We can also take the opportunity to remove Phoenix’s pub/sub dependency and channels/sockets as they will not be used for our RESTful API.
Starting the Phoenix server
Fetch mix dependencies and compile:
Run the Phoenix server:
Visit http://localhost:4000/ in a browser to check the server is running. An error is shown as no routes have been defined yet.
Commanded facilitates CQRS/ES in Elixir
We will use Commanded6 to build our Elixir application following the CQRS/ES pattern. Commanded is an open source library that contains the building blocks required to implement CQRS/ES in Elixir.
It provides support for:
- Command registration and dispatch.
- Hosting and delegation to aggregates.
- Event handling.
- Long running process managers.
You can use Commanded with one of the following event stores for persistence:
- EventStore Elixir library, using PostgreSQL for persistence.
- Greg Young’s Event Store.
Your choice of event store has no affect on how you build your application.
For Conduit we will use the PostgreSQL based Elixir EventStore as we will also be using PostgreSQL for our read model store and the Ecto database query library.
Write and read model stores
Applications applying the CQRS pattern have a logical separation between the write and read models. You can choose to make these physically separated by using an alternative database, schema, or storage mechanism for each.
In Conduit, we will be using event sourcing to persist domain events created by our write model. These events are the canonical source of truth for our application, they are used by both the aggregates to rebuild their state and are projected into the read model store for querying. Since the read model is a projection built from all domain events in the event store, we can rebuild it from scratch at any time. To rebuild a read store, the database is recreated and then populated by projecting all of the domain events.
We will use two databases for Conduit: one for the event store; another for the read model.
The database naming convention is to suffix the storage type (event store or read store) and environment name to the application name (conduit):
Environment | Event store database | Read store database |
---|---|---|
dev | conduit_eventstore_dev |
conduit_readstore_dev |
test | conduit_eventstore_test |
conduit_readstore_test |
prod | conduit_eventstore_prod |
conduit_readstore_prod |
Installing and configuring Commanded
We’ll be using the following open source libraries, published to Hex, to help build Conduit:
-
commanded
- used to build Elixir applications following the CQRS/ES pattern. -
eventstore
- an Elixir event store using PostgreSQL as the underlying storage engine. -
commanded_eventstore_adapter
- adapter to use EventStore with Commanded.
The Commanded README details the steps required to install and configure the library.
- Add
commanded
andcommanded_eventstore_adapter
to the list of dependencies in mix.exs: - Include
:eventstore
in the list of extra applications inmix.exs
: - Configure Commanded to use the EventStore adapter in the mix config file (
config/config.exs
): - Configure the event store database in each environment’s mix config file (e.g.
config/dev.exs
): - Fetch and compile the dependencies:
- Create the event store database and tables using the mix task:
Configuring the read model store
Ecto will be used for building and querying the read model. The Phoenix generator will have already included the phoenix_ecto
dependency, which includes ecto
, and generated config settings for each environment.
- Configure the
Conduit.Repo
Ecto repository database in each environment’s mix config file (e.g.config/dev.exs
): - Create the read store database:
There are now two databases in our development environment:
- Read model store,
conduit_readstore_dev
, containing only the Ecto schema migrations table. - An event store,
conduit_eventstore_dev
, containing the default event store tables.
Accounts
The Conduit blogging platform requires authors to register an account before they can publish articles. We shall begin our first feature by implementing user registration in the accounts context.
Register a user
The API spec for registration is as follows:
HTTP verb | URL | Required fields |
---|---|---|
POST | /api/users | email, username, password |
Example request body:
Example response body:
The request should fail with a 422
HTTP status code error should any of the required fields be invalid. In this case the response body would be in the following format:
We must ensure that usernames are unique and cannot be registered more than once.
Building our first context
Phoenix includes a set of generators to help scaffold your application:
Command | Action |
---|---|
mix phx.gen.channel |
Generates a Phoenix channel |
mix phx.gen.context |
Generates a context with functions around an Ecto schema |
mix phx.gen.embedded |
Generates an embedded Ecto schema file |
mix phx.gen.html |
Generates controller, views, and context for an HTML resource |
mix phx.gen.json |
Generates controller, views, and context for a JSON resource |
mix phx.gen.presence |
Generates a Presence tracker |
mix phx.gen.schema |
Generates an Ecto schema and migration file |
mix phx.gen.secret |
Generates a secret |
Since we’re building a REST API, we can use the phx.gen.json
generator to create our first context, resource, controller, and JSON view. As we already know the fields relating to our users we can include them, with their type, in the generator command:
Overall, this generator will add the following files to lib/conduit
:
- Context module in
lib/conduit/accounts/accounts.ex
, serving as the API boundary. - Ecto schema in
lib/conduit/accounts/user.ex
, and a database migration to create theaccounts_users
table. - View in
lib/conduit_web/views/user_view.ex
. - Controller in
lib/conduit_web/controllers/user_controller.ex
. - Unit and integration tests in
test/conduit/accounts
.
Remember that the User
module we’re creating here is not our domain model. It will be a read model projection, populated by domain events published from an aggregate.
The generator prompts us to add the resource to the :api
scope in our Phoenix router module. For now, we will configure only the :create
controller action to support registering a user:
Writing our first integration test
Let’s follow Behaviour Driven Development (BDD), thinking “from the outside in”, and start by writing a failing integration test for user registration. We will include tests that cover the happy path of successfully creating a user, and for the two failure scenarios mentioned above: missing required fields and duplicate username registration.
Factories to construct test data
We will use factory functions to generate realistic data for our tests. ExMachina is an Elixir library that makes it easy to create test data and associations.
In mix.exs
, add :ex_machina
as a test environment dependency:
Fetch mix dependencies and compile:
We must ensure the ExMachina application is started in the test helper, test/test_helper.exs
, before ExUnit:
Now we create our factory module in test/support/factory.ex
:
In our test module, we must import Conduit.Factory
to access our user factory. Then we have access to build/1
and build/2
functions to construct params for an example user to register:
build(:user)
build(:user, username: "ben")
User registration integration test
In our integration test we want to verify successful user registration and check any failure includes a useful error message to help the user identify the problem.
- To test success, we assert that the returned HTTP status code is
201
and JSON response matches the API: - To test a validation failure, we assert the response is
422
and errors are included:
The full integration test is given below:
Before running these tests, we must create the event store and read store databases for the test environment:
Then we can execute our registration integration test using the mix test
command:
The execution result of running these tests will be:
Great, we have three failing tests. We now have the acceptance criteria of user registration codified in our tests. When these tests pass, the feature will be done. These tests will also help to prevent regressions caused by any changes we, or anyone else, may make in the future.
Let’s move forward by building the domain model to support user registration.
Application structure
The default directory structure used by the Phoenix generator creates a folder per context, and places them inside a folder named after the application within the lib
directory.
We currently have our accounts
context, along with the Phoenix web
folder:
lib/conduit/accounts
lib/conduit_web
One benefit of this approach is that when a context becomes too large, it can be extracted into its own project. Using an umbrella project allows these separate Elixir applications to be used together, via internal mix references.
When our application grows too large to be comfortably hosted by a single, monolithic service we can migrate the individual apps into their own microservices. This is why it’s important to focus on separation of concerns, using contexts, from the outset. It allows us to split the application apart as production usage and requirements dictate, and more importantly it supports rewriting and deletion of code. Keeping each context highly cohesive, but loosely coupled, provides these benefits.
Within each context in our CQRS application we will create modules for the common building blocks: aggregates, commands, events, read model projections and projectors, and queries. I prefer to create a separate folder for each of these. It provides further segregation within a single context and allows you to easily locate any module by its type and name.
The folder structure for our first accounts context will be:
lib/conduit/accounts/aggregates
lib/conduit/accounts/commands
lib/conduit/accounts/events
lib/conduit/accounts/projections
lib/conduit/accounts/projectors
lib/conduit/accounts/queries
lib/conduit/accounts/validators
Inside the lib/conduit/accounts
folder we will place the context module and a supervisor module:
lib/conduit/accounts/accounts.ex
lib/conduit/accounts/supervisor.ex
These are the public facing parts of the account context, and provide the API into its available behaviour. The supervisor is responsible for supervising the workers contained within, such as the event handlers and projectors.
Alternate structure
Instead of grouping modules by their type within a context, you may chose to group by their aggregate functionality. You can follow the convention used by Phoenix where filename and module names are suffixed by their type (e.g. user_aggregate.ex
).
In this example I’ve illustrated the file structure for modules related to the User aggregate in the Accounts context, including the commands, events, projection, validators, and queries:
lib/conduit/accounts/user/user_aggregate.ex
lib/conduit/accounts/user/register_user.ex
lib/conduit/accounts/user/user_registered.ex
lib/conduit/accounts/user/user_projection.ex
lib/conduit/accounts/user/user_projector.ex
lib/conduit/accounts/user/user_by_email_query.ex
lib/conduit/accounts/user/unique_username_validator.ex
You can use either approach, or another application structure entirely, but it’s important that you choose a convention and adhere to it within your application.
Building our first aggregate
As we’re dealing with registering users, our first aggregate will be the user.
One decision we must take when designing an aggregate is how to identify an instance. The simplest approach is to use a UUID7. This may be generated by the client or the server, and is used to guarantee a unique identity per aggregate instance. All commands must include this identity to allow locating the target aggregate instance.
For Conduit users, we have a restriction that their username must be unique. So we could use the username to identify the aggregate and enforce this business rule. Domain events persisted for each user would be appended to a stream based upon their individual username. Populating the user aggregate would retrieve their events from the stream based on their username. Attempting to register an already taken username would fail since the aggregate exists and its state will be non-empty. However, one downside to this approach is that it would prevent us from allowing a user to amend their username at some point in the future. Remember that domain events are immutable once appended to the event store, so you cannot amend them, or move them to another stream. Instead you would need to create a new aggregate instance, using the new username, initialise its state from the existing aggregate, and mark the old aggregate instance as obsoleted.
We’ll use an assigned unique identifier for each user. The uuid package provides a UUID generator and utilities for Elixir. With this library we can assign a unique identity to a user using UUID.uuid4()
.
We’ll add the UUID package to our mix dependencies:
To enforce the username uniqueness, we will validate the command before execution to ensure the username has not already been taken.
The User
aggregate module, created in lib/conduit/accounts/aggregates/user.ex
, defines the relevant fields as a struct, and exposes two public functions:
-
execute/2
that accepts the empty user struct,%User{}
, and the register user command,%RegisterUser{}
, returning the user registered domain event. -
apply/2
that takes the user struct and the resultant user registered event%UserRegistered{}
and mutates the aggregate state.
This approach to building aggregates will be followed for all new commands and events. The execute/2
function takes the command and returns zero, one, or more domain events. While the apply/2
function mutates the aggregate state by applying a single event.
The execute/2
function to register the user uses pattern matching to ensure the uuid
field is nil. This ensures a user aggregate for a given identity can only be created once.
Why did I name the command function execute/2
and not register_user/2
? This is to allow commands to be dispatched directly to the aggregate, without needing an intermediate command handler. This means less code to write. You can choose to have descriptive command function, but you must also write a command handler module to route each command to the function on the aggregate module. It’s also possible to have the command handler module implement the domain logic by returning any domain events itself, if you prefer.
Building our first command
We need to create a command to register a user. A command is a standard Elixir module using the defstruct
keyword to define its fields. A struct is a map with an extra field indicating its type and allows developers to provide default values for keys.
The register user command can be constructed using familiar Elixir syntax:
When building a struct, Elixir will automatically guarantee all keys belongs to the struct. This helps prevent accidental typos:
Constructing commands from external data
Commands will usually be populated from external data. In Conduit, this will be JSON data sent to our Phoenix web server. Phoenix will parse JSON data into an Elixir map with key based strings. We therefore need a way to construct commands from these key/value maps.
ExConstructor is an Elixir library that makes it easy to instantiate structs from external data, such as that emitted by a JSON parser.
Add
use ExConstructor
after a defstruct statement to inject a constructor function into the module.
We’ll add this library to our mix dependencies:
Then we add use ExConstructor
to our command:
This allows us to create the command struct from a plain map, such as that provided by the params
argument in a Phoenix controller function using the new/1
function:
Building our first domain event
Domain events must be named in the past tense, so for user registration an appropriate event name is UserRegistered
. Again we’ll use plain Elixir modules and structs to define our domain event:
Note we derive the Poison.Encoder
protocol in the domain event module. This is because Commanded uses the poison pure Elixir JSON library to serialize events in the database. For maximum performance, you should @derive [Poison.Encoder]
for any struct used for encoding.
Writing our first unit test
With our User
aggregate, register user command, and user registered event modules defined we can author the first unit test. We’ll use the test to verify the expected domain event is returned when executing the command, and that the fields are being correctly populated.
ExUnit provides an ExUnit.CaseTemplate
module that allows a developer to define a test case template to be used throughout their tests. This is useful when there are a set of functions that should be shared between tests, or a shared set of setup callbacks.
We can create a case template for aggregate unit tests that provides a reusable way to execute commands against an aggregate and verify the resultant domain events. In the following Conduit.AggregateCase
case template an Elixir macro is used to allow each unit test to specify the aggregate module acting as the test subject:
The unit test asserts that the register user command returns a user registered event:
To facilitate test-driven development I use the mix test.watch
command provided by the mix_test_watch package. It will automatically run tests whenever files change.
In mix.exs
, add the package as a dev environment dependency:
Fetch and compile the mix dependencies:
We can now execute our tagged unit test as a one off test run:
… or automatically whenever a file is saved:
Command dispatch and routing
We’ve implemented registration for the user aggregate. Now we need to expose this behaviour through the public API, the Conduit.Accounts
context module. We will create a register_user/1
function that takes an Elixir map containing the user attributes, then construct and dispatch a register user command.
To dispatch a command to its intended aggregate we must create a router module that implements the Commanded.Commands.Router
behaviour:
Once configured, the router allows us to dispatch a command:
We can pattern match on the return value to ensure that the command succeeded, or handle any failures.
The register_user/1
function in the accounts context assigns a unique identity to the user, constructs the register user command, and dispatches it to the configured aggregate:
To verify the expected behaviour of the register user function we turn to the accounts test in test/conduit/accounts/accounts_test.exs
:
Again the test is tagged, using @tag integration
, to indicate it is an integration test and will likely be slower due to accessing the database. Running the test results in a failure:
A failing test is helpful feedback: it guides us as to what we need to build next. In this case, we need to populate our read model and return the newly registered user.
Writing our first read model projection
A projection is a read-only view of some application state, built up from the published domain events.
We’ll be using Ecto to persist our read model to a PostgreSQL database. A projection is built by a projector module defined as an event handler: it receives each published domain event and updates the read model. So a projection is read model state that is projected from domain events by a projector.
In Commanded, an event handler is an Elixir module that implements the Commanded.Event.Handler
behaviour. Each event handler is given a unique name and should be included in the application supervision tree by being registered as a child of a supervisor. An event handler must implement the handle/2
callback function which receives the domain event and its associated metadata. The function must return :ok
to indicate successful processing of the event. You can use pattern matching to define multiple handle/2
functions, one per domain event you want to process.
Here’s an example event handler using the Commanded.Event.Handler
macro:
Commanded Ecto projections
The commanded_ecto_projections Elixir library helps you to build read model projections using the Ecto database library.
Commanded Ecto projections provides a macro for defining a read model projection inside a module which are is defined as a Commanded event handler. The project
macro provides a convenient DSL8 for defining projections. It uses pattern matching to specify the domain event being projected, and provides access to an Ecto.Multi data structure for grouping multiple Repo operations. Ecto.Multi
is used to insert, update, and delete data, and these will be executed within a single database transaction.
The Phoenix generator has already included the Ecto package as a dependency and created an Ecto repo for us, Conduit.Repo
in lib/repo.ex
. We configured the database connection details for the repo in the configuring the read model store section of the getting started chapter.
We’ll add the Commanded Ecto projections package to our dependencies in mix.exs
:
Fetch mix dependencies and compile:
We need to configure the commanded_ecto_projections
library with the Ecto repo used by our application in config/config.exs
:
Then we generate an Ecto migration to create a projection_versions
table:
This table is used to track which events each projector has seen, to ignore events already seen should they be resent as the event store guarantees at-least-once delivery of events. It’s possible an event may be handled more than once if the event store doesn’t receive the acknowledgement of successful processing.
We need to modify the generated migration, in priv/repo/migrations
, to create the projection_versions
table as detailed in the Commanded projections project README:
Creating a user projection
Now we need to create our User schema module, a database migration to create the accounts_users
table, and a corresponding projector module.
When we ran the Phoenix resource generator to create the accounts context, we also asked it to create a user schema and specified its fields. It generated a database migration for us in priv/repo/migrations
. By default Phoenix schemas use auto-incrementing integer fields as the table primary key. As we’re using UUIDs to identify our user aggregate we need to amend the schema and migration to use the uuid
data type.
We’ll add two unique indexes to the accounts_users
table, on username
and email
, to support efficient querying on those fields.
The user projection schema is modified to use Ecto’s binary_id
as the primary key data type:
Then we migrate our database:
Finally, we create a projector module to insert a user projection each time a user is registered. This uses the project
macro, provided by the Commanded Ecto projections library, to match each user registered domain event and insert a new User
projection into the database.
The project
macro exposes an Ecto.Multi
struct, as multi
, that we can use to chain together many database operations. They are executed within a single database transaction to ensure all changes succeed, or fail, together.
Include projector in supervision tree
To start and register the projector module as an event handler we need to include it within our application’s supervision tree. We will create a supervisor module per context responsible for handling its processes. The following supervisor, created in lib/conduit/accounts/supervisor.ex
, will start the user projector:
In lib/application.ex
, we add the Conduit.Accounts.Supervisor
supervisor module to the top level application supervisor:
Reset storage between test execution
To ensure test independence we must clear the event store and read store test databases between each test execution. We already have a Conduit.DataCase
module, generated by Phoenix, to use for integration tests accessing the database. This can be extended to clear both databases; so we add reset_eventstore/0
and reset_readstore/0
functions to do just that.
For the event store, we take advantage of the EventStore.Storage.Initializer.reset!/1
function to reset the database structure, removing any events, streams, and clearing all subscriptions.
The read model database is manually reset by executing a truncate table
SQL statement specifying each projection table to clear. We must remember to add any additional tables to this statement as we build our application to also reset them during test execution.
Returning to the accounts integration test
We have now done almost enough to make our register user test in the accounts context pass. The remaining change is to return the User
projection from the register_user/1
function.
In this scenario, we could attempt to return a %User{}
struct populated from the parameters passed to the register_user/1
function. The concern with this approach is the additional duplicate code we must write, and the potential for it getting out of sync during future changes. Instead we’ll take advantage of Commanded’s support for strongly consistent command dispatch.
The Commanded consistency model is opt-in, with the default consistency being :eventual
. We need to define our user projector as strongly consistent:
Returning to the accounts context, we will update the register_user/1
function to dispatch the command using consistency: :strong
:
Now when we receive an :ok
reply from command dispatch we can be assured that the user projection has been updated with our newly registered user. Allowing us to query the projection and return the populated %User{}
. Let’s run the accounts test to check our changes:
Success, we have a passing test.
We still have one other failing test, but that’s useful as it directs us towards what needs to be worked on next: adding command validation.
Command validation
We want to build our application to ensure that most commands are successfully handled by an aggregate. The first way to achieve this is to limit which commands can be dispatched by only allowing acceptable commands to be shown to the end user in the UI. The second level of protection before a command reaches an aggregate is command validation; all commands should be validated before being passed to the aggregate.
There are three different levels of command validation that apply to an application:
- Command property validation: mandatory fields, data format, min/max ranges.
- Domain validation rules: prevent duplicate usernames, application state based validation logic.
- Business invariants: protection against invalid state changes.
Command property validation
Superficial command field validation is the simplest to apply. You add rules to each command property specifying its data type, whether it’s mandatory or optional, and apply basic range checking (e.g. date must be in the future). You can even apply cross field validation (e.g. start date must be before end date). These rules apply to the command itself, requiring no external information.
Property validation helps guard against common errors, such as the user forgetting to fill out a mandatory field, by applying the rules before accepting the command and rejecting upon validation failure. These rules can be applied at the user interface to help assist the user.
Domain validation rules
In our user registration feature we have a rule that usernames must be unique. To enforce this rule we must check that a given username does not yet exist when executing the register user command. This information will need to be read from a read model. We cannot enforce this rule within our user aggregate because each aggregate instance runs completely independent from any other. It’s not possible to have a command that affects, or uses, multiple aggregates since an aggregate is itself the transaction boundary.
You could decide that this invariant was important enough to warrant protection by using an aggregate whose purpose is to record and assign unique usernames. Its job would be to enforce uniqueness by acting as a gatekeeper to the user registration. A command, such as reserve username, could be used to claim the username. The aggregate would publish a domain event with the newly assigned username on success, allowing an event handler to then register the user with the guaranteed unique username.
In Elixir a GenServer
process can be successfully used to enforce uniqueness as concurrent requests to a process are handled serially. The process would allow a username to be claimed or reserved during command dispatch, preventing any later request from using the same username. The only caveat to this approach is that the GenServer
’s in-memory state must be persisted to storage so that it can be restarted with the list of already taken usernames.
Business invariants
An aggregate root must protect itself against commands that would cause an invariant to be broken. This includes attempting to execute a command that is invalid for the aggregate’s current state. An example would be attempting to rename an article that has been deleted. In this scenario the aggregate would return an {:error, reason}
tagged tuple from the command execute/2
function.
For certain business operations you might decide to return a domain event indicating an error, rather than preventing the command execution. An example would be attempting to withdraw money from a bank account where the amount requested is larger than the account balance. Retail banks earn interest or fees when an account goes overdrawn, so rather than reject the withdraw money command, a bank account aggregate might instead allow the withdrawal and also return an account overdrawn domain event.
Applying command property validation
For command field validation we will be using Vex.
An extensible data validation library for Elixir.
Can be used to check different data types for compliance with criteria.
Ships with built-in validators to check for attribute presence, absence, inclusion, exclusion, format, length, acceptance, and by a custom function. You can easily define new validators and override existing ones.
– Vex
We’ll add the vex package to our dependencies in mix.exs
:
Fetch mix dependencies and compile:
Then we add validation rules for each of the fields in the command:
For the uuid
field we will use a custom validator that attempts to parse the given string as a UUID:
To validate string fields, such as username and email, we will use another custom validator:
Then register these validators in config/config.exs
:
Once registered, we can verify a validator is configured using iex -S mix
:
With the validation rules in place, we can validate a register user command as follows:
Validating dispatched commands
We’ve defined our command validation rules, now we need to apply them during command dispatch.
Commanded provides middleware as an the extension point to include cross-cutting concerns into command dispatch. This can be used to add in command validation, authorization, logging, and other behaviour that you want to be called for every command the router dispatches. You define your own middleware modules and register them in your command router. They are executed before, and after success or failure, of every dispatched command.
We will write a middleware module that implements the Commanded.Middleware
behaviour. It uses the Vex.valid?/1
and Vex.errors/1
functions to validate commands before dispatch:
This middleware will return an {error, :validation_failure, errors}
tagged tuple should a command fail validation. The errors will contain the collection of validation failures, per field, that can be returned and shown to the client.
The validation middleware module is registered in the router:
Testing user registration validation
Returning to our accounts test module, which includes our failing test:
We can run the test again to check whether it passes:
It’s still failing, but only because the validation error message we’re expecting, “can’t be empty”, differs from the default validation error message provided by Vex, “must be present”.
We can provide our own message when registering the validation rules in the command:
Run the test again to see it succeed:
We now have complete end-to-end user registration including command dispatch and validation, aggregate construction, domain event publishing, and read model projection. That covers the entire flow of a CQRS application from an initial command dispatch resulting in an updated read model available to query.
Enforce unique usernames
We’ve implemented basic command field validation using Vex. Now we need to move on to the second level validation: domain validation rules. Enforcing unique usernames when registering a new user will be the first that we’ll implement.
Typically domain validation will use a read model to query for application state. In our case we already have a user projection that contains the username. We even specified a unique index on the username column in the database migration:
The index will ensure that querying on this column is performant.
Let’s write an integration test to assert that registering the same username will fail with a useful error message:
Running this test will fail, so we need to implement the unique username validation rule. First we build a read model query to lookup the user projection by username:
This can be executed by passing the query to our Ecto repository: UserByUsername.new("jake") |> Conduit.Repo.one()
We use this query to expose a new public function in the accounts context: user_by_username/1
:
Then we can check if a username already exists in the new unique username validator, added to the accounts context in lib/conduit/accounts/validators
:
Add the accounts validators to the vex config in config/config.exs
:
Then we can register the new validator against the username
property:
Run the accounts integration test and we now have three passing tests:
Concurrent registration
We’ve included command validation to ensure unique usernames, and have tested this when registering one user after another. However, there’s a problem: attempting to register two users with the same username concurrently. The unique username validation will pass for both commands, allowing both users with an identical username to be created. This issue exists during the small period of time between registering the user and the read model being updated.
An integration test demonstrates the problem:
Since the issue exists only during concurrent command handling we can use another router middleware module to enforce uniqueness. In the before_dispatch/1
callback for the register user command we can attempt to claim the username. Should that fail, it indicates that another user registration for that username is currently being processed and return a validation failure.
The middleware will use a new Unique
module that provides a claim/2
function. This attempts to reserve a unique value for a given context. It returns :ok
on success, or {:error, :already_taken}
on failure. To make the middleware reusable for other fields we define an Elixir protocol (UniqueFields
) allowing commands to specify which fields are unique.
For the RegisterUser
command we specify the :username
field must by unique by implementing the UniqueFields
protocol:
The new Uniqueness
middleware is registered after command validation so that it will only be applied to valid commands:
We’ll use a GenServer
to track assigned unique values. Its state is a mapping between a context, such as :username
, and the already claimed values. Attempting to claim an assigned value for a context returns an {:error, :already_taken}
tagged error.
The Conduit.Support.Unique
module is included in the application supervision tree, in lib/conduit/application.ex
:
We now have unique usernames enforced as part of the register user command dispatch pipeline. This should prevent duplicate usernames from being registered at exactly the same time. We can verify this by running the integration tests again:
Additional username validation
There are two further validation rules to implement on usernames during registration:
- Must be lowercase.
- Must only contain alphanumeric characters (a-z, 0-9).
We can use a regular expression9 to enforce both of these rules.
First we add two integration tests to cover these requirements:
Vex supports regex validation using the format
validator. We add this to the username validation rules in the register user command:
The allow_nil
and allow_blank
options are included as we already have validation to ensure the username is present. We don’t want duplicate error messages when it is not provided: “can’t be empty” and “is invalid”.
We need to convert the username to lowercase during registration in the Accounts
context register_user/1
function. Let’s take the opportunity to make a small refactoring by moving the existing assign_uuid/2
function into the RegisterUser
module. At the same time we will include a new downcase_username/1
function that does as described. These functions are chained together using the pipeline operator after constructing the RegisterUser
command struct from the user supplied attributes.
The new functions are added to the RegisterUser
command:
Running the integration test suite confirms our changes are good.
Validating a user’s email address
We can now apply the same strategy to email address validation. The rules we need to enforce are that an email address:
- Must be unique.
- Must be lowercase.
- Must be in the desired format: contain an
@
character.
The implementation will follow a similar approach to how we validated usernames.
First, we write failing tests to cover the scenarios above:
Second, extend email validation in the command:
Third, we create the new unique email validator:
This also requires a new public user_by_email/1
function in the accounts context to retrieve a user by their email address:
The UserByEmail
query is a module that constructs a standard Ecto query:
Fourth, we extend the UniqueFields
protocol implementation for the register user command to include email address:
Last we include the RegisterUser.downcase_email/1
function in the register user pipeline:
That completes the email address validation: we run the integration test suite again to confirm this with passing tests.
Hashing the user’s password
We don’t want to store a user’s password anywhere in our application. Instead we’ll use a one-way hashing function and store the password hash. To authenticate a user during login we hash the password they provide, using the same algorithm, and compare it with the stored password hash: not the actual password.
For Conduit we’ll use the bcrypt10 password hashing function as described in how to safely store a password using bcrypt. The Comeonin library provides an implementation of the bcrypt hashing function in Elixir.
Password hashing (bcrypt, pbkdf2_sha512 and one-time passwords) library for Elixir.
This library is intended to make it very straightforward for developers to check users’ passwords in as secure a manner as possible.
– Comeonin
Add comeonin
and bcrypt_elixir
to dependencies in mix.exs
:
Fetch mix dependencies and compile:
For our test environment only we will reduce the number of bcrypt rounds so it doesn’t slow down our test suite. In config/test.exs
we configure comeonin
as follows:
We’ll create a Conduit.Auth
module to wrap the Comeonin library’s bcrypt hashing functions:
Then create an integration test to verify the password is being hashed and stored in the user read model. For the test assertion we use the Auth.validate_password/2
function, shown above, which hashes the provided password, jakejake
, and compares with the already hashed password saved for the user, such as $2b$04$W7A/lWysNVUqeYg8vjKCXeBniHoks4jmRziKDmACO.fvqo3wdqsea
. Remember that we never store the user’s password, only a one-way hash.
Next we include a password
field in the register user command struct, to contain the user provided password in plain text. We add a hash_password/1
function that hashes the password, stores the hash value as hashed_password
, and clears the original plain text password. This prevents the user’s password from being exposed by any command auditing.
The final change is to include this function in the register user command dispatch chain:
We’ve now successfully hashed the user’s password during registration, helping to protect our users’ security should our deployed environment be compromised and database accessed. The Comeonin library will generate a different 16 character length salt for each hashed password by default. This is another layer of protection against hashed password dictionary and rainbow table attacks.
Completing user registration
With user registration done, at least from the accounts context, we return to our acceptance criteria defined in the UserControllerTest
integration test. To specify the initial requirements and direct our development efforts we started out by writing end-to-end tests to ensure that the /api/users
registration endpoint adheres to the requirements of the JSON API.
On successful registration the following response should be returned:
For now we will skip the authentication token, that will be addressed in the next chapter.
The integration test for successful user registration asserts against the JSON returned from a POST
request to /api/users
in the UserControllerTest
module:
Running the test still results in a failure, so there’s more work for us to do. We need to modify the user view and select a subset of the fields from our user projection to be returned as JSON data:
As per the API spec we only return the username
, email
, bio
, and image
fields.
Next we need to handle the case where validation errors are returned during command dispatch. The request should fail with a 422
HTTP status code and the response body would be in the following format:
This scenario is covered by the following test:
To achieve this we will use a new feature in Phoenix 1.3, the action_fallback
plug for controllers to support generic error handling. Including the plug inside a controller allows you to ignore errors, and only handle the successful case. Take a look at our existing user controller, where we only pattern match on the {:ok, user}
successful outcome:
Any errors that aren’t handled within your controller can be dealt with by the configured fallback controller. We pattern match on the {:error, :validation_failure, errors}
tagged error tuple returned when command dispatch fails due to a validation failure. The errors are rendered using a new validation view module and returned with an HTTP 422 “Unprocessable Entity” status code:
The validation view returns a map containing the errors that is rendered as JSON:
We can run the integration tests tagged with @web
after making these changes, and the good news is they all pass:
Having completed user registration, we now move on to authentication in the next chapter.
Authentication
Authenticate a user
The API spec for authentication is as follows:
HTTP verb | URL | Required fields |
---|---|---|
POST | /api/users/login | email, password |
Example request body:
Example response body:
Example failure response body:
The successful login response includes a JSON Web Token (JWT). This token is included in the HTTP headers on subsequent requests to authorize the user’s actions. We’ll use Guardian to authenticate users and take advantage of its support for JWT tokens.
An authentication framework for use with Elixir applications.
– Guardian
Guardian provides a number of Plug modules to include within the Phoenix request handling pipeline. We’ll make use of the following three plugs for the Conduit API:
Plug | Usage |
---|---|
Guardian.Plug.VerifyHeader |
Looks for a token in the Authorization header. |
Useful for APIs. | |
If one is not found, this does nothing. | |
Guardian.Plug.EnsureAuthenticated |
Looks for a previously verified token. |
If one is found, continues. | |
Otherwise it will call the :unauthenticated function of your handler. |
|
Guardian.Plug.LoadResource |
Looks in the sub field of the token, |
fetches the resource from the configured serializer | |
and makes it available via Guardian.Plug.current_resource(conn) . |
In mix.exs
, add the guardian package as a dependency:
Fetch and compile the mix dependencies:
Guardian requires a secret key to be generated for our application. We can use the “secret generator” mix task provided by Phoenix to do this:
Configure Guardian in config/config.exs
, including copying the key from above into secret_key
:
Guardian requires you to implement a serializer, as specified in the config above, to encode and decode your resources into and out of the JWT token. The only resource we’re interested in are users. We can encode the user’s UUID into the token, and later use it to fetch the user projection from the read model.
At this point we will move the existing Conduit.Auth
module into its own context. This will allows us to keep authentication concerns, such as password hashing, separate from user accounts.
The Guardian serializer module is created at lib/conduit/auth/guardian_serializer.ex
:
We need to add the user_by_uuid/1
function to the accounts context:
The Conduit API specs show the authentication header is in the following format:
So we need to prefix the JWT token with the word Token
. To do this we configure the Phoenix web router, in lib/conduit_web/router.ex
, and instruct Guardian to use Token
as the realm:
We will create a new session controller to support user login. It will authenticate the user from the provided email and password and return the user’s details as JSON:
An error is returned with a 422 HTTP status code and a generic “is invalid” error message for the email or password on login failure. The existing user and validation views are reused for rendering the response as JSON.
The session controller uses a new public function in the auth context: authenticate/2
This function will look for an existing user by their email address, and then compare their stored hashed password with the password provided hashed using the same bcrypt hash function. An {:error, :unauthenticated}
tagged tuple is returned on failure:
The POST /api/users/login
action, mapped to the new session controller, is added to the router:
With the controller and routing configured we can write a web integration test to verify the functionality. In test/conduit_web/controllers/session_controller_test.exs
we use the Phoenix connection test case to access helper functions for controllers.
There are three scenarios to test:
- Successfully authenticating an existing user and valid password.
- Failing to authenticate a known user when the password is incorrect.
- Failing to authenticate an unknown user.
Run the new web tests, mix test --only web
, to confirm that our changes are good.
Generating a JWT token
User authentication is now working, but we’ve omitted a necessary part of the user data returned as JSON from the login and register user actions. In both cases our response does not include the JWT token as shown in the example response:
We need to rectify that omission by including the token in the response. First, we’ll include the token
property in the session controller test. We assert that it is not empty when successfully authenticating a user:
Let’s use Guardian to generate the token for us. It will use the Conduit.Auth.GuardianSerializer
module we’ve already written and configured to serialize our user resource into a string for inclusion in the token.
To generate the JWT we use Guardian.encode_and_sign/2
by adding a Conduit.JWT
module and wrapper function in lib/conduit_web/jwt.ex
:
Since the token generation will be used in both the session and user controllers we will import the ConduitWeb.JWT
module in the Phoenix controller macro, in lib/conduit_web/web.ex
. This makes the generate_jwt/2
function available to use in all of our web controllers.
The session controller needs to be updated to generate the JWT after authenticating the user. The JWT token is passed to the render
function to make it available to the view:
The render
function in the user view for a single user merges the JWT token into the user data that is rendered as JSON:
Running the web tests again, mix test --only web
, confirms that the token is successfully generated and included in the response.
Getting the current user
An authenticated HTTP GET request to /api/user
should return a JSON representation of the current user. Authentication is determined by the presence of a valid HTTP request header containing the JWT token: Authorization: Token jwt.token.here
.
We will start by adding two new tests to the user controller to verify the following scenarios:
- Successful authentication, with a valid JWT token, returns the current user as JSON data.
- An invalid request, missing a JWT token, returns a
401 Unauthorized
response.
To support a valid request we must register a user and generate a JWT token for them in the test setup. The token is included in the request headers of the test connection using the authenticated_conn/1
function:
The failing tests guide us towards our next code change, we need to register the /api/user
route in the router:
Next we add a current
function to the user controller module. Before doing so we’ll take advantage of Guardian’s built in support for Phoenix controllers. Using the Guardian.Phoenix.Controller
module in our controller provides easier access to the current user and their claims. The public controller functions are extended to accept two additional parameters, user
and claims
, as shown below.
Before: def current(conn, params) do
After: def current(conn, params, user, claims) do
We will also use two plugs provided by Guardian:
-
Guardian.Plug.EnsureAuthenticated
ensures a verified token exists. -
Guardian.Plug.EnsureResource
guards against a resource not found.
Both plugs require us to implement an error handler module that deals with failure cases. In lib/conduit_web/error_handler.ex
we provide functions for the three main error cases. They each return an appropriate HTTP error status code and an empty response body:
The Guardian plugs are configured with our error handler module and to only apply to the current
controller action. This action returns the authenticated current user, and their JWT token, as JSON data:
When an unauthenticated user requests /api/user
the Guardian.Plug.EnsureAuthenticated
plug will step in. It redirects the request to our error handler module, which responds with a 401
unauthorized status code.
Run the web tests, mix test --only web
, to confirm the new route is working as per the API spec.
We’ve now built out the basic user registration and authentication features required for Conduit. Let’s move on to authoring articles in the next chapter.
Articles
Publishing an article
The API spec for creating an article is as follows:
HTTP verb | URL | Required fields |
---|---|---|
POST | /api/articles | title, description, body |
Example request body:
Example response body:
We’ll use the phx.gen.json
generator once again to create a new context for articles. The generator will create the blog context, schema, controller, and JSON view. We already know which fields we need for articles so we can include them, with their types, in the generator command:
Overall, this generator will add the following files to lib/conduit
:
- Context module in
lib/conduit/blog/blog.ex
, serving as the public API boundary. - Ecto schema in
lib/conduit/blog/article.ex
, and a database migration to create theblog_articles
table. - View in
lib/conduit_web/views/article_view.ex
. - Controller in
lib/conduit_web/controllers/article_controller.ex
. - Unit and integration tests in
test/conduit/blog
.
The only change to the generated module locations is to move the article Ecto schema into the lib/conduit/blog/projections
folder, not the blog context root.
Authoring articles
Before we begin publishing articles we’ll take a small detour since we first need a way of identifying their author. We could just use our existing user aggregate and read model projection as a convenience. However, we’ve already determined that accounts and blog are separate contexts, therefore they shouldn’t necessarily share models.
Instead, we’re going to model authors as part of the blog context, segregated from users, but have them related by their identity. There will be a one-to-one mapping from user accounts to blog authors. A benefit of this separation is that the user and author models are only responsible for concerns related to their own role; the user model deals with a user’s email and password, whereas the author model will contain their bio, profile image, and can be used for tracking followers.
We’ll need to build an author aggregate, create author command and author created domain event, and use a Commanded event handler to create an author whenever a user is registered. But first let’s define an integration test that verifies an author is created after successful user registration.
The following integration test uses the assert_receive_event
helper function from Commanded’s event assertions module. Here we assert that an AuthorCreated
domain event is created at some point after user registration and verify it’s for the same user:
As mentioned above we’ll use an event handler to create the author whenever a UserRegistered
event occurs. An event handler is used whenever you need to react to a domain event being created. It’s a good extension point to use for adding auxiliary concerns and integrating separate contexts.
The handler below will delegate to a create_author/1
function we will define in the new blog context. Since the handler is modelling a business process I’ve defined it in a workflows
folder within the blog context and have named it after its behaviour:
In the blog context we add the new create_author/1
function to dispatch a CreateAuthor
command. It has a reference to the associated user aggregate by uuid and also includes the username:
The CreateAuthor
command contains the author identity, associated user identity, and username fields:
We use Commanded’s identity prefix feature to allow the user and author aggregates to share the same aggregate identity. In our router module we identify both aggregates by their respective field (author_uuid
or user_uuid
) and also provide the prefix
option used to differentiate between the event streams used to store their domain events. Author aggregates are prefixed with “author-“ (e.g. author-53db6101-6725-4332-ba94-75b4d05213ab
) and users by “user-“ (e.g. user-53db6101-6725-4332-ba94-75b4d05213ab
). This allows an easy way of correlating an author with its associated user account, and vice versa.
The author aggregate has a single execute/2
function to create an instance, returning an AuthorCreated
event.
We define an author projection (Ecto schema) and a migration to create the blog_authors
table. The corresponding projector module is shown below:
The projector is named article projector as this will be used for projecting both authors and their published articles. We’ll see later why two projections are built using a single projector; it’s because we need to query an article’s author to copy their details into the article projection during publishing.
Finally, the article projector and create author workflow are included as supervised processes in a new blog supervisor:
This supervisor is then added to the top level application supervisor in lib/conduit/application.ex
.
With this chunk of work done we can execute our initial test to verify an author is successfully created in response to registering a user:
By now you should be familiar with the test-driven development cycle we are following:
- Write failing integration tests.
- Build a web controller and define the public API required for the context.
- Implement the context public API, returning empty data.
- Write failing unit tests for the context.
- Build domain model (aggregate, commands, and events) to fulfil the context behaviour.
- Verify unit tests and integration tests pass.
This outside in approach helps to define the outcome we’re working towards in the integration test. Then guides us, step by step, to build the supporting code moving towards that goal.
Publish article integration test
We’ll begin with a controller integration test for the “happy path” of successfully publishing an article. A POST request to /api/articles
should return a 201
response code with the article as JSON data:
The favorited
and favoritesCount
won’t be supported just yet, so we will fake it, until we make it and just return false
and 0
respectively. We will return to build this functionality when we add the favourite articles feature.
Our test requires a new factory function, in test/support/factory.ex
, to build the parameters for an article:
The web controller test also makes use of a convenience function, authenticated_conn/1
, to register a user and set their JWT token. This register a new user account and authenticates the request to be sent to the controller as the newly registered user:
Building the article controller
The integration test will initially fail because we have not yet configured a Phoenix route for the /api/articles
path. We map this route to the article controller in lib/conduit_web/router.ex
:
Only authenticated users are allowed to publish articles. So we authenticate the request to the article controller using the two Guardian plugs Guardian.Plug.EnsureAuthenticated
and Guardian.Plug.EnsureResource
.
The controller uses the Blog context to publish an article, using a new Blog.publish_article/2
function. It will follow our standard command dispatch pattern:
- Create a command from the user provided input parameters.
- Dispatch the command, thereby invoking its validation rules.
- Wait for the read model to be updated.
- Return the projected data from the read model.
You may notice that we assign the article’s author from the given user and must also generate a unique URL slug from the article title. These are important requirements for the feature, so we will write an integration test for the blog context and include tests to cover these.
The register_user/1
function is called before each test case. It provides a registered user to use within the tests, since a user is required to publish articles. The article parameters are built by reusing the factory function previously created for the article controller test.
Defining the publish article command
The publish article command, in lib/conduit/blog/commands/publish_article.ex
, contains:
- A struct to hold the input data.
- Validation rules using the Vex library.
- Functions to assign the article unique identifier and its author.
- A function to generate a unique URL slug, using a separate
Slugger
module.
Generating a unique URL slug
A slug is part of the URL that identifies a page in human-readable keywords. As an example, given an article title of “Welcome to Conduit” the corresponding slug might be “welcome-to-conduit”.
We will use the Slugger package to generate a slug from an article title.
In mix.exs
, add the slugger dependency:
Fetch and compile the mix dependencies:
One complication of URL slug generation is that each slug must be unique. A single slug can only be used one: two articles with the same title cannot share a slug.
We will wrap the slugger library with our own module, in lib/conduit/blog/slugger.ex
. For each generated slug it will query the article read model to determine whether the slug has already been assigned. If it has, a suffix will be appended and retried. So “article” becomes “article-2”, “article-3”, “article-4”, and so on until an unclaimed slug is found.
We need to provide a query to find an article by a slug:
Made publicly available from the Blog context:
Finally, we add validation to the publish article command to ensure uniqueness:
Building the article aggregate
Publishing an article indicates that our domain model should comprise an article aggregate:
An aggregate may only reference other aggregates by their identity, not by reference, so we provide the author’s identity as part of the command (author_uuid
). We don’t include the author’s username, or any other details, as the article does not need that information. It is only required in the read model. You will see an example of combining and denormalising data across aggregates in a read model projection when we build the article projector.
We create a unit test for the article aggregate to cover publishing an article:
The article published domain event defines a struct and uses the Poison JSON encoder:
Lastly, the publish article command is routed to the aggregate in lib/conduit/router.ex
:
Projecting the article read model
We’ve built the article domain model, handling writes, so let’s turn our attention to the read model projection.
In CQRS applications we aim to build read models that directly support the queries our application requires. The benefit of the separate read model is that we can have many views of our data, each perfectly suited to the query it was built for. We want performant reads, so we choose to denormalise data and minimise joins in the database.
Blog article read model
For the article read model we want to also include the author’s details. So the query becomes a simple SELECT
from a single table, no joins needed. We define a database migration to create the blog_articles
table, including the author:
Note we also take advantage of PostgreSQL and Ecto support for arrays for the tag_list
column. We add indexes on the columns that will be used for querying to improve their performance.
The article read model defines the corresponding Ecto schema:
Blog author read model
We define a database migration to create the blog authors table:
A corresponding Ecto schema is built, containing the subset of the user details we’ll use for authors:
Projecting blog authors and articles
In the article projector we handle two domain events:
-
UserRegistered
to capture the author details. -
ArticlePublished
to record each article.
We use Ecto.Multi.run/2
to lookup an author by their identity before creating the article read model.
A projector is guaranteed to handle events in the order they were published. Therefore we can be sure that, within the article projector, the author will have been created before they publish an article.
Publishing articles test
With the read model projection completed we can verify article publishing from the blog context by executing the tests.
The final step is to confirm the article controller tests pass. Before doing so we must update the article view, responsible for formatting the data into the desired structure and returned as JSON data:
Then execute the article controller test:
We’ve now successfully published an article, let’s move on to the queries we need to support.
Listing articles
Fetching and displaying articles is the principal feature of a blog. In Conduit we will support listing all articles and filtering by tag, favorited, and author. To support pagination, an offset and limit may be provided. By default, a GET /api/articles
request returns the most recent articles globally.
The tag
, author
and favorited
query parameter are used to filter results.
Filter by tag | ?tag=AngularJS |
Filter by author | ?author=jake |
Favorited by user | ?favorited=jake |
Limit number of articles (default is 20) | ?limit=20 |
Offset/skip number of articles (default is 0) | ?offset=0 |
Example response body:
List articles controller test
Once again our starting point when building a feature is to define an integration test that verifies the behaviour according to the above API spec. In this case, a GET
request should return all published articles, ordered by published date with the most recent articles first.
The setup
function makes use of two helpers to seed appropriate test data: register_user/1
and publish_articles/1
.
In the article controller, we add an index/4
function to query the latest articles from the given request params, and render the articles as JSON. We include the total count of articles matching the request query in addition to the subset of paginated articles returned.
This route is mapped inside the /api
scope of the web router:
The total count is included in the article view:
Querying latest articles
The article controller depends upon a new function in the blog context: Blog.list_articles/1
It delegates the actual fetching of articles from the database to a new ListArticles
query module.
Unlike previous queries, we’ll provide the query with the repo module allowing it to execute a request to the database. This is because we need to execute two queries:
- Find the articles matching the query, and return a subset of the request page (using limit and offset).
- Count the total number of articles matching the query.
Paginated articles
The entries/2
function includes the pagination, limit
and offset
, and orders the articles by their published date with the most recent articles first.
Article count
The count/1
function selects only the article’s uuid
field and executes a database aggregation to count the rows.
The map of parameters is parsed into an Options
struct using the ExConstructor
library. This provides us with type checking on the available keys, and default values when not present in the user provided params.
We’ll extend the blog test to include listing articles, ensuring that pagination is working as expected. Included in the test is a convenience function to publish multiple articles: publish_articles/1
Filter by author
Let’s start with filtering articles by their author. The test cases we’ll add cover the two scenarios where an author has, or has not, published any articles:
For the test to pass we make a small change to the existing Ecto query, in Conduit.Blog.Queries.ListArticles
, to add a WHERE clause that matches the author_username
field with a given author
value. The query is returned unmodified when the author is nil
.
Populating the author
field in the Options
struct from the map of params from the request is handled by our use of ExConstructor (Options.new(params)
).
Filter by tag
We’ve defined the tag_list
field in the articles table as an array of text. We can use PostgreSQL’s built in support for searching inside arrays.
The SQL statement to query for a tag within an article’s tags array uses the ANY
keyword:
This SQL is translated to the following Ecto query in our ListArticles
module:
Unfortunately this is not a performant query to execute as it will require a sequential table scan.
We can analyse the query plan for our tag query as follows:
The result shows the query planner has chosen to execute a sequential scan on the blog_articles
table:
That’s bad news: our query will gradually degrade in performance over time as our blogging platform gains in popularity, encouraging more authors to publish their own articles. However, we can remedy this situation before it causes a problem in production by optimising the query.
Tagged articles table
One of the advantages of CQRS is that our read model can be built for the exact queries it must support. We could create a separate table for tagged articles and insert one entry for each tag assigned to a published article.
article_uuid | tag | author_username | published_at |
---|---|---|---|
18e760d2-04f1-4da6-b27a-fca6d3ef1fa0 | dragons | jake | 2017-07-28 12:00:00.000000 |
18e760d2-04f1-4da6-b27a-fca6d3ef1fa0 | training | jake | 2017-07-28 12:00:00.000000 |
62acb90d-5ea3-4c0a-9145-2d397fc5750f | cqrs | ben | 2017-07-30 14:00:00.000000 |
Using an index on the tag
column would allow performant lookup.
Use PostgreSQL’s GIN index
We can take advantage of PostgreSQL’s GIN indexes, thereby we don’t need to build a separate table.
GIN indexes are inverted indexes which can handle values that contain more than one key, arrays for example.
To add a GIN index we create an Ecto database migration and specify the type of index via the :using
option:
Then run the migration:
After adding the GIN index on the tag_list
column we can execute the following query:
The @>
clause is used to match rows where the array contains the given value. It’s the same behaviour as the ANY
query we initially wrote, but performs significantly better as it can use the index.
Now the query planner is taking advantage of our GIN index:
We now need to update the filter by tag query in the ListArticles
module. We use Ecto’s fragment
function to provide the exact SQL syntax required for the GIN array clause:
Finally, we verify this query succeeds by adding two new integration tests to the blog test:
Get an article
Now we can list and filter articles, the next feature is to get a single article by its unique URL slug. First up is an integration test that creates an author, publishes an article, and attempts to get the newly published article:
The test fails, so let’s go and make the changes necessary for it to pass. We need to route the article slug URL in the Phoenix web router module:
This route is mapped to a new show/4
function in the ArticleController
which retrieves the article by its unique slug and renders it as JSON:
Since we want to return a 404 HTTP error response when the article does not exist we add a Blog.article_by_slug!/1
function, note the !
suffix, which raises an error when the query returns nothing. This will be handled by the FallbackController
to render the appropriate HTTP status.
That’s all we need to get an article from our API since most of the heavy lifting was already implemented by us earlier to support listing multiple articles.
Favorite articles
The API spec to favorite and unfavorite an article is as follows:
HTTP verb | URL | Required fields |
---|---|---|
POST | /api/articles/:slug/favorite | None |
DELETE | /api/articles/:slug/favorite | None |
There’s no request body or required fields since the URL contains the article being favorited, the HTTP verb informs us of the operation, and the authenticated user making the request is the person who’s favorite it is.
To implement this feature we’ll need to add two new commands, and associated domain events, one to favorite an article and another to unfavorite. When deciding which aggregate should be responsible for this behaviour we need to consider the invariants to be protected. In this example we’d like to ensure a user may only favorite an article once, and they may only unfavorite an article they have previously favourited. We can use the article aggregate to enforce these rules by having each article track who has favorited it.
Favorite integration test
There’s no surprises that we start building the favoriting feature by writing an integration test to specify the required behaviour. In the setup function defined in the favorite article controller test we seed an initial author, publish an article, and register a user. This user will be used to make the authenticated requests to favorite the published article.
You’ll notice that we have an assertion to check the favorited
flag is correctly toggled and the favoritesCount
is incremented and decremented when a user favorites or unfavorites an article. Running this test will immediately fail as we haven’t defined the favourite_article
path in our Phoenix router nor built the FavoriteArticleController
.
Article routing
We need to route POST and DELETE requests to the /api/articles/:slug/favorite
URL. Both of these actions will require fetching the article by its slug. We could do this query in the controller, but Phoenix’s router allows us to define our own request handling pipeline and include any custom plug modules or functions. We’ll take advantage of this feature to define an :article
pipeline with a plug module which attempts to load an article by the slug contained within the URL. This pipeline will be used for any requests matching the /api/articles/:slug
path, including the new favorite article controller.
The LoadArticleBySlug
plug extracts the slug
from the request params and fetches the article from the database. The article is assigned to the connection, allowing it to be accessed later in a controllet action using %{assigns: %{article: article}}
.
Favorite article controller
Let’s go ahead and build the favorite article controller. You’ll notice that we require an authenticated user for the create
and delete
controller actions. This allows us to lookup the author associated with the current user. It’s the author who will favorite, or unfavorite, an article. For both controller actions we return a JSON represenation of the article. As previously mentioned, the article has already been retrieved from the database and made available within the assigns
map by the LoadArticleBySlug
plug.
Favorite articles in Blog context
The FavoriteArticleController
expects Blog.favorite_article/2
and Blog.unfavorite_article/2
functions to exist in the blog context, so we’ll add them to the public API exposed by Conduit.Blog
. Both functions construct a command, dispatch it using the router, and then query the read model to return updated data. This helps us to identify the two new command we need to define: FavoriteArticle
and UnfavoriteArticle
.
You might have noticed we manually set the favorited
flag on the Article
schema and are wondering how does that work? The answer is that a virtual
field has been added to the Ecto schema which allows us to set the value but it’s not backed by a column in the database. This is useful for fields used for setting transient values related to a single query. In this case it’s whether the author has favorited the article. We can manually set the value in these functions because we know what the actual value should be without requiring any further database interaction, such as querying for an author’s favorites. It’s a small performance optimisation.
Favorite commands and events
The favorite article command requires only the article and author identifiers, which are validated as UUIDs:
The article favorited domain event includes both identifiers, but also contains a favorite_count
field. This is included by the article aggregate as a count of favorites so that it can be later projected into the read model.
The unfavorite command and events follow the same pattern, so have been omitted.
Favorite article aggregate handling
As discussed earlier, the article must now track which authors and how many in total have favorited it. We add favorited_by_authors
and favorite_count
fields to the aggregate’s state.
When favoriting an article we must ensure the author hasn’t already favorited the article. This rule is checked by the is_favorited?/2
helper function which looks to see if the author is already in the favorited_by_authors
MapSet. If the author’s identity is already present, the favorite article command returns nil
. This allows the command to be idempotent; if an author requests to favorite an article they’ve already favorited then we can just ignore their request. The unfavorite command is handled similarly, except the check is to ensure the article has already been favorited by the author before unfavoriting.
We also ensure an author can only (un)favorite an existing article by pattern matching on the article’s identity field, using %Article{uuid: nil}
in the execute/2
function. An error is returned when it’s nil
, indicating an article that has never been published.
The favorite_count
value is calculated and included in the events in the (un)favorite command handling functions. This allows the apply/2
state mutator functions to be logic free, they only need to copy the value from the event to the aggregate’s state. We want to ensure there’s minimal processing being done in the apply/2
functions.
Unit testing favorites in the article aggregate
We can test the newly added behaviour to the article aggregate by extending the article unit test and reusing the assert_events/3
test helper function provided by the Conduit.AggregateCase
ExUnit case template module. The assert events function takes a list of initial events, used to populate the aggregate’s state, a command to execute, and a list of expected events to be produced by the aggregate. To favorite an article we need to seed the aggregate with an article published event, produced by the factory function defined in Conduit.Factory
.
Routing favorite commands
With the article aggregate modified to handle the new favorite commands, we need to finish off by routing the commands in the Conduit.Router
module:
Projecting favorite articles in the read model
We’re going to use a SQL join table to track favorited articles which we’ll later use to filter articles favorited by a user.
After creating and running a database migration to add the new blog_favorited_articles
join table we can extend the article projector to handle the new favorite and unfavorite events. Whenever an article is favorited we insert a row into the join table, on unfavorite the row is deleted.
Aditionaly, we also update the article’s favorite_count
field from the count included in the events. Remember that we try to keep our projection code as simple as possible, preferring to keep calculation logic in the domain model (our aggregates). We chain together the two Ecto.Multi
operations which update the join table and articles table using Elixir’s pipeline syntax (|>
).
Favorite articles test
With the read model projection complete we can now run our favorite article tests and should see them pass, which they do. However we’re not quite finished yet. Remember when we favorite, or unfavorite, an article we manually set the favorited
field depending upon what the expected outcome would be. This works fine for this use case, but if we later view all articles the field isn’t being set and defaults to false
.
We can demonstrate this problem with the following integration test which favorites a published article and then immediately requests all articles.
Our expectation is the favorited
flag will be true for the article we just favorited, but running the test shows that it’s false.
Determining whether an article is favorited or not requires us to look in the blog_favorited_articles
join table. When a row exists for the article and author it’s a favorite, otherwise it’s not. To implement this conditional checking we modify the Conduit.Blog.Queries.ListArticles
module and extend the query. A left join is used to compare whether a field from the joined table is not nil
(not is_nil
indicating no row exists) to set the virtual favorited
flag.
Now we’re able to run the full test suite and see it passing.
Filter by favorite articles
One reason why an author would want to favorite an article is for bookmarking, allowing them to later view all of their favorites, or to view another author’s favorites.
Let’s begin by creating two integration tests to assert our desired behaviour. One test will ensure that we can view a user’s favorites, a second is used to check that no articles are returned for a user who has no favorites.
To implement this feature we’ll need to extend the query in the Conduit.Blog.Queries.ListArticles
module to accept an optional favorited
username. We’re using ExConstructor
for the Options
struct, so we only need to add a new favorited
field and it will automatically be populated from the HTTP request query string (such as ?favorited=jake
).
Unfortunately we cannot filter by an author’s username just yet because our blog_favorited_articles
join table only includes the article and author identities. We must add the username to the table, as favorited_by_username
, and populate this field in the article projector from the FavoritedArticle
(which luckily already includes the username).
With the favorited_by_username
field now being set we can join onto the blog_favorited_articles
table using the requested username to only return those articles that have been favorited by that person.
Run the tests again to see that they pass. Now we’re finally done with favoriting articles.
With the article features implemented we take a short detour in the next chapter on tags to look at how CQRS can benefit our application by using a denormalized read model projection.
Tags
Listing tags
A GET /api/tags
request returns a list of tags.
Example response body:
Returning a list of tags applied to published articles isn’t difficult, but does illustrate how separating reads and writes in a CQRS application can be used to build multiple views from the same source of truth (an application’s domain events).
In a CRUD application the list of tags might be built by querying all published articles and finding the distinct tags. This query will likely degrade in performance over time as the number of published articles increases. To counteract this problem developers might choose to use a dual-write approach when publishing an article by updating the article and inserting the tag into a separate tags table. This negatively affects write latency but improves query efficiency when reading. The trade-off chosen here helps typical applications which encounter far more reads than writes.
Using CQRS we can take advantage of fast writes to the event store, with low latency, and use a read model projection to support whatever view of the is data needed for performant querying, such as by denormalizing data. We get the best of both worlds.
The ArticlePublished
event already includes the tag_list
field containing the list of tags for the published article. We’ll project the tags from the event into a separate tags table containing the unique tag names.
Let’s begin with a controller integration test for the new GET /api/tags
endpoint and assert that the returned tags match those included in a published article.
The test will fail as the route isn’t configured and the controller doesn’t exist. Following the outside-in approach we start by adding a new TagController
module:
Then route the /api/tags
path to the controller:
Our controller is using a new Blog.list_tags/1
function which we need to define as a query to find all tags and return only their name:
The ListTags
query module is a very simple Ecto query to find all tags, ordered by name:
Now let’s define our data model to store the global tags. We only record the tag’s name and use an autogenerated field as its identity.
The database migration to create the new blog_tags
also includes a unique index on the name
column. This ensures that tags must be unique, we cannot have any duplicates.
Projecting tags into the read model
Projecting the list of tags from the article published event into the new tags table is the most complex addition for this feature. We’ll use Ecto’s conflict_target
and on_conflict
options to handle inserts of existing tags (enforced by the unique index on :name
we included in the migration above). This approach simplifies the projection code as we don’t need to query first to check whether the tag already exists. We let the database uniqueness constraint take care of the invariant and ignore any name conflicts. We also need to use Enum.reduce/3
to include an insert operation for each tag in the tag list.
The Blog.Projectors.Tag
projector module is added to Conduit.Blog.Supervisor
to ensure it is started with the application.
The tag controller test will now pass and this small feature is complete. We’ve added a global tag list of all published articles without impacting the performance of publishing articles and have implemented an efficient tag query.
Frequently asked questions
How do I structure my CQRS/ES application?
Application structure is described in the Accounts chapter.
How do I deal with eventually consistent read model projections?
Dealing with eventual consistency is explained in the Accounts chapter.
Appendix I
Conduit API specs
Authentication header
Authorization: Token jwt.token.here
JSON objects returned by API
User
Used for authentication.
Profile
Single article
Multiple articles
Single comment
Multiple comments
List of tags
Errors and status codes
If a request fails any validations, expect a 422 and errors in the following format:
Other status codes
401 |
Unauthorized requests, when a request requires authentication but it isn’t provided. |
403 |
Forbidden requests, when a request may be valid but the user doesn’t have permissions to perform the action. |
404 |
Not found requests, when a resource can’t be found to fulfill the request. |
Endpoints
Authentication
POST /api/users/login
Example request body:
JSON
{
"user":{
"email": "jake@jake.jake",
"password": "jakejake"
}
}
No authentication required, returns a user.
Required fields: email
, password
Registration
POST /api/users
Example request body:
JSON
{
"user":{
"username": "Jacob",
"email": "jake@jake.jake",
"password": "jakejake"
}
}
No authentication required, returns a user.
Required fields: email
, username
, password
Get current user
GET /api/user
Authentication required, returns a user that’s the current user
Update user
PUT /api/user
Example request body:
JSON
{
"user":{
"email": "jake@jake.jake",
"bio": "I like to skateboard",
"image": "https://i.stack.imgur.com/xHWG8.jpg"
}
}
Authentication required, returns the user.
Accepted fields: email
, username
, password
, image
, bio
Get profile
GET /api/profiles/:username
Authentication optional, returns a profile.
Follow user
POST /api/profiles/:username/follow
Authentication required, returns profile.
No additional parameters required
Unfollow user
DELETE /api/profiles/:username/follow
Authentication required, returns profile.
No additional parameters required
List articles
GET /api/articles
Returns most recent articles globally by default.
Query parameters
Provide tag
, author
or favorited
query parameter to filter results.
Filter by tag | ?tag=AngularJS |
Filter by author | ?author=jake |
Favorited by user | ?favorited=jake |
Limit number of articles (default is 20) | ?limit=20 |
Offset/skip number of articles (default is 0) | ?offset=0 |
Authentication optional, will return multiple articles, ordered by most recent first.
Feed articles
GET /api/articles/feed
Can also take limit
and offset
query parameters like list articles.
Authentication required, will return multiple articles created by followed users, ordered by most recent first.
Get article
GET /api/articles/:slug
No authentication required, will return single article.
Create Article
POST /api/articles
Example request body:
Authentication required, will return an article.
Required fields: title
, description
, body
Optional fields: tagList
as an array of Strings
Update Article
PUT /api/articles/:slug
Example request body:
Authentication required, returns the updated article.
Optional fields: title
, description
, body
The slug
also gets updated when the title
is changed.
Delete article
DELETE /api/articles/:slug
Authentication required
Add comments to an article
POST /api/articles/:slug/comments
Example request body:
Authentication required, returns the created comment.
Required fields: body
Get comments from an article
GET /api/articles/:slug/comments
Authentication optional, returns multiple comments.
Delete comment
DELETE /api/articles/:slug/comments/:id
Authentication required
Favourite article
POST /api/articles/:slug/favorite
Authentication required, returns the article.
No additional parameters required
Unfavourite article
DELETE /api/articles/:slug/favorite
Authentication required, returns the article.
No additional parameters required
Get tags
GET /api/tags
No authentication required, returns a list of tags.
Notes
1CRUD is an abbreviation of Create, Read, Update, and Delete.↩
2A pure function always evaluates the same result value given the same argument value.↩
3JSON Web Tokens are an open, industry standard method for representing claims securely between two parties.↩
6Commanded is MIT licensed, a permissive free software license. This allows reuse within proprietary software, and for commercial purposes.↩
7A universally unique identifier (UUID) is a 128-bit number used to identify information in computer systems.↩
8Domain specific language↩
9Regular expression, regex or regexp, is a sequence of characters that define a search pattern in a string.↩
10bcrypt is a password hashing function designed by Niels Provos and David Mazières, based on the Blowfish cipher.↩