AdonisJs – Installation and Database Setup

Now that you have all the requirements we need to be installed, let’s set up the project.

If you’re having any problems setting up or installing the dependencies, feel free to leave a comment or shoot me a DM.

What we’ll be covering in this post.


This content originally appeared on DEV Community and was authored by Ted Ngeene

Now that you have all the requirements we need to be installed, let's set up the project.

If you're having any problems setting up or installing the dependencies, feel free to leave a comment or shoot me a DM.

What we'll be covering in this post.

  1. Creating a new project
  2. Adonis Project Structures
  3. IDE Setup
  4. Starting the Development Server
  5. Database Setup

Create a new project

To initialize a new project, all we need is a simple command on the terminal.
Simply navigate to the directory you'd like the project to be located and type the following;

npm init adonis-ts-app fitit or yarn create adonis-ts-app fitit

Let's break down this command for context.

  1. npm init - this is simply initializing the project. Since we're using npm as the package manager, we use npm.
  2. adonis-ts-app - we're initializing the project as a typescript project. If you wish not to use typescript and stick to vanilla JavaScript, you can use the adonis new fitit. This would involve installing the adonis cli. For more details on this, head over to this link. However, I recommend using the typescript version.
  3. fitit - this is the name of the application.

In general, the general structure of creating a new Adonis application is

npm init adonis-ts-app <project_name>

After you've typed the project initialization command, npm first installs the necessary adonis packages, which then prompts you to choose a preferred project structure.

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jhd6lkqz09ilulc1qljr.png

Adonis Project structures

You can choose between one of the following project structures.

  • web project structure is ideal for creating classic server-rendered applications. We configure the support for sessions and also install the AdonisJS template engine(edge). Also, the support for serving static files like images is provided.
  • api project structure is ideal for creating an API server. This also configures the support for CORS.
  • slim project structure creates the smallest possible AdonisJS application and does not install any additional packages, except the framework core. This sort of allows for flexibility. It's up to the developer to build the application ground-up.

It's worth noting that apart from some minor differences, the overall project structure is almost similar.

For this project, we'll be using the api project structure. The reason for this is that I'm mostly going to be using Adonis as an API server, which I'll then hook to a vue.js frontend.

If you're using vs code, the command prompt will ask for additional configurations. These are prettier and eslint-related. I advise using both formatters.

After the project has been created, you'll get a message like this on the terminal.

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rx9s29si21l3kyrpyuxf.png

Vs Code Setup

This section is intended for anyone using vs code as their IDE. If you use any other IDE, you can skip over to the next section.

Some extensions will make your adonis development easier in vs code. These are;

  1. Prettier and eslint - As I'd mentioned earlier you need to have prettier and eslint installed. This will be set up during the installation process.
  2. JavaScript and TypeScript Nightly
  3. Adonis JS Snippets - provides insightful snippets.
  4. Adonis Js Go to controller will come in handy when we start working with routes.

Starting the Development server

Navigate to the project directory and open it on your IDE now that the project has been created.
Run the following command to spin up your local development server

node ace serve --watch

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pip6qxqqllqxdxv45hmj.png

Open up your browser, and visit localhost:3333. If you did everything right, then you should see a screen with hello world text. Congratulations on setting up your first Adonis project! ??

From here, things start to get interesting, we'll set up the database but before we head there, you might be wondering what node ace serve --watch is.

ace is a command-line framework that is embedded within your app. It allows you to create project-specific commands and run them using node ace. We'll be using ace commands throughout the tutorial, each with it's own purpose. For a more detailed explanation on ace commands, head over to this article by @amanvirk1

For the above command, let's break down what it does.

  • The serve command starts the HTTP server and performs an in-memory compilation of TypeScript to JavaScript.
  • The -watch flag is meant to watch the file system for changes and restart the server automatically(hot reload).

Database Setup

Before we wind up, let's connect our application to a database.

I'll assume that you have some knowledge of setting up Postgres or SQL databases and already have one on your computer. If this is not the case, you can use sqlite, which will be a file created on your machine once we start defining the database configuration.

AdonisJS has first class support for SQL databases. The data layer of the framework is powered by Lucid(AdonisJs ORM) and the package must be installed separately.

Simply run npm i @adonisjs/lucid

Upon successful installation, we'll configure our database driver and create a database. For this tutorial, I'll be using postgres. So my configs will be postgres-related. However, if you're using SQL, then use relevant configuration.
If you choose sqlite, no configuration will be required.

Once done, run

node ace configure @adonisjs/lucid

or

node ace invoke @adonisjs/lucid

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a89rfw84vqrd02v4poy7.png

The ace configure and invoke commands executes the instructions Javascript file exposed by the package.

Since I decided to go with postgres, I'll copy the code for validating the environment variables to the env.ts file.

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xd58875vcey8sokk2z9s.png

Environment variables are injected from outside. The env.ts file validates that they type match and that the app is always running with the correct set of configuration values.
Your env.ts file should now look like this.

import Env from '@ioc:Adonis/Core/Env'

export default Env.rules({
  HOST: Env.schema.string({ format: 'host' }),
  PORT: Env.schema.number(),
  APP_KEY: Env.schema.string(),
  APP_NAME: Env.schema.string(),
  PG_HOST: Env.schema.string({ format: 'host' }),
  PG_PORT: Env.schema.number(),
  PG_USER: Env.schema.string(),
  PG_PASSWORD: Env.schema.string.optional(),
  PG_DB_NAME: Env.schema.string(),
  NODE_ENV: Env.schema.enum(['development', 'production', 'testing'] as const),
})

  • The config/database.ts file holds all the configuration related to the database. For more details on this, check out the documentation.

Next, we'll configure our database on postgres.

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dj0r18jifd8bcx183qn0.png

You can name your database whatever name you wish.

Finally, go to your .env file and modify these values


DB_CONNECTION=pg
PG_HOST=localhost
PG_PORT=5432
PG_USER=postgres
PG_PASSWORD=<your_postgres_password>
PG_DB_NAME=<your_db_name>

Testing Database connection.

Adonis comes with a neat health checker that checks if the database connection is working.

Navigate to start/routes.ts and paste the following code.


import HealthCheck from '@ioc:Adonis/Core/HealthCheck'
import Route from '@ioc:Adonis/Core/Route'

// check db connection
Route.get('health', async ({ response }) => {
  const report = await HealthCheck.getReport()

  return report.healthy ? response.ok(report) : response.badRequest(report)
})

With your server still running, open a browser tab and type localhost:3333/health

If everything worked fine and your database is connected, it should display the following screen.

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oprh8itnvqyzl8a1xx4f.png

Closing Thoughts

Thank you for following along, if you like the content and would like to know more about Adonis Development, bookmark this series, head over to my personal website or follow me on Twitter. You can also leave a comment in case you need any clarification or would like to point out an addition.

For the next piece, I'll be covering database models and relationships.

You can also follow the series on my personal website.

Stay tuned!


This content originally appeared on DEV Community and was authored by Ted Ngeene


Print Share Comment Cite Upload Translate Updates
APA

Ted Ngeene | Sciencx (2021-08-16T08:58:44+00:00) AdonisJs – Installation and Database Setup. Retrieved from https://www.scien.cx/2021/08/16/adonisjs-installation-and-database-setup/

MLA
" » AdonisJs – Installation and Database Setup." Ted Ngeene | Sciencx - Monday August 16, 2021, https://www.scien.cx/2021/08/16/adonisjs-installation-and-database-setup/
HARVARD
Ted Ngeene | Sciencx Monday August 16, 2021 » AdonisJs – Installation and Database Setup., viewed ,<https://www.scien.cx/2021/08/16/adonisjs-installation-and-database-setup/>
VANCOUVER
Ted Ngeene | Sciencx - » AdonisJs – Installation and Database Setup. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/08/16/adonisjs-installation-and-database-setup/
CHICAGO
" » AdonisJs – Installation and Database Setup." Ted Ngeene | Sciencx - Accessed . https://www.scien.cx/2021/08/16/adonisjs-installation-and-database-setup/
IEEE
" » AdonisJs – Installation and Database Setup." Ted Ngeene | Sciencx [Online]. Available: https://www.scien.cx/2021/08/16/adonisjs-installation-and-database-setup/. [Accessed: ]
rf:citation
» AdonisJs – Installation and Database Setup | Ted Ngeene | Sciencx | https://www.scien.cx/2021/08/16/adonisjs-installation-and-database-setup/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.