Intentionally Learning Elixir

Written by Pete Corey on Dec 19, 2016.

I’ve been programing computers in one way or another since I was ten years old. This means that I’ve had to teach myself quite a bit over the years.

My usual method of learning new programming concepts is to immerse myself in blog posts, online tutorials, forums, and chat rooms, trying to absorb as much information as I can. Unfortunately, I’ve come to realize that this can be a slow, unfocused method of learning.

When learning from scattered resources, information can come to me in an unideal order and from authors with entirely different outlooks and perspectives on the topics they’re teaching about.

Wanting to fast-track learning Elixir, I decided to try something I’d always shied away from. Reading books!

I’ve spent the past two weeks reading Programming Elixir (affiliate link) by Dave Thomas.

I picked Programming Elixir over the other multitude of books on Elixir because it’s often touted as the best introductory book to the language. After reading it, I’d have to agree that’s it’s a fantastic entry point.

To get the most out of the experience, I decided to read through the book in an intentionally focused way, reproducing most examples on my own machine, and completely (nearly) every exercise.

At the end of the day, I can happily say that the time investment is paying off. While I originally thought I had a grasp on Elixir, I feel significantly more comfortable with all of the nuances of the language after having read the book.

Next, I plan on reading Elixir in Action (affiliate link) by Sasa Juric to get a better handle on OTP and “thinking in processes”.

This experience has shown me that books are an invaluable tool for learning programming concepts. The curated, focused approach of following a single author’s train of thought through a topic really does give the reader a solid understanding of the topic.

If you’re looking for a book on Elixir, I highly recommend starting with Programming Elixir (affiliate link).

How to use MongoDB With Elixir - Revisited

Written by Pete Corey on Dec 5, 2016.

I recently wrote an article on how to use MongoDB with Elixir. Since that article was released, changes have been made to the MongoDB Elixir package.

In many ways, these changes make the package more approachable and flexible for developers, but they left my old instructions outdated and incomplete.

Previous versions of the MongoDB driver (< 0.2) required that you build your own MongoPool module somewhere in your project:

defmodule MongoPool do
  use Mongo.Pool, name: __MODULE__, adapter: Mongo.Pool.Poolboy

This MongoPool module set up your connection pooling (using Mongo.Pool.Poolboy) and was the main process you would instantiate to establish a connection with your MongoDB database:

{:ok, _} = MongoPool.start_link(database: "test")

Once the connection was established, you could query the database through the connection pool, without specifying the PID if the pool’s process:

|> Mongo.find("collection", %{ "foo" => "bar" })
|> Enum.to_list

However, with version 0.2 of the MongoDB driver, things have changed.

Now, you instantiate your connection to your MongoDB database by spinning up the Mongo process directly:

{:ok, mongo_pid} = Mongo.start_link(database: "test")

The first argument to Mongo.find/Mongo.insert_one/etc… is now the Mongo process ID:

|> Mongo.find("collection", %{ "foo" => "bar" })
|> Enum.to_list

Alternatively, you can name your Mongo process to avoid having to pass the mongo_pid around your application:

{:ok, _} = Mongo.start_link(database: "test", name: :mongo)

|> Mongo.find("collection", %{ "foo" => "bar" })
|> Enum.to_list

Out of the box, this will establish a single connection to the database. To enable connection pooling, like we had with our old MongoPool, we need to specify how we want our pooling handled when we spin up our Mongo process:

{:ok, _} = Mongo.start_link(database: "test", name: :mongo, pool: DBConnection.Poolboy)

You then need to specify the pool module you’re using when running MongoDB operations:

|> Mongo.find("collection", %{ "foo" => "bar" }, pool: DBConnection.Poolboy)
|> Enum.to_list

The heart of these changes is that the mongodb driver package is now using the DBConnection package, instead of wrapping Poolboy itself.

See the changelog and the GitHub documentation and the Hex documentation for more details.

Using Apollo Client with Elixir's Absinthe

Written by Pete Corey on Nov 21, 2016.

There’s no doubt that GraphQL has been making waves in the web development community since it was announced, and for good reason! GraphQL helps decouple an application’s front-end from its back-end in amazingly flexible ways.

Unfortunately, React and Redux, the current go-to front-end frameworks for handling client-side state and interacting with a GraphQL server are cumbersome to use at best. Thankfully, the Apollo client, a new project from the Meteor Development Group, is trying to offer a more straight-forward, batteries included option for interfacing with GraphQL and managing your client-side state.

Let’s dig into how to set up a basic GraphQL server in Elixir using Absinthe, and how to interact with that server using the Apollo client.

Elixir’s Absinthe

Absinthe is a GraphQL implementation for Elixir. It lets you set up a GraphQL endpoint on your Elixir/Phoenix server.

Setting up Absinthe is a straight-forward process. To start, we’ll add dependencies on the absinthe and absinthe_plug Mix packages and fire up their corresponding applications:

defp deps do
  [ ...
   {:absinthe, "~> 1.2.0"},
   {:absinthe_plug, "~> 1.2.0"}]

applications: [ … :absinthe, :absinthe_plug]

Just like in the Absinthe tutorial, our next step is to set up our GraphQL types. We’ll create simple schemas for an author and a post:

object :author do
  field :id, :id
  field :first_name, :string
  field :last_name, :string
  field :posts, list_of(:post) do
    resolve fn author, _, _ ->
      {:ok, HelloAbsinthe.Schema.find_posts(}

object :post do
  field :id, :id
  field :title, :string
  field :author, :author do
    resolve fn post, _, _ ->
      {:ok, HelloAbsinthe.Schema.find_author(}
  field :votes, :integer

Next, we’ll define the types of queries we support. To keep things simple, we’ll add two basic queries. The first, posts, will return all posts in the system, and the second, author, will return an author for a given id:

query do
  field :posts, list_of(:post) do
    resolve &get_all_posts/2

  field :author, type: :author do
    arg :id, non_null(:id)
    resolve &get_author/2

To cut down on the number of moving parts in this example, we’ll write our two resolver functions to return a set of hard-coded posts and authors, rather than pulling them from some external data source:

@posts [
  %{id: 1, title: "GraphQL Rocks",           votes: 3, author: %{id: 1}},
  %{id: 2, title: "Introduction to GraphQL", votes: 2, author: %{id: 2}},
  %{id: 3, title: "Advanced GraphQL",        votes: 1, author: %{id: 1}}

@authors [
  %{id: 1, first_name: "Sashko", last_name: "Stubailo"},
  %{id: 2, first_name: "Tom",    last_name: "Coleman"},


def get_all_posts(_args, _info) do
  {:ok, @posts}

def get_author(%{id: id}, _info) do
  {:ok, find_author(id)}

def find_author(id) do
  Enum.find(@authors, fn author -> == id end)

def find_posts(author_id) do
  Enum.find(@posts, fn post -> == author_id end)

Now all we need to do is tell Absinthe that we want our GraphQL endpoint to listen on the "/graphql" route and that we want it to use our newly defined schemas and queries:

forward "/graphql", Absinthe.Plug, schema: HelloAbsinthe.Schema

And that’s it! Now we can send our server GraphQL queries and it will process them and send back the result.

Let’s move on to setting up Apollo on the front-end.

Apollo Client

If you haven’t noticed already, we’re basing this example off of the query example on the Apollo Developer page.

Before we continue with their example, we need to set up React in our application. Since we started with a fresh Phoenix project (mix, we’ll need to install install some NPM dependencies to work with React, Apollo, etc…:

npm install --save react react-dom apollo-client react-apollo \
                         graphql-tag babel-preset-react

Next, we’ll need to tell Brunch how to we want our ES6 transpiled by tweaking our Babel options in brunch-config.js:

plugins: {
  babel: {
    presets: ["es2015", "react"],

The last thing we need to do is replace the HTML our Phoenix application generates (in app.html.eex) with an empty <div> to hold our React application:

 <div id="app"></div>

Now we can copy over the <PostList> component from the Apollo example. We’ll throw it in a file called PostList.jsx.

Lastly, we’ll create an instance of ApolloClient and wire up the <PostList> component to our container <div> in our app.js:

const client = new ApolloClient();

  <ApolloProvider client={client}>
    <PostList />

And that’s it! When our application reloads, we’ll see all of the hard-coded author and post data from our server loaded up and rendered on the client.

How it Works

This is obviously a drastically over-simplified example of what GraphQL can do, but it’s a good jumping off point. Let’s see how all of it ties together, starting on the client.

The <PostList> component we pulled from the Apollo example is a simple component that expects to be passed a loading boolean and a list of posts inside of a data property.

If loading is true, we’ll show a loading message. Otherwise, we’ll render the list of posts:

function PostList({ data: { loading, posts } }) {
  if (loading) {
    return <div>Loading</div>;
  } else {
    return (<ul>{ => … )} </ul>);

Where do loading and posts come from? The loading field is controlled by the Apollo client. When we’re waiting on the response for a GraphQL query, loading will be true. The posts field actually comes directly from the response to our GraphQL query.

When we export PostList, we actually wrap it in a GraphQL query that describes the data this component needs to render:

export default graphql(gql`
  query allPosts {
    posts {
      author {

The shape of a GraphQL query’s response maps directly to the shape of the query itself. Notice how we’re asking for a set of posts. We want each post to be returned with an id, title, votes, and an author object, complete with id, firstName, and lastName.

Our response will look exactly like this:

  posts: [
      id: 1,
      title: "GraphQL Rocks",
      votes: 3,
      author: {
        id: 1,
        firstName: "Sashko",
        lastName: "Stubailo"

This is the power of GraphQL. It inverts the normal query/result relationship between the client and the server. The client tells the server exactly what it needs, and that exact data is returned from the query. No more, no less.

Apollo takes that client-first mentality even further. With Apollo, each component tells the server exactly what it needs and manages it’s data lifecycle entirely on its own, independent from other components in the application.

Final Thoughts

I’m really excited about the combination of an Elixir/Absinthe back-end driving an Apollo-powered client front-end.

I’ve only just started playing with this combination, but I hope to start building out more complex and realistic applications to see if it lived up to my hopes and expectations.

Be sure to check out the entire project on GitHub. Have you used Absinthe or any part of the Apollo stack? If so, shoot me an email and let me know your opinions!