install npm install --save @nest/typeorm typeorm pg
Pg is for postgre that we are going to use in this
these are the two modules we are going to use
Make a Configuration Folder and add this type of code according to what configuration you have used
import {TypeOrmModuleOptions } from '@nestjs/typeorm' export const typeOrmConfig: TypeOrmModuleOptions = { type: 'postgres', host: 'localHost', port: 5432, username: 'postgres', password: 'postgre', //Password usually the same unless you have changed some settings.. database: 'taskmanagement', Most important thing because what you have made on the app. it should be the same entities: [__dirname + '/../**/*.entity.ts'], synchronize: true, };
Any Mistake in this configuration will lead to the app crash.
Now Import these to the APP Module
import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { TasksModule } from './tasks/tasks.module'; import { typeOrmConfig } from './config/typeorm.config';
@Module({ imports: [ TypeOrmModule.forRoot(typeOrmConfig), TasksModule], })
) export class AppModule {}
These are the basics steps you should follow for connecting a nestJs with a database of typeORM (POSTGRE Sql)
Create A Task Entity
In TypeORM we define entities that represent tables and those entities then carry logiic under the hood that makes our work easy to work on database: so that we dont have to write too many queries.
import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from "typeorm"; import { TaskStatus } from "./task.model"; @Entity() export class Task extends BaseEntity{ @PrimaryGeneratedColumn() //This tells TYPEORM that it is a primary key automatically generated and incremented whenever we create a new task id: number; @Column() title: string; @Column() description: string; @Column() status: TaskStatus; }
We have created an entity for a class we can use this class in our service to perform operations such as finding task Deleting task --- CRUD Operations. However this could end up in lot of codes for simple database Operations. We can split the code and make a repository
Creating a Task Repository
We can do the same all operations we can do on the entity but we can also do some cutom logic to our database
Create a new folder under task
import { Task } from "./task.entity"; import { EntityRepository, Repository } from "typeorm"; @EntityRepository(Task) export class TaskRepository extends Repository <Task> { }
and also import this into Task Module
@Module({ imports: [ TypeOrmModule.forFeature([TaskRepository]), ],
Comentarios