Cloudinary Blog

How to build a CMS with Adonis: A Laravel-like MVC framework for Node - Part 1

By Christian Nwamba
Learn about AdonisJs and how to set up a CMS with it

Even though Node is fun, easy and cheap to work with, we spend a lot of time writing boilerplate codes because structure and organization is missing.

What happened to Convention Over Configuration?

While Node is simple, it requires you to make a lot of decisions, which ultimately causes confusion because it leaves you with several options. Languages like PHP, Ruby, C# and Python have one or more Molde-View-Controller (MVC) frameworks, such as Laravel, Rails, ASP.Net and Django. These help developers to achieve structure and write maintainable code with these languages. That was not the case for Node until AdonisJs was introduced.

AdonisJs can help with these challenges. AdonisJs is an MVC framework for Node that is modeled after the popular PHP’s Laravel framework with a few concepts from Rails as well.

Now, let’s look at how you can use Adonis to create a simple content management system (CMS) performing CRUD (create, read, update and delete) operations.

Adonis Setup

Before we write example code, we need to get Adonis on our machines and review a typical Adonis application files structure.

Adonis Installation & New Projects

Adonis has a command-line interface (CLI) that makes most utility tasks easy. We can use npm to install the CLI globally:

Copy to clipboard
$ npm install -g adonis-cli

Node v4.0.0 and npm are the only requirements for installing Adonis to your computer.

With Adonis installed and the Adonis command available, we can use it to create a new project:

Copy to clipboard
$ adonis new simple-blog
$ cd simple-blog
$ npm start

The new command creates a new Adonis project with all the necessary files and content to get us started. It also installs the npm dependencies into the node_modules folder, so there is no need to run npm install.

You can create an Adonis project without using the CLI command. This option is considered manual and can be achieved by getting the boilerplate from GitHub and installing the dependencies:

Copy to clipboard
$ git clone https://github.com/adonisjs/adonis-app simple-blog

$ cd simple-blog

$ npm install

$ npm start

The purple screen at localhost:3333 indicates that a new app was successfully created: Successfully created app

Directory Structure

The directory structure of an Adonis project can be intimidating at first. But, that’s the case with any framework that implements the MVC architecture. With time, you will understand how to navigate it. Here’s a top-level overview for your reference:

Copy to clipboard
├── app # Your code's home
│   ├── Commands # Ace Commands
│   ├── Http # Controllers and Routes
│   ├── Listeners # Event Listeners
│   ├── Model # Database Models
├── bootstrap # Application setup logistics 
├── config # All Configuration lives here
├── database
│   ├── migrations # Database Migrations
│   └── seeds # Dummy data
├── providers # Service Providers
├── public # Client files
├── resources
│   └── views # Application views
├── storage # Temporary Logs and Sessions

Database & Migrations

The Sqlite database is a good choice for development purposes and very small scale applications. We can make use of it by installing via npm and telling Adonis to use it as our default database via the database config.

Copy to clipboard
npm i --save sqlite3

The above command runs the installation process for sqlite3. Now we must tell Adonis to make use of the database we just installed. Conveniently, Adonis already uses sqlite3 as the default database:

Copy to clipboard
// ./config/database.js
module.exports = {
    // Use Connection defined in .env file or
    // sqlite if none
    connection: Env.get('DB_CONNECTION', 'sqlite'),
    // sqlite configuration
    sqlite: {
      client: 'sqlite3',
      connection: {
        filename: Helpers.databasePath('development.sqlite')
      },
      useNullAsDefault: true
    },
    ...
 }

Migration is not a core MVC architecture concept, but it makes it easy to share schemas in a declarative manner. Rather than defining the schema in our databases directly, we define them in a file. This file can then be shared among team members.

To create a posts migration, run:

Copy to clipboard
./ace make:migration posts --create=posts

The command will create a migration class file named [TIMESTAMP]_posts.js in database/migrations.

The class has an up and down method. up is called when we run migrations to create the database table, while down is called when we want to tear down the table.

Currently, the schema is defined with nothing but methods that will create the primary key (increments()) and another to create timestamps (timestamps()). Let’s add something that a post should have:

Copy to clipboard
// ./database/migrations/[TIMESTAMP]_posts.js
...
up () {
    this.create('posts', (table) => {
      table.increments();
      table.timestamps();
      // New columns' methods 
      table.string('title');
      table.string('body');
      table.string('image');
    })
  }
...

We are calling the string method on the table, which was passed in to the create closure. This method will create a column of string type (or varchar, as the case may be) and the column will be named after whatever value was passed in.

You can then execute the migration run command to begin migration:

Copy to clipboard
./ace migration:run

After a successful migration, you should get a message in the console saying so:

Copy to clipboard
✔ Database migrated successfully in 120 ms

Database Models

Now let’s focus on the M in MVC, which stands for Models. Models are stored in the app/Model folder and can be created using the ace command as well:

Copy to clipboard
./ace make:model Post

Note: Convention over configuration is a software engineering paradigm in which developers are not required to make too many decisions. Each Model needs to be mapped to a migration. Adonis uses this paradigm, so rather than defining it manually, it helps you make the decision. A Post will map to a posts migration, which is a plural lowercase. We are never compelled to define a config of what model maps to what migration.

Here’s what our model looks like:

Copy to clipboard
// ./app/Model/Post.js
const Lucid = use('Lucid')

class Post extends Lucid {

}

module.exports = Post

Lucid is the library that Adonis uses to manage Models.

The above Post model might seem empty. However, because it will eventually be mapped to our posts migration, we still gain access to the table’s columns. We will discuss this later in the article.

Creating Posts

Now that Migrations and Models have been taken care of, we have a store. Henceforth, we will be playing with HTTP requests and responses using routes, controllers and views.

Our first two routes are going to handle creating new posts:

Copy to clipboard
// ./app/Http/routes.js

//GET route to send the new post form
Route.get('/new', 'PostController.new');
//POST route to send form data to the server
Route.post('/create', 'PostController.create');

The route method takes two arguments – the route URL and the controller actions. We now need to create the controllers with the new and create action methods:

Copy to clipboard
// Import Model
const Post = use('App/Model/Post');

class PostController {
    // New action method
    * new(request, response) {
        // Send a view
        yield response.sendView('post/new'); // ./resources/views/post/new.njk
    }

    // Create Action method
    * create(request, response) {
        // Filter relevant post data
        const postData = request.only('title', 'body');
        // Create and store post
        yield Post.create(postData);
        // Redirect to home page
        response.redirect('/');
    }
}

module.exports = PostController
  • We first import the Post Model to our controller. This is because, the create action method will make use of this Model to create and store new posts.
  • The first controller action – new – sends a Nunjucks view that contains a template for the post form. The syntax is known as Nunjucks with an.njk extension and that is what Adonis uses for templates.
  • The second controller action – create – receives data from the browser through the form and stores it using the Post Model.

The * ... yield syntax is an EcmaScript upcoming feature called Generators. They are a different kind of function and Adonis uses it to simplify a lot of async tasks.

Here is what the form in the view looks like:

Copy to clipboard
{% extends 'master' %}

{% block content %}
    <h2>New Post</h2>
  {{ form.open({action: 'PostController.create'}) }}

    {{ csrfField }}

    <div class="ui form">
        <div class="field">
            {{ form.label('Post Title') }}
            {{ form.text('title', null) }}
        </div>

        <div class="field">
            {{ form.label('Body') }}
            {{ form.textarea('body', null) }}
        </div>

        {{ form.submit('Create', 'create', { class: 'ui blue button' }) }}
    </div>

  {{ form.close() }}
{% endblock %}

You can visit the /new route to create a new post. This is what our data looks like in the database viewer: Our data in the database viewer

Next Up

Here we introduced Adonis and some of its basic concepts. In the second part of this article, we’ll share how easy it is to handle image uploads when creating a new post, how to read/update existing posts and display them, and how to delete posts from the store.

Christian Nwamba Christian Nwamba is a code beast, with a passion for instructing computers and understanding it's language. In his next life, Chris hopes to remain a computer programmer.

Recent Blog Posts

Our $2B Valuation

By
Blackstone Growth Invests in Cloudinary

When we started our journey in 2012, we were looking to improve our lives as developers by making it easier for us to handle the arduous tasks of handling images and videos in our code. That initial line of developer code has evolved into a full suite of media experience solutions driven by a mission that gradually revealed itself over the course of the past 10 years: help companies unleash the full potential of their media to create the most engaging visual experiences.

Read more
Direct-to-Consumer E-Commerce Requires Compelling Visual Experiences

When brands like you adopt a direct–to-consumer (DTC) e-commerce approach with no involvement of retailers or marketplaces, you gain direct and timely insight into evolving shopping behaviors. Accordingly, you can accommodate shoppers’ preferences by continually adjusting your product offering and interspersing the shopping journey with moments of excitement and intrigue. Opportunities abound for you to cultivate engaging customer relationships.

Read more
Automatically Translating Videos for an International Audience

No matter your business focus—public service, B2B integration, recruitment—multimedia, in particular video, is remarkably effective in communicating with the audience. Before, making video accessible to diverse viewers involved tasks galore, such as eliciting the service of production studios to manually dub, transcribe, and add subtitles. Those operations were costly and slow, especially for globally destined content.

Read more
Cloudinary Helps Minted Manage Its Image-Generation Pipeline at Scale

Shoppers return time and again to Minted’s global online community of independent artists and designers because they know they can count on unique, statement-making products of the highest quality there. Concurrently, the visual imagery on Minted.com must do justice to the designs into which the creators have poured their hearts and souls. For Minted’s VP of Engineering David Lien, “Because we are a premium brand, we need to ensure that every single one of our product images matches the selected configuration exactly. For example, if you pick an 18x24 art print on blue canvas, we will show that exact combination on the hero images in the PDF.”

Read more
Highlights on ImageCon 2021 and a Preview of ImageCon 2022

New year, same trend! Visual media will continue to play a monumental role in driving online conversions. To keep up with visual-experience trends and best practices, Cloudinary holds an annual conference called ImageCon, a one-of-a-kind event that helps attendees create the most engaging visual experiences possible.

Read more