API with NestJS #2. Setting up a PostgreSQL database with TypeORM

JavaScript NestJS TypeScript

The next important thing when learning how to create an API is how to store the data. In this article, we look into how to do so with PostgreSQL and NestJS. To make the managing of a database more convenient, we use an Object-relational mapping (ORM) tool called TypeORM. To have an even better understanding, we also look into some SQL queries. By doing so, we can grasp what advantages ORM gives us.

You can find all of the below code in this repository.

Creating a PostgreSQL database

The most straightforward way of kickstarting our development with a Postgres database is to use docker.
Here, we use the same setup as in the TypesScript Express series.

The first thing to do is to install Docker and Docker Compose. Now, we need to create a docker-compose file and run it.

docker-compose.yml

The useful thing about the above configuration is that it also starts a pgAdmin console. It gives us the possibility to view the state of our database and interact with it.

To provide credentials used by our Docker containers, we need to create the docker.env file. You might want to skip committing it by adding it to your .gitignore.

docker.env

Once all of the above is set up, we need to start the containers:

Environment variables

A crucial thing to running our application is to set up environment variables. By using them to hold configuration data, we can make it easily configurable. Also, it is easier to keep sensitive data from being committed to a repository.

In the Express Typescript series, we use a library called dotenv to inject our variables. In NestJS, we have a   that we can use in our application. It uses dotenv under the hood.

app.module.ts

As soon as we create a .env file at the root of our application, NestJS injects them into a ConfigSerivice that we will use soon.

.env

Validating environment variables

It is an excellent idea to verify our environment variables before running the application. In the TypeScript Express series, we’ve used a library called envalid.

The   built into NestJS supports @hapi/joi that we can use to define a validation schema.

app.module.ts

Connecting a NestJS application with PostgreSQL

A first thing to do once we have our database running is to define a connection between our application and the database. To do so, we use  .

To keep our code clean, I suggest creating a database module.

database.module.ts

The synchronize flag above is very important. We will elaborate on it a lot later

An essential thing above is that we use the  and . The   method can access the environment variables thanks to providing the   and   arrays. We elaborate on these mechanisms in the upcoming parts of this series.

Now, we need to import our .

app.module.ts

Entities

The most crucial concept to grasp when using TypeORM is the entity. It is a class that maps to a database table. To create it, we use the   decorator.

post.entity.ts

A neat thing about TypeORM is that it integrates well with TypeScript because it is written in it. To define our columns, we can use various decorators.

@PrimaryGeneratedColumn()

primary key is a column used to identify a row uniquely in a table. Although we might use an existing column and make it primary, we usually create an id column. By choosing   from TypeORM, we create an integer primary column that has a value generated automatically.

@Column()

The   decorator marks a property as a column. When using it, we have two possible approaches.

The first approach is not to pass the column type explicitly. When we do it, TypeORM figures out the column using our TypeScript types. It is possible because NestJS uses reflect-metadata under the hood.

The second approach would be to pass the type of column explicitly, for example, by using  . The available column types differ between databases like MySQL and Postgres. You can look them up in the TypeORM documentation.

It is a proper moment to discuss different ways to store strings in Postgres. Relying on TypeORM to figure out the type of a string column results in the “character varying” type, also called varchar.

Varchar is very similar to a text type of a column but gives us a possibility to limit the length of a string. Both types are the same performance-wise.

SQL query

In pgAdmin, we can check a query equivalent to what TypeORM did for us under the hood.

There are a few interesting things to notice above

Using   results in having an int column. It defaults to the return value of a   function that returns unique ids. An alternative would be to use a serial type instead and would make the query shorter, but it works the same under the hood.

Our entity has varchar columns that use COLLATE. Collation is used to specify the sort order and character classification. To see our default collation, we can run this query:

en_US.utf8

The above value is defined in a query that was used to create our database. It is UTF8 and English by default.

Also, our   query puts a constraint on our ids so that they are always unique.

PK_be5fda3aac270b134ff9c21cdee is a name of the above constraint and was generated

Repositories

With repositories, we can manage a particular entity. A repository has multiple functions to interact with entities. To access it, we use the   again.

posts.module.ts

Now, in our  , we can inject the Posts repository.

Finding

With the  function, we can get multiple elements. If we don’t provide ith with any options, it returns all.

To get just one element we use the   function. By providing it with a number we indicate that we want an element with a particular id. If the result is undefined, it means that the element wasn’t found.

Creating

By using the  function, we can instantiate a new Post. We can use the  function afterward to populate the database with our new entity.

Modifying

To modify an existing element, we can use the  function. Afterward, we would use the   function to return the modified element.

A significant thing is that it accepts a partial entity, so it acts as a PATCH, not as a PUT. If you want to read more on PUT vs PATCH (although with MongoDB), check out TypeScript Express tutorial #15. Using PUT vs PATCH in MongoDB with Mongoose

Deleting

To delete an element with a given id, we can use the   function.

By checking out the documentation of the DELETE command, we can see that we have access to the count of removed elements. This data is available in the   property. If it equals zero, we can assume that the element does not exist.

Handling asynchronous errors

A beneficial thing about NestJS controllers is that they handle asynchronous errors very well.

If the   function throws an error, NestJS catches it automatically and parses it. When using pure Express, we would do this ourselves:

Summary

In this article, we’ve gone through the basics of connecting our NestJS application with a PostgreSQL database. Not only did we use TypeORM, but we’ve also looked into some SQL queries. NestJS and TypeORM have lots of features built-in and ready to use. In the upcoming parts of this series, we will look into them more, so stay tuned!

Series Navigation<< API with NestJS #1. Controllers, routing and the module structureAPI with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies >>
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Kuba
Kuba
28 days ago

I like the series but posts tend to be really chaotic and missing some steps/vital information. Like here – where does docker start pgadmin ?Or you define the post entity, and then check the table structure in pgadmin, but we’ve never actually run anything yet. And you can’t run the server at this step, since the rest of the app was not updated (post.service for instance).

Hossein
Hossein
24 days ago

Thanks for this great article. It helps much.
I have two questions.

1. There is any way that automates the creation of the DB?
It seems that we should write our query manually, and I think it’s not much interested that do the exact same thing when we want to deploy it on real servers or event Netlify.

2. How to have only one .env file in dockerized projects?
I’m working on a dockerized project that some variables are shared between them. I don’t want to have separated .env files for each project.

Thanks and best of luck.