Database

For this project, we will be using Postgres as a database and the ORM Sequelize. They are amongst the most popular. But you can find many other viable alternatives.

Run a local database

If you have installed docker, you can simply run the following command:

$ docker run -e POSTGRES_PASSWORD=postgres -e POSTGRES_DB=bookapp -p 5432:5432 postgres

Otherwise, you need to download and install it from the official website.

Find a GUI to interact with your database. Have a look at TablePlus (Free or $59) or PgAdmin (Open Source).

We should now be able to connect to our database:

Host: 127.0.0.1
Port: 5432
User: postgres
Password: postgres
Database: bookapp

Update the config and .env

export interface SharedConfig {
  logLevel: string;
  port: number;
  database: {
    dialect: "postgres";
    host: string;
    username: string;
    password: string;
    database: string;
    port: number;
    logging: boolean;
  };
}

export const sharedConfig: SharedConfig = {
  logLevel: process.env.LOG_LEVEL || "info", // we will come back to logs later
  port: parseInt(process.env.PORT || "1234"),
  database: {
    dialect: "postgres",
    host: process.env.PG_HOST || "",
    username: process.env.PG_USERNAME || "",
    password: process.env.PG_PASSWORD || "",
    database: process.env.PG_DATABASE || "",
    port: parseInt(process.env.PG_PORT || ""),
    logging: Boolean(parseInt(process.env.DB_LOGS || "0"))
  }
};

Models

Update our dependencies

You'll see the following message:

Fix it by installing the required dependencies:

Let's create a folder models to keep our files organised and create aLink model.

Create our Sequelize instance

and sync our model when we bootstrap the app

We should now see the link table in our database (try to refresh if you don't).

Migrations

Let's try to rename url to uriin our Link model and run the app again.

If we look in your UI, nothing changed.

This is because of CREATE TABLE IF NOT EXISTS. The table already exists and the statement gets ignored.

One way of solving this issue is to force sequelize to recreate all the tables with

This is fine while we are building database and we don't have any data in production. However, how do we deal with this once we're live? We write migrations

Umzung

Umzung is a framework agnostic migration tool for Node.js. We create migration files and umzug will run them one after the other. It will also store the last migration in a new table.

We will store our files in a new migrations folder and create our migration 001_rename_url_to_uri.ts.

We need a file to configure the migration

And run the migration when we start the app

Run the app

Two things happened:

  • url has been renamed to uri.

  • A new table SequelizeMeta has been created.

SequelizeMeta will keep track of the latest migration.

database branch available on GitHub.

Last updated

Was this helpful?