Setting up Adonis v5 with PostgreSQL 
Tags: tutorial, adonis, postgres, api
Published: 2020-09-19 23:08:39

> In this multi-part tutorial, we'll create and deploy a multi-server architecture web application. 

> Part 1: [Creating a front-end using NuxtJS and TailwindCSS](https://dev.to/armiedema/create-and-deploy-a-multi-server-app-w-adonis-nuxt-and-cleaver-part-1-set-up-front-end-5185)
> Part 2: Setting up Adonis v5 with PostgreSQL 
> Part 3: [Creating a REST API using Adonis v5](https://dev.to/armiedema/creating-a-rest-api-using-adonis-v5-4n1p)
> Part 4: [Connecting Nuxt front-end to Adonis 5 API](https://dev.to/armiedema/connecting-nuxt-front-end-to-adonis-5-api-using-axios-1ego)
> Part 5: [Deploying a multi-server app with Cleavr](https://dev.to/armiedema/deploying-a-multi-server-app-with-cleavr-3jh3)

#### Frameworks and tools used
* Front-end: [NuxtJS](https://nuxtjs.org/) and [TailwindCSS/UI](https://tailwindcss.com/)
* Back-end: [AdonisJS](https://adonisjs.com/) 
* Database: [PostgreSQL](https://www.postgresql.org/)
* Server provision and deployment: [Cleavr](https://cleavr.io)

# Part 2 - Setting up Adonis v5 with PostgreSQL

AdonisJS version 5 is now available to preview and brings about a huge overhaul as it is completely re-written in Typescript. We'll be using version 5 in this tutorial and you can check out the [new documentation here](https://preview.adonisjs.com/guides/quick-start/).   

## Install AdonisJS v5 on your local machine

{% youtube mtUemPG1yNg %}

We'll first install our Adonis project via the terminal by running the following command. 

```bash
yarn create adonis-ts-app movieapi
```

Swap out `movieapi` if you want to name your project something else.

When asked, select the option for `API Server` as we will be creating an API only. 

Once the installation is complete, you'll be prompted to run the following commands. 

```
cd movieapi
node ace serve --watch
```

This will open up the `movieapi` directory and then serve our starter project. 

Your app will be served on your localhost, copy and paste the `<address>:<port number>` from the terminal and paste into your web browser.

If you see the following appear on your browser, then you're off to a good start!

```json
{"hello":"world"}
``` 

## Install PostgreSQL drivers for AdonisJS v5

{% youtube LNpjCdLu9jw %}

We'll now work on installing database drivers for PostgreSQL. You may choose to use a different database type. If so, follow the [instructions for the database type you want to use](https://preview.adonisjs.com/guides/database/setup/).  

No matter the database type you choose, you'll first need to install `lucid`. 

```
cd movieapi
yarn add @adonisjs/lucid@alpha
```

Next, run:
```
node ace invoke @adonisjs/lucid
```

You'll then be asked which database drivers to install. I'll select PostgreSQL. 

Lastly, let's finish up configuring the Postgres driver. 

```
npm i pg
```

## Check the database connection between Adonis and Postgres

{% youtube y4jZ8VPoYiw %}

First, make sure you have an instance of PostgreSQL running on your machine. 

[DBngin](https://dbngin.com/) offers a quick and easy way to manage local database servers. I'll use it to run a PostgreSQL server on my machine, and then I'll connect to it via TablePlus and add a new database named `movies`.

Now, open up the `movieapi` project in IntelliJ and navigate to the `database.ts` file to configure database connections. 

```typescript
pg: {
      client: 'pg',
      connection: {
        host: Env.get('DB_HOST', '127.0.0.1') as string,
        port: Number(Env.get('DB_PORT', 5432)),
        user: Env.get('DB_USER', 'postgres') as string,
        password: Env.get('DB_PASSWORD', '') as string,
        database: Env.get('DB_NAME', 'movies') as string,
      },
      healthCheck: true,
    },
```

Note - `postgres` is typically the default username for new PostgreSQL installations. 

Also, we'll want to make sure that `healthCheck` is set to `true` as Adonis only attempts to establish a connection with the database when queries are ran. And, using the health check feature is a quick way to test the database connection. 

From the configs above, you can see that Adonis will first check to see if the variables exist in the .env file; so, we'll need to make sure we change the defaults in the .env file as well. 

```
DB_USER=postgres
DB_PASSWORD=
DB_NAME=movies
```

Now, let's open `routes.ts`, import health check, and then add a health check route. 

```typescript
import HealthCheck from '@ioc:Adonis/Core/HealthCheck'

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

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

We can now check the connection. You may need to re-run `node ace serve --watch` if the process stopped. 

Also, I received an error at this step and had to install `proxy-addr` to continue. If you get this error as well, just run the following command and then re-serve the project. 

```
npm install proxy-addr
```

Open up your browser and append the url with `/health` to see the results of the health check. If you've successfully established a connection with your database, you'll see the following message: 

```json
{"healthy":true,"report":{"env":{"displayName":"Node Env Check","health":{"healthy":true}},"appKey":{"displayName":"App Key Check","health":{"healthy":true}},"lucid":{"displayName":"Database","health":{"healthy":true,"message":"All connections are healthy"},"meta":[{"connection":"pg","message":"Connection is healthy","error":null}]}}}
```

Now that our Adonis and PostgreSQL connection is setup and is working, we'll continue creating our API in [part 3](https://dev.to/armiedema/creating-a-rest-api-using-adonis-v5-4n1p).  

---
Following along? View Part 2 progress on GitHub at https://github.com/armgitaar/moviesapi. 

[Watch the full tutorial series uninterrupted on Youtube.](https://www.youtube.com/playlist?list=PLApnZzwJN4G5gHKMr4owbFKUdAtdwPB-X)