TypeORM is one of the most popular ORMs out there. It can run in a wide variety of platforms and help connect our applications to various databases. However, NodeJS is arguably the most widely used platform for using TypeORM. With a tremendous increase in the popularity of Typescript, it is quite common to build a NodeJS Typescript TypeORM application.

To start with a NodeJS Typescript TypeORM application, we need to mainly install the typeorm package along with the database driver. Post the installation, we need to setup TypeORM datasource configuration and declare entities. However, there are important points to consider in the whole process.

We will look at the entire process in this post with code examples.

1 – Installation of NodeJS Typescript TypeORM packages

The first step is to install the appropriate packages. See below command:

$ npm install --save typeorm reflect-metadata pg

The typeorm package is the common core package irrespective of the database choice. Next, we have the reflect-metadata package. It is used to handle runtime reflection on types. To make it work, we need to import it globally in our app.

Lastly, we have the database-specific driver package. In this case, we are using PostgreSQL and hence we install the pg package.

Also, since we are working with Typescript, we need to install some additional packages.

$ npm install --save-dev typescript @types/node ts-node

Basically, these are all development dependencies.

Finally, we also need to perform some settings in the tsconfig.json file.

"emitDecoratorMetadata": true,
"experimentalDecorators": true,

While it is a possible to setup our TypeORM application manually, we can avoid the hassle of installing all the packages and creating files by using the CLI.

For example, we can create a new TypeORM Typescript project for NodeJS using the below command:

$ npx typeorm init --name typeorm-nodejs-demo --database postgres

Basically, this will initialize a new project for us with all the necessary files and setup configuration. The –database flag is used to specify the database we want to use.

2 – Configuring the TypeORM DataSource with Typescript & NodeJS

The most important file in the TypeORM project is the data-source.ts. Basically, this is the TypeORM DataSource where we specify the database configuration of our application.

See below:

import "reflect-metadata"
import { DataSource } from "typeorm"
import { User } from "./entity/User"

export const AppDataSource = new DataSource({
    type: "postgres",
    host: "localhost",
    port: 5432,
    username: "test",
    password: "test",
    database: "testdb",
    synchronize: true,
    logging: false,
    entities: [User],
    migrations: [],
    subscribers: [],
})

As you can see, we create a new instance of the TypeORM DataSource class. The constructor of the class takes a configuration object as input.

Within the object, we specify the database host details and database credentials in this particular configuration file. Also, for entity discovery, we provide a list of entities in the entities array. The entities are equivalent to tables in the actual database.

Do notice the import statement for reflect-metadata. Basically, this is a global import for the package.

3 – Using the TypeORM DataSource with Entity

Once the TypeORM DataSource is defined, we can use it to interact with the database.

First, we can declare an Entity as below:

import { Entity, PrimaryGeneratedColumn, Column } from "typeorm"

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number

    @Column()
    firstName: string

    @Column()
    lastName: string

    @Column()
    age: number
}

Notice that this is the same Entity class that we import in the data source. We use special decorators such as @Entity, @PrimaryGeneratedColumn and @Column from the typeorm package.

Now, we can initialize the database connection and perform operations on it.

See below:

import { AppDataSource } from "./data-source"
import { User } from "./entity/User"

AppDataSource.initialize().then(async () => {

    console.log("Inserting a new user into the database...")
    const user = new User()
    user.firstName = "Daniel"
    user.lastName = "Craig"
    user.age = 50
    await AppDataSource.manager.save(user)
    console.log("Saved a new user with id: " + user.id)

    console.log("Loading users from the database...")
    const users = await AppDataSource.manager.find(User)
    console.log("Loaded users: ", users)

}).catch(error => console.log(error))

We call the initialize() function available with the AppDataSource. This function returns a promise. In the promise resolve callback, we create an instance of the User entity and insert the same into database. Also, we retrieve the user records by using the DataSource manager.

Conclusion

In this post, we have successfully built a NodeJS Typescript application using TypeORM. We explored the configuration aspects of TypeORM DataSource and how we can define an entity.

Want to learn how to use TypeORM in building a fully functional application? If yes, check out this post on NestJS TypeORM integration.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: BlogNodeJS

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *