In NestJS Boilerplate uses TypeORM and PostgreSQL for working with database, and all examples will for PostgreSQL, but you can use any database.
-
Create entity file with extension
.entity.ts
. For examplepost.entity.ts
:// /src/posts/entities/post.entity.ts import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm'; import { EntityHelper } from 'src/utils/entity-helper'; @Entity() export class Post extends EntityHelper { @PrimaryGeneratedColumn() id: number; @Column() title: string; @Column() body: string; // Here any fields what you need }
-
Next, generate migration file:
npm run migration:generate -- src/database/migrations/CreatePostTable
-
Apply this migration to database via npm run migration:run.
npm run migration:run
npm run migration:revert
npm run schema:drop
-
Go to
src/database/seeds
and create directory for your seed. For examplepost
-
Create 2 files: module and service. For example:
post-seed.module.ts
andpost-seed.service.ts
:// /src/database/seeds/post/post-seed.module.ts import { Module } from '@nestjs/common'; import { TypeOrmModule } from '@nestjs/typeorm'; import { Post } from 'src/posts/entities/post.entity'; import { PostSeedService } from './post-seed.service'; @Module({ imports: [TypeOrmModule.forFeature([Post])], providers: [PostSeedService], exports: [PostSeedService], }) export class PostSeedModule {}
// /src/database/seeds/post/post-seed.service.ts import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Post } from 'src/posts/entities/post.entity'; import { Repository } from 'typeorm'; @Injectable() export class PostSeedService { constructor( @InjectRepository(Post) private repository: Repository<Post>, ) {} async run() { const count = await this.repository.count(); if (count === 0) { await this.repository.save( this.repository.create({ title: 'Hello', body: 'World', }), ); } } }
-
Go to
src/database/seeds/seed.module.ts
and add your module toimports
. For example:// /src/database/seeds/seed.module.ts // Some code here... import { PostSeedModule } from './post/post-seed.module'; @Module({ imports: [ // Some code here... PostSeedModule, ], }) export class SeedModule {}
-
Go to
src/database/seeds/run-seed.ts
and invoke methodrun
from your service inrunSeed
function. For example:// /src/database/seeds/run-seed.ts // Some code here... import { PostSeedService } from './post/post-seed.service'; const runSeed = async () => { // Some code here... await app.get(PostSeedService).run(); // Some code here... }; // Some code here...
-
Run npm run seed:run
npm run seed:run
Don't forget to create indexes
on the Foreign Keys (FK) columns (if needed), because by default PostgreSQL does not automatically add indexes to FK.
Set the optimal number of max connections to database for your application in /.env
:
DATABASE_MAX_CONNECTIONS=100
You can think of this parameter as how many concurrent database connections your application can handle.
Next: Auth