Learn NestJS with MikroORM by Creating a Blog Project
2024-06-01
In the world of Node.js, frameworks like NestJS have transformed the landscape of building server-side applications by introducing a scalable, maintainable, and modular architecture. Coupled with MikroORM, an intuitive TypeScript ORM, you get a powerful duo that promotes code reliability and database management. This post will guide you through setting up a simple blog application using NestJS and MikroORM.
Prerequisites
Before we dive in, ensure you have the following installed:
- Node.js
- Docker (for running the PostgreSQL database)
Step 1: Setting Up Your NestJS Project
First, install the NestJS CLI globally, if you haven't already:
npm install -g @nestjs/cli
Create a new project:
nest new blog-nest
Navigate to your project directory:
cd blog-nest
Step 2: Integrating MikroORM
Install MikroORM and the PostgreSQL driver:
npm install @mikro-orm/core @mikro-orm/nestjs @mikro-orm/postgresql pg
Create a mikro-orm.config.ts
at the root of your project to configure MikroORM:
import { MikroOrmModuleSyncOptions } from '@mikro-orm/nestjs';
import { Post } from './src/posts/post.entity';
const config: MikroOrmModuleSyncOptions = {
entities: [Post],
dbName: 'blog',
type: 'postgresql',
user: 'test',
password: 'test',
};
export default config;
Step 3: Running PostgreSQL in Docker
Set up a docker-compose.yml
file to run PostgreSQL:
version: '3.8'
services:
postgres:
image: postgres:latest
environment:
POSTGRES_DB: blog
POSTGRES_USER: test
POSTGRES_PASSWORD: test
ports:
- "5432:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
volumes:
postgres-data:
Start your PostgreSQL database:
docker-compose up -d
Step 4: Building the Blog API
Define your Post entity:
import { Entity, PrimaryKey, Property } from '@mikro-orm/core';
@Entity()
export class Post {
@PrimaryKey()
id!: number;
@Property()
title!: string;
@Property()
content!: string;
}
Create the Posts module, service, and controller to handle CRUD operations.
Posts Module
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { PostsController } from './posts.controller';
import { PostsService } from './posts.service';
import { Post } from './post.entity';
@Module({
imports: [MikroOrmModule.forFeature([Post])],
controllers: [PostsController],
providers: [PostsService],
})
export class PostsModule {}
Posts Service
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { EntityRepository } from '@mikro-orm/core';
import { Post } from './post.entity';
@Injectable()
export class PostsService {
constructor(
@InjectRepository(Post)
private readonly postRepository: EntityRepository<Post>
) {}
async findAll(): Promise<Post[]> {
return this.postRepository.findAll();
}
}
Posts Controller
import { Controller, Get } from '@nestjs/common';
import { PostsService } from './posts.service';
import { Post } from './post.entity';
@Controller('posts')
export class PostsController {
constructor(private readonly postsService: PostsService) {}
@Get()
async findAll(): Promise<Post[]> {
return this.postsService.findAll();
}
}
Step 5: Running the Application
Run your application and navigate to http://localhost:3000/api/posts
to see the posts retrieved from the database:
npm run start
Conclusion
You've just set up a basic blog API using NestJS and MikroORM, with a PostgreSQL database running in a Docker container. This project lays the foundation for building scalable and maintainable applications with advanced features like data mapping, dependency injection, and modular architecture.
For the complete source code, check out the GitHub repository: blog-nest.
NestJS and MikroORM are powerful tools in your Node.js arsenal. By mastering them, you can greatly enhance your backend development capabilities. Happy coding!