Create a Rest API with Express, PostgreSQL, TypeOrm, and TypeScript
By: Jose Luis Campos Bautista
Tags: Web Development, Programming, Typescript, Expressjs, Postgresql

Create a Rest API with Express, PostgreSQL, TypeOrm, and TypeScript

Create a Rest API with Express, PostgreSQL, TypeOrm, and TypeScript.

Prerequisites

Please make sure that Node.js (>= 10.13.0) is installed on your operating system and docker.

Init project

We need to create our project, firstly create blog directory.

mkdir blog

Later, go to blog directory and init the project.

cd blog npm init

The last command going to create a package.json file, its purpose is to handle the history of all dependencies installed in our project.

package.json

Install dependencies

To our API Rest, we need the next dependencies, express, pg, TypeOrm, typescript.

Install dependencies dev dependencies.

npm install typescript @types/express @types/node --save-dev

We will only use the last dependencies to develop our API.

Now, install the dependencies that we’ll use in the production environment.

npm install express pg typeorm

express: This is a web application framework for NodeJS.

pg: It is a collection of NodeJS modules for interfacing with your PostgreSQL database.

Typescript: It’s a language for application-scale JavaScript, this module helps us to add optional types to JavaScript that support tools for large-scale JavaScript applications for any browser.

typeorm: It’s an ORM that runs in Node JS that can use with TypeScript and JavaScript (ES5, ES6, ES7, ES8).

@types/express, @types/node: these packages help us with the type definitions for Express and NodeJS.

packahe.json file with our dependencies.

Configuring TypeScript

First, we need to add a command into the package.json file to execute commands of the typescript module. In the section of scripts add the next line.

“tsc”: “tsc “

Now, we going to configure TypeScript in our project, execute the command below:

npm run tsc -- --init

The last command generates tsctsconfig.json, this file indicates that we are going to working with TypeScript. This file contains the working setup for TypeScript transpillation.

In the file, we add the next lines, those lines help us with the configuration of the build and root directories.

“outDir”: “./build”,

“rootDirs”: [“./src”],

rootDirs: This configuration list who combined represent the project.

outDir: This line redirects the output of compiled files.

Configuring our server

We going to create the src directory and server.ts file.

mkdir src

cd src

touch server.ts

Once created our sever.ts file we going to create a class called Server and the constructor, configuration, routes, and start method.

Basic server configuration.

Once created the class and methods execute the command below to convert our TypeScript code to JavaScript.

npm run tsc

Remember the tsctsconfig.json configurations, the JavaScript files will generate into the build directory.

Now, start the server with the next command.

node ./build/server.js

After that. try to go to the next link http://localhost:3000/.

Create controllers

In this example of API, we going to use controllers to handle the routes, we need to create the controller directory and the post.controller.ts file.

In this controller, we going to handle the methods to the CRUD.

Example of controller file.

Now into our class server, we need to import the controller and configure new routes.

Server with the post controller configuration.

Next, execute the command below:

npm run tsc

node ./build/server.js

And try to access the new routes of the post controller. http://localhost:3001/api/posts

If you want to prove all the methods of post controller use postman.

Create services

In some cases, we need to get data from different places thus database or another API, for this reason, we need to handle this operation in an exclusive file. In this practice, we’ll use services to handle these tasks.

Create a new directory called services and the file post.service.ts.

Example of post-service file.

Import the new service into the controller file and execute each method.

Now, in the controller, we execute the method from service.

Now execute commands to transpillate our code and start the server.

npm run tsc

node ./build/server.js

Now you get the message from the post-service.

In the next section, we’ll configure the database and execute some queries.

Create the database

For this practice, we going to use Docker containers, you can get some information about how to install docker in the documentation.

Once Docker installed, run the next command:

docker run -d -p 5433:5432 — name blog -e POSTGRES_USER=blog -e POSTGRES_PASSWORD=blog — mount src=db-blog,dst=/var/lib/postgresql/data postgres

The flag -d indicates that the container going to execute in detach mode in the background.

The flag -p 5433:5432 specifies that the container will configure the port 5432 and we can access it with the 5444 from localhost.

— name blog specify the name of our container.

In the line -e POSTGRES_PASSWORD=password we specified an environment variable POSTGRES_PASSWORD.

You can validate if the container was launched correctly using PgAdmin.

Start session in our database.

Configure the database connection

In this section, we going to configure the database connection with our API using typeorm.

Create the connection

In the server file, we import createConnection function from TypeOrm, in this section we use async functions, so if you want to learn more about this topic visit the documentation.

Database configuration.

The last picture shows how to create a new connection, It needs the type of database, port, host, username, password, database name. The method createConnection was imported from the TypeOrm module.

Our method database Configuration going to execute into routes method and wait until the connection finished. It’s important the connection before starting with routes configuration.

If you want to know more about the different ways to create a connection visit typeorm’s documentation.

Create entities

Well, we have the database connection, so the next step is to configure the entities of our application. According to TypeOrm’s documentation, an entity is a class that maps to a database table, you can define an entity using the annotation @Entity().

If you remember, in the configuration of the database we have these line entities: [“build/database/entities/**/*.js”], so we need to create the directory src/database/entities, and this directory will contain our entities.

Create a class called PostEntity and in this class, we define our table posts.

Post entity example.

@PrimaryGeneratedColumn() generate a primary column which value will be automatically generated and @Column() define a column of our database.

Create custom repository

All the actions that we need to do, we’ll do in the repository file, in this file we connect to a specific table and execute some actions such as update, create, delete, and other DML operations.

Create the src/repository directory and a file called post.repository.ts and create the class PostRepository like class bellow.

Example of a repository with TypeOrm.

The class PostRepository extends from the Repository class, this class lets us work with our entity objects. Find entities, insert, update, delete, etc, and @EntityRepository() is used to declare a class as a custom repository.

Integrate services with the repositories

Now we have all necessary to finish our API, we have the controllers, services, and repositories, in this section we integrate all the components.

First, we’ll import PostRepository into the class PostService, and initialize the repository with some commands from TypeOrm module. The methods that we’ll use are getConnection() this method helps us to get a specific connection, for example, our connection was called blog and getCustomRepository() get the custom repository for example PostRepository, once initialized the service we can execute some methods, for example, find(), this method retrieves all registers into the table posts.

Implementation of PostRepository.

Now transpillate the code and start the server.

npm run tsc

node ./build/server.js

Insert some data into posts table and you can access to the next url http://localhost:3000/api/posts and get data.

Get data from database with our API.

Now, we implemetn the create, update and delete methods, Its necesary to update the controller and the service.

Post Controller.

Post-service.

Now you can compile the code test the API, with Postman.

Get all posts.

Creta a post.

With this, we finish the practice, but you can see the complete code on GitHub.

Conclusion

Let’s look at what we have learned.

How to create a single Rest API with express.

Configuration of typescript.

Configuration of Typeform.

How to configure controllers, services, and repositories.

How to configure PostgreSQL Docker container.

First of all, thanks for reading and I hope this little tutorial will help you.

Kindest Regards.