Go to Blogs
How to integrate TypeORM in a Node.js and Express.js application

How to integrate TypeORM in a Node.js and Express.js application

For this tutorial, go ahead and clone this repo.

Once cloned, install dependencies

npm install

Now, install TypeORM and other required dependencies.

npm install typeorm reflect-metadata mysql2

Import reflect-metadata in the main.ts file at the top

import "reflect-metadata";
...
// Remaining code here

Now enable these two settings in the tsconfig.json file

{  
  "emitDecoratorMetadata": true,  
  "experimentalDecorators": true  
}  

Create a datasource file in db/datasource.ts

const entitiesPath = path.resolve(__dirname, "./entity") + "/*.ts";
const migrationsPath = path.resolve(__dirname, "./migration") + "/*.ts";

export const AppDataSource = new DataSource({
    type: "mysql",
    host: "localhost",
    port: 3306,
    username: "root",
    password: "root",
    database: "typeorm_demo_db",
    synchronize: process.env.NODE_ENV !== "production",
    logging: process.env.NODE_ENV !== "production",
    entities: [entitiesPath],
    migrations: [migrationsPath],
})

Initialize the datasource in the main.ts file

const main = async () => {
	await AppDataSource.initialize()
}

main()

Create an entity file in db/entity/post.ts

export enum PostStatus {
  PUBLISHED = "published",
  DRAFT = "draft"
}  
  
@Entity()
export class Post {  
    @PrimaryGeneratedColumn("uuid")
    id: string;
    
    @Column()
    title: string;
    
    @Column()
    content: string;
    
    @Column({
        type: "enum",
        enum: PostStatus,
    })
    status: PostStatus;
    
    @CreateDateColumn()
    createdAt: Date;
    
    @UpdateDateColumn()
    updatedAt: Date;  
}  

Go into modules/post/service.ts file and write code to create the post

const postRepository = AppDataSource.getRepository(Post);

export const addPost = async (data: DeepPartial<Post>) => {
  return postRepository.save(data);
};  

Using Thunderclient, make a POST call to the url http://localhost:4000/post create a post with below data

{
	"title": "Demo Title",
	"content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
	"status": "published"
}

Go into modules/post/service.ts file and write code to get the post

const postRepository = AppDataSource.getRepository(Post);

export const findPosts = async (query: FindManyOptions<Post>) => {
  return postRepository.find(query);
};  

Using Thunderclient, make a GET call to the url http://localhost:4000/post get posts

Written On: 11 Nov, 2024

Last Updated On: 11 Nov, 2024

Abhishek Diwakar

Abhishek Diwakar

Software Engineer