As part of my attempt to learn more about Phoenix I decided to write a Phoenix application backend to the infamous TodoMVC example using ember-cli and the JSON API standard.
There are a few examples out there how to set up communication between an Ember application and Phoenix, but these tutorials are either outdated (and aren't working anymore) or are ignoring some of the conventions that either Phoenix or Ember provide.
The ember examples are either introducing unnecessary boilerplate code and custom serialiser and adapter code instead of using the now stable JSONAPI adapter that comes with ember. I think this may be a missed opportunity to simplify code.
On the Phoenix side a lot of the examples out there are using variable bindings instead of pipes which is understandable to anyone who might be coming from another language, such as Ruby. However, I think we should try a little harder and make use of the features that Elixir provides us, such as piping, ultimately creating more idiomatic code.
Setting up the necessary CORS headers also seemed to be a bit more difficult to anyone who may be new to Phoenix, so I decided to create the Phoenix app from scratch and learn on the way.
In a nutshell, the following steps were necessary to ensure communication between the server and the client.
I needed to...
- Configure Ember Data to use a JSON API serialiser (
- Configure Ember Data to point to the Cowboy server that is running
- Set the necessary CORS headers in Ember so that the browser will allow Ajax requests to the Phoenix API server
- Set up CORS in Phoenix using the Corsica plug to allow requests from the Ember application
- Teach Phoenix how to handle requests with
- Serialise controller parameters in Phoenix using the ja_serializer package
Get the code
As currently I don't have the time to write a detailed article where I explain the decisions behind each and every single change, I decided to make the code available anyway to anyone who might want to learn from this. I'm hoping the commits are self-explanatory and descriptive enough to be able to follow my steps if anyone decides to do so.
The repositories for both the Phoenix application and the ember-cli ui are on my Github.
I'm by no means an Ember or Elixir expert (yet - fingers crossed) so if you find ways to improve the codebase, please tell me in the comments or open a pull request.
During the learning process, the following people helped me understanding the issues and sometimes even debugging the code:
I'm a Ruby/JS dev/trainer with a focus on quality. An ex-Londoner, @terracycle, @ubxd, @lastfm. Follow me at http://twitter.com/attilagyorffy