<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Ian Sam Mungai</title>
    <description>The latest articles on DEV Community by Ian Sam Mungai (@iansamz).</description>
    <link>https://dev.to/iansamz</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F213005%2F6489cf9f-60ec-462d-90e3-564efb89e561.jpeg</url>
      <title>DEV Community: Ian Sam Mungai</title>
      <link>https://dev.to/iansamz</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/iansamz"/>
    <language>en</language>
    <item>
      <title>Create Custom Database Module in NestJS with TypeORM MySQL/PostgreSQL</title>
      <dc:creator>Ian Sam Mungai</dc:creator>
      <pubDate>Thu, 01 Jul 2021 01:27:03 +0000</pubDate>
      <link>https://dev.to/iansamz/create-custom-database-module-in-nestjs-with-typeorm-mysql-postgresql-e7j</link>
      <guid>https://dev.to/iansamz/create-custom-database-module-in-nestjs-with-typeorm-mysql-postgresql-e7j</guid>
      <description>&lt;h1&gt;
  
  
  Intro
&lt;/h1&gt;

&lt;p&gt;First, Check out these articles for&lt;br&gt;
Custom Database Setup for Sequelize: &lt;a href="https://www.freecodecamp.org/news/build-web-apis-with-nestjs-beginners-guide/"&gt;https://www.freecodecamp.org/news/build-web-apis-with-nestjs-beginners-guide/&lt;/a&gt;&lt;br&gt;
Custom Database Setup for MongoDB: &lt;a href="https://dev.to/10xtarun/create-custom-database-module-in-nestjs-4kim"&gt;https://dev.to/10xtarun/create-custom-database-module-in-nestjs-4kim&lt;/a&gt;&lt;br&gt;
I got a lot of inspiration from these articles especially from the first by Victor&lt;/p&gt;
&lt;h1&gt;
  
  
  Setup Project
&lt;/h1&gt;

&lt;p&gt;We Create new nest project as,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ nest new custom-db-project
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will also install all we need,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ npm install --save @nestjs/typeorm @nestjs/config typeorm mysql2 dotenv

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now generate the custom database module as,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ nest generate module core/database
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;...&lt;br&gt;
Let's Code&lt;/p&gt;
&lt;h2&gt;
  
  
  Database Interface
&lt;/h2&gt;

&lt;p&gt;Inside the database folder, create an interfaces folder, then create a &lt;strong&gt;dbConfig.interface.ts&lt;/strong&gt; file inside it. This is for the database configuration interface.&lt;/p&gt;

&lt;p&gt;Each of the database environments should optionally have the following properties.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export interface IDatabaseConfigAttributes {
    username?: string;
    password?: string;
    database?: string;
    host?: string;
    port?: number;
    type?: string;
    urlDatabase?: string;
    entities?: string[];
    migrationsTableName?: string;
    migrations?: string[];
    cli?: {
        migrationsDir?: string;
    }
    synchronize?: boolean;
}

export interface IDatabaseConfig {
    development: IDatabaseConfigAttributes;
    test: IDatabaseConfigAttributes;
    production: IDatabaseConfigAttributes;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Database Configuration
&lt;/h2&gt;

&lt;p&gt;Now, let’s create a database environment configuration. Inside the database folder, create a &lt;strong&gt;database.config.ts&lt;/strong&gt; file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as dotenv from 'dotenv';
import { IDatabaseConfig } from './interfaces/dbConfig.interface';

dotenv.config();

let entities = [__dirname + '/**/*.entity{.ts,.js}']

let migrationsDir = 'src/migration';
let migrations = [migrationsDir + '/*.ts']

export const databaseConfig: IDatabaseConfig = {
    development: {
        username: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_NAME_DEVELOPMENT,
        host: process.env.DB_HOST,
        port: +process.env.DB_PORT,
        type: process.env.DB_DIALECT,
        entities: entities,
        migrationsTableName: process.env.DB_MIGRATION_TABLE_NAME,
        migrations: migrations,
        cli: {
            migrationsDir: migrationsDir
        },
        synchronize: true
    },
    test: {
        username: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_NAME_TEST,
        host: process.env.DB_HOST,
        port: +process.env.DB_PORT,
        type: process.env.DB_DIALECT,
        entities: entities,
        migrationsTableName: process.env.DB_MIGRATION_TABLE_NAME,
        migrations: migrations,
        cli: {
            migrationsDir: migrationsDir
        },
        synchronize: true
    },
    production: {
        username: process.env.DB_USER,
        password: process.env.DB_PASS,
        database: process.env.DB_NAME_PRODUCTION,
        host: process.env.DB_HOST,
        port: +process.env.DB_PORT,
        type: process.env.DB_DIALECT,
        entities: entities,
        migrationsTableName: process.env.DB_MIGRATION_TABLE_NAME,
        migrations: migrations,
        cli: {
            migrationsDir: migrationsDir
        },
        synchronize: true
    },
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The environment will determine which configuration should be used.&lt;/p&gt;

&lt;h2&gt;
  
  
  .env file
&lt;/h2&gt;

&lt;p&gt;On our project root folder, create a &lt;strong&gt;.env&lt;/strong&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB_HOST=localhost
DB_PORT=3306
DB_USER=database_user_name
DB_PASS=database_password
DB_DIALECT=postgres
DB_NAME_TEST=test_database_name
DB_NAME_DEVELOPMENT=development_database_name
DB_NAME_PRODUCTION=production_database_name
DB_MIGRATION_TABLE_NAME=migration

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Don't forget to add .env to your &lt;strong&gt;.gitignore&lt;/strong&gt; file. &lt;/p&gt;

&lt;h2&gt;
  
  
  Import the @nestjs/config
&lt;/h2&gt;

&lt;p&gt;Import the @nestjs/config into your app root module:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { DatabaseModule } from './core/database/database.module';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    DatabaseModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Victor Pointed out that Setting the ConfigModule.forRoot({ isGlobal: true }) to isGlobal: true will make the .env properties available throughout the application.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Database Provider
&lt;/h2&gt;

&lt;p&gt;Let’s create a database provider. Inside the database folder, create a file called &lt;strong&gt;database.providers.ts&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;The core directory will contain all our core setups, configuration, shared modules, pipes, guards, and middlewares.&lt;/p&gt;

&lt;p&gt;In the database.providers.ts let's add&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { TypeOrmModule } from '@nestjs/typeorm';
import { TYPEORM ,DEVELOPMENT, TEST, PRODUCTION } from '../constants';
import { databaseConfig } from './database.config';

export const databaseProviders = [{
    provide: TYPEORM,
    useFactory: async () =&amp;gt; {
      let config;
      switch (process.env.NODE_ENV) {
      case DEVELOPMENT:
         config = databaseConfig.development;
         break;
      case TEST:
         config = databaseConfig.test;
         break;
      case PRODUCTION:
         config = databaseConfig.production;
         break;
      default:
         config = databaseConfig.development;
      }

      const typeOrm = TypeOrmModule.forRoot(config);

      return typeOrm
    },
}];

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, the application decides what environment we are currently running on and then chooses the environment configuration.&lt;/p&gt;

&lt;p&gt;Best practice: It is a good idea to keep all string values in a constant file and export it to avoid misspelling those values. You'll also have a single place to change things.&lt;/p&gt;

&lt;p&gt;Inside the core folder, create a constants folder and inside it create an index.ts file. Paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const TYPEORM = 'TYPEORM';
export const DEVELOPMENT = 'development';
export const TEST = 'test';
export const PRODUCTION = 'production';
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I hope this article helps someone. Check out the article by Victor to get started with Nestjs&lt;/p&gt;

</description>
      <category>nestjs</category>
      <category>typeorm</category>
      <category>mysql</category>
      <category>postresql</category>
    </item>
  </channel>
</rss>
