<?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>Forem: phin</title>
    <description>The latest articles on Forem by phin (@saiphin).</description>
    <link>https://forem.com/saiphin</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%2F651325%2Fa6f6b237-f0e9-4d7a-9a73-c946db993bd2.png</url>
      <title>Forem: phin</title>
      <link>https://forem.com/saiphin</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/saiphin"/>
    <language>en</language>
    <item>
      <title>Setup Node.js API with Prisma, TypeScript, and PostgreSQL</title>
      <dc:creator>phin</dc:creator>
      <pubDate>Sun, 05 Mar 2023 16:58:37 +0000</pubDate>
      <link>https://forem.com/saiphin/setup-nodejs-api-with-prisma-typescript-and-postgresql-14e4</link>
      <guid>https://forem.com/saiphin/setup-nodejs-api-with-prisma-typescript-and-postgresql-14e4</guid>
      <description>&lt;p&gt;&lt;strong&gt;What the course will cover&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;How to spawn docker containers with docker-compose&lt;/li&gt;
&lt;li&gt;How to connect a Prisma Express app to the PostgreSQL database&lt;/li&gt;
&lt;li&gt;How to connect a Prisma Express app to the Redis database&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Prerequisites&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To follow along with this tutorial, make sure you have the following:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Software&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://nodejs.org/en/download/"&gt;Node JS&lt;/a&gt; – for writing the backend logic&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.docker.com/products/docker-desktop/"&gt;Docker&lt;/a&gt; – for packaging applications in containers&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;VS Code Extensions&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-docker"&gt;Docker&lt;/a&gt;(optional) – To manage docker containers directly in VS Code&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://marketplace.visualstudio.com/items?itemName=Prisma.prisma"&gt;Prisma&lt;/a&gt; – Adds syntax highlighting, formatting, auto-completion, and linting for &lt;code&gt;.prisma&lt;/code&gt; files.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Assumed Knowledge&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You already know the basics of JavaScript, TypeScript, and Node.js&lt;/li&gt;
&lt;li&gt;You have basic knowledge of SQL, PostgreSQL, Redis, Prisma, and Docker&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  How to Setup Node.js with Express, PostgreSQL, Redis, and Prisma.
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Creating PostgreSQL and Redis Database with Docker-compose&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The most obvious way to get PostgreSQL and Redis databases running on your machine is to use Docker and Docker-compose.&lt;/p&gt;

&lt;p&gt;Am going to assume you already have &lt;a href="https://docs.docker.com/get-docker/"&gt;Docker&lt;/a&gt; and &lt;a href="https://docs.docker.com/compose/install/"&gt;Docker-compose&lt;/a&gt; installed on your computer.&lt;/p&gt;

&lt;p&gt;In the root directory create a &lt;code&gt;docker-compose.yml&lt;/code&gt; file and paste the configurations below into it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;docker-compose.yml&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;version: '3'
services:
  postgres:
    image: postgres:latest
    container_name: postgres
    ports:
      - '6500:5432'
    volumes:
      - progresDB:/data/postgres
    env_file:
      - ./.env

  redis:
    image: redis:alpine
    container_name: redis
    ports:
      - '6379:6379'
    volumes:
      - redisDB:/data
volumes:
  progresDB:
  redisDB:

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

&lt;/div&gt;



&lt;p&gt;Throughout this tutorial series, we’ll be using this VS Code extension to view the data stored in either the PostgreSQL or Redis databases.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--q8sakJPP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/80ghnz3y1syfjcbgp7nj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--q8sakJPP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/80ghnz3y1syfjcbgp7nj.png" alt="Image" width="880" height="293"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To provide the credentials (username, password, and database name) needed by the PostgreSQL Docker image, we need to create a &lt;code&gt;.env&lt;/code&gt; file in the root directory.&lt;/p&gt;

&lt;p&gt;You can add the &lt;code&gt;.env&lt;/code&gt; file to your &lt;code&gt;.gitignore&lt;/code&gt; file to omit it from your Git commits. I will include some of the &lt;code&gt;.env&lt;/code&gt;file content in an &lt;code&gt;example.env&lt;/code&gt; file so that you can see what the &lt;code&gt;.env&lt;/code&gt; file should look like.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;.env&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;PORT=8000
NODE_ENV=development

POSTGRES_HOST=127.0.0.1
POSTGRES_PORT=6500
POSTGRES_USER=admin
POSTGRES_PASSWORD=password123
POSTGRES_DB=node_prisma
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;It is a convention for environment variables to be in uppercase.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Once we have the above configurations in place, run this command to spawn the docker containers.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;docker-compose up -d

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Setup Environment Variables&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;The most essential part of our application is to set up environment variables. This allows us to store sensitive information (API Keys, passwords, etc) and we can easily exclude them from the Git commits.&lt;/p&gt;

&lt;p&gt;Am going to use the popular library dotenv to load the environment variables from the &lt;code&gt;.env&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Also, I will use the config library to set and access the environment variables. The config library helps us provide the TypeScript types for our environment variables&lt;/p&gt;

&lt;p&gt;Initialize a new Typescript Node.js project with this command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn init -y &amp;amp;&amp;amp; yarn add -D typescript @types/node &amp;amp;&amp;amp; npx tsc --init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Remove the configurations in the &lt;code&gt;tsconfig.json&lt;/code&gt; file and paste these configurations into it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "compilerOptions": {
    "target": "es2016",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "strictPropertyInitialization": false,
    "skipLibCheck": true,
    "outDir": "./build",
    "rootDir": "."
  }
}

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

&lt;/div&gt;



&lt;p&gt;Run this command to install the &lt;code&gt;dotenv&lt;/code&gt; and config &lt;code&gt;packages&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add config dotenv &amp;amp;&amp;amp; yarn add -D @types/config
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the root directory create a config folder and within the config directory create two files named &lt;code&gt;default.ts&lt;/code&gt; and &lt;code&gt;custom-environment-variables.ts&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Copy and paste the code snippets below into their respective files.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;default.ts&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default {
  origin: 'http://localhost:3000'
};

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;custom-environment-variables.ts&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default {
  port: 'PORT',
  nodeEnv: 'NODE_ENV',
};

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Validating Environment Variables&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Forgetting to add an environment variable can lead to unexpected bugs which will cause your application to malfunction.&lt;/p&gt;

&lt;p&gt;To prevent this, we’re going to use the envalid package to validate the environment variables&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add envalid

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

&lt;/div&gt;



&lt;p&gt;Create an &lt;code&gt;src&lt;/code&gt; folder in the root directory and within the &lt;code&gt;src&lt;/code&gt; folder create another folder named &lt;code&gt;utils&lt;/code&gt; .&lt;/p&gt;

&lt;p&gt;Within the &lt;code&gt;utils&lt;/code&gt; folder create a &lt;code&gt;validateEnv.ts&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;src/utils/validateEnv.ts&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { cleanEnv, port, str } from 'envalid';

const validateEnv = () =&amp;gt; {
  cleanEnv(process.env, {
    NODE_ENV: str(),
    PORT: port(),
    POSTGRES_HOST: str(),
    POSTGRES_PORT: port(),
    POSTGRES_USER: str(),
    POSTGRES_PASSWORD: str(),
    POSTGRES_DB: str(),
  });
};

export default validateEnv;

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

&lt;/div&gt;



&lt;p&gt;The envalid package will throw an error if we don’t have any of the defined variables in the &lt;code&gt;.env&lt;/code&gt; file or if they’re of the wrong types.&lt;/p&gt;

&lt;h2&gt;
  
  
  Initialize a Prisma Project with ExpressJs
&lt;/h2&gt;

&lt;p&gt;Prisma comes with a CLI tool we can use to perform different operations like creating migrations out of our schema definitions and pushing the generated migration code to the preferred database.&lt;/p&gt;

&lt;p&gt;To do that, you need to install the &lt;code&gt;prisma&lt;/code&gt; CLI tool as a dependency.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add -D prisma 

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

&lt;/div&gt;



&lt;p&gt;Now run this command to create a basic Prisma setup with the Prisma CLI:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx prisma init --datasource-provider postgresql

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

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;The &lt;code&gt;--datasource-provider&lt;/code&gt; flag tells the Prisma CLI what database to use. I used &lt;code&gt;postgresql&lt;/code&gt; since that’s what am writing about in this tutorial.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;A new &lt;code&gt;prisma&lt;/code&gt; folder is created in the root directory and within the &lt;code&gt;prisma&lt;/code&gt; folder you will find a &lt;code&gt;schema.prisma&lt;/code&gt; file. The &lt;code&gt;schema.prisma&lt;/code&gt; file is the main Prisma configuration file which will contain your database schema.&lt;/p&gt;

&lt;p&gt;Also, if you open the &lt;code&gt;.env&lt;/code&gt; file you should see a PostgreSQL database connection URL created by the Prisma CLI.&lt;/p&gt;

&lt;p&gt;Change the default credentials in the URL created by the Prisma CLI with the credentials we provided to the Docker PostgreSQL image.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;.env&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;POSTGRES_HOST=127.0.0.1
POSTGRES_PORT=6500
POSTGRES_USER=admin
POSTGRES_PASSWORD=password123
POSTGRES_DB=node_prisma

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

&lt;/div&gt;



&lt;p&gt;Your connection URL should now look somewhat like this assuming you used the configurations I provided.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;.env&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DATABASE_URL="postgresql://admin:password123@127.0.0.1:6500/node_prisma?schema=public"

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Creating a database schema with Prisma&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you open the &lt;code&gt;/prisma/schema.prisma&lt;/code&gt; file you’ll find a barebone schema:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;prisma/schema.prisma&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

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

&lt;/div&gt;



&lt;p&gt;In the &lt;code&gt;datasource&lt;/code&gt; field, you can see Prisma used &lt;code&gt;postgresql&lt;/code&gt; as the database provider and that we’re loading the database connection URL form the &lt;code&gt;.env&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;Also, in the &lt;code&gt;generator&lt;/code&gt; block, the &lt;code&gt;provider = "prisma-client-js"&lt;/code&gt; tells Prisma to generate the Prisma Client based on our data models.&lt;/p&gt;

&lt;h2&gt;
  
  
  Defining the user model
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;prisma/schema.prisma&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;model User{
  @@map(name: "users")

  id String  @id @default(uuid())
  name String  @db.VarChar(255)
  email String 
  photo String? @default("default.png")
  verified Boolean? @default(false) 

  password String
  role RoleEnumType? @default(user)

  verificationCode String? @db.Text

  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  @@unique([email, verificationCode])
  @@index([email, verificationCode])
}

enum RoleEnumType {
  user
  admin
}

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

&lt;/div&gt;



&lt;p&gt;In the above, we defined the &lt;code&gt;User&lt;/code&gt; model and the &lt;code&gt;@@map(name: "users")&lt;/code&gt; tells Prisma to use &lt;code&gt;users&lt;/code&gt; as the database table name.&lt;/p&gt;

&lt;p&gt;Each field in the model has a name followed by a type and an optional field attribute(s).&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;@id&lt;/code&gt; attribute on the &lt;code&gt;id&lt;/code&gt; field specifies that it’s a primary key of the &lt;code&gt;users&lt;/code&gt; table. Also, the &lt;code&gt;@default(uuid())&lt;/code&gt;attribute sets a default UUID (Universally Unique Identifier).&lt;/p&gt;

&lt;p&gt;All the fields are required by default so adding &lt;code&gt;?&lt;/code&gt; after the field type specifies that it’s optional.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;RoleEnumType&lt;/code&gt; enum denotes whether the user is an admin or not.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;@@unique([email, verificationCode])&lt;/code&gt; specifies that the &lt;code&gt;email&lt;/code&gt; and &lt;code&gt;verificationCode&lt;/code&gt; fields provided in the array should have unique constraints in the database.&lt;/p&gt;

&lt;p&gt;Lastly, the &lt;code&gt;@@index([email, verificationCode])&lt;/code&gt; defines indexes on both the &lt;code&gt;email&lt;/code&gt; and &lt;code&gt;verificationCode&lt;/code&gt; fields in the database.&lt;/p&gt;

&lt;h2&gt;
  
  
  Database Migration with Prisma
&lt;/h2&gt;

&lt;p&gt;To create a new migration, run the following command&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The PostgreSQL docker container must be running for this to work.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx prisma migrate dev --name user-entity --create-only

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

&lt;/div&gt;



&lt;p&gt;The&lt;code&gt;--name&lt;/code&gt; flag gives the migration a name and the &lt;code&gt;--create-only&lt;/code&gt; tells Prisma to only create the migration without applying it.&lt;/p&gt;

&lt;p&gt;Now run this command to install the Prisma Client. Needed for the next step.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add @prisma/client

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

&lt;/div&gt;



&lt;p&gt;To create the &lt;code&gt;users&lt;/code&gt; table in the database, run the following command:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx prisma db push

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

&lt;/div&gt;



&lt;h2&gt;
  
  
  How to connect an ExpressJs app to Redis
&lt;/h2&gt;

&lt;p&gt;Run the following command to install Express and Redis&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add express redis &amp;amp;&amp;amp; yarn add -D @types/express

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

&lt;/div&gt;



&lt;p&gt;Create a &lt;code&gt;connectRedis.ts&lt;/code&gt; file in the &lt;code&gt;utils&lt;/code&gt; folder and add the code snippets below.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;src/utils/connectRedis.ts&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createClient } from 'redis';

const redisUrl = 'redis://localhost:6379';

const redisClient = createClient({
  url: redisUrl,
});

const connectRedis = async () =&amp;gt; {
  try {
    await redisClient.connect();
    console.log('Redis client connect successfully');
    redisClient.set('try', 'Welcome to Express and TypeScript with Prisma');
  } catch (error) {
    console.log(error);
    setTimeout(connectRedis, 5000);
  }
};

connectRedis();

export default redisClient;


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

&lt;/div&gt;



&lt;p&gt;I used the &lt;code&gt;.set()&lt;/code&gt; method on the Redis instance to add a message with a &lt;code&gt;try&lt;/code&gt; key to the Redis database.&lt;/p&gt;

&lt;p&gt;Next, create an &lt;code&gt;app.ts&lt;/code&gt; file in the &lt;code&gt;src&lt;/code&gt; folder and paste the code snippets below into it.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;src/app.ts&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;require('dotenv').config();
import express, { Response } from 'express';
import config from 'config';
import validateEnv from './utils/validateEnv';
import { PrismaClient } from '@prisma/client';
import redisClient from './utils/connectRedis';

validateEnv();

const prisma = new PrismaClient();
const app = express();

async function bootstrap() {
  // Testing
  app.get('/api/healthchecker', async (_, res: Response) =&amp;gt; {
    const message = await redisClient.get('try');
    res.status(200).json({
      status: 'success',
      message,
    });
  });

  const port = config.get&amp;lt;number&amp;gt;('port');
  app.listen(port, () =&amp;gt; {
    console.log(`Server on port: ${port}`);
  });
}

bootstrap()
  .catch((err) =&amp;gt; {
    throw err;
  })
  .finally(async () =&amp;gt; {
    await prisma.$disconnect();
  });


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

&lt;/div&gt;



&lt;p&gt;Here is the breakdown of what I did in the &lt;code&gt;app.ts&lt;/code&gt; file:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;First I evoked the &lt;code&gt;validateEnv()&lt;/code&gt; function to validate the environment variables in the &lt;code&gt;.env&lt;/code&gt; file.&lt;/li&gt;
&lt;li&gt;Next, I created an instance of the Prisma Client and Express&lt;/li&gt;
&lt;li&gt;Next, I created a &lt;code&gt;bootstrap&lt;/code&gt; function where I define the application logic. I created a &lt;code&gt;/api/healthchecke&lt;/code&gt;r GET route to help us check if all the configurations we provided are valid.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Also, I called the &lt;code&gt;listen()&lt;/code&gt; method to start the server.&lt;/p&gt;

&lt;p&gt;Lastly, in the &lt;code&gt;/api/healthchecker&lt;/code&gt; route controller, I used the &lt;code&gt;.get()&lt;/code&gt; method on the &lt;code&gt;redisClient&lt;/code&gt; instance to get the message we stored in the Redis database.&lt;/p&gt;

&lt;p&gt;Now add the following scripts to your &lt;code&gt;package.json&lt;/code&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;{
"scripts": {
    "start": "ts-node-dev --respawn --transpile-only --exit-child src/app.ts",
    "migrate": "npx prisma migrate dev --name user-entity &amp;amp;&amp;amp; npx prisma generate",
    "push": "npx prisma db push",
    "build": "tsc . -p"
  }
}

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

&lt;/div&gt;



&lt;p&gt;Since we’re using TypeScript, we need a package to automatically restart the server upon file change.&lt;/p&gt;

&lt;p&gt;I recommend &lt;code&gt;ts-node-dev&lt;/code&gt; since it’s optimized for speed compared to &lt;code&gt;nodemon&lt;/code&gt; and &lt;code&gt;ts-node&lt;/code&gt; .&lt;/p&gt;

&lt;p&gt;Run this command to install the &lt;code&gt;ts-node-dev&lt;/code&gt; package&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn add ts-node-dev

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

&lt;/div&gt;



&lt;p&gt;With &lt;code&gt;ts-node-dev&lt;/code&gt; installed, run this command to start the development server.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yarn start

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

&lt;/div&gt;



&lt;p&gt;Open a new tab in your browser and enter this URL &lt;code&gt;http://localhost:8000/api/healthchecke&lt;/code&gt;r and you should see a JSON response with the massage we stored in the Redis database.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Connecting to PostgreSQL and Redis with MySQL VS Code Extension&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Connecting to the Redis Docker container&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Click on the NoSQL tab on the sidebar and then click on the “Create Connection” blue button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vXb6himG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6b5dusuxj7jg2k4qtwal.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vXb6himG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6b5dusuxj7jg2k4qtwal.png" alt="Image" width="727" height="865"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We don’t need to provide any credentials to connect to the Redis container so click on the &lt;strong&gt;“Connect”&lt;/strong&gt; button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kG3HKahR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yr9q3t2ph0zjndykwl11.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kG3HKahR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yr9q3t2ph0zjndykwl11.png" alt="Image" width="880" height="604"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Expand the dropdowns and click on the &lt;code&gt;try&lt;/code&gt; key to see the message we stored in the Redis database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xgFFR2IG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7rt8cbw3wx21d05ab8xv.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xgFFR2IG--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7rt8cbw3wx21d05ab8xv.png" alt="Image" width="880" height="527"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Connecting to the PostgreSQL Docker container&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Click on the database tab on the left sidebar of VS Code and then click on the &lt;strong&gt;&lt;em&gt;“Create Connection”&lt;/em&gt;&lt;/strong&gt; button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--fvswY1dN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbpm8s9jfc2ird0wrfjt.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fvswY1dN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vbpm8s9jfc2ird0wrfjt.png" alt="Image" width="695" height="726"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Select PostgreSQL from the available server types then provide the database credentials contained in the &lt;code&gt;.env&lt;/code&gt; file and click on the &lt;strong&gt;&lt;em&gt;“Connect”&lt;/em&gt;&lt;/strong&gt; button.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9a4gvud8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uk9u1z18fhholbqpqgdc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9a4gvud8--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uk9u1z18fhholbqpqgdc.png" alt="Image" width="880" height="519"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Assuming the connection was successful, expand the dropdowns on the left side and click on the &lt;code&gt;users&lt;/code&gt; table to see the columns we defined with Prisma.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Ry3r924j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/me7yxx85x0z31tsua2gk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Ry3r924j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/me7yxx85x0z31tsua2gk.png" alt="Image" width="880" height="622"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;&lt;em&gt;Congratulation on reaching the end. In this article, you learned how to set up a Node.js project with ExpressJs, Redis, Prisma, PostgreSQL, and Docker.&lt;/em&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>postgres</category>
      <category>prisma</category>
    </item>
    <item>
      <title>Connecting Node.js with MongoDB: A Step-by-Step Guide</title>
      <dc:creator>phin</dc:creator>
      <pubDate>Sat, 25 Feb 2023 06:21:59 +0000</pubDate>
      <link>https://forem.com/saiphin/connecting-nodejs-with-mongodb-a-step-by-step-guide-3mac</link>
      <guid>https://forem.com/saiphin/connecting-nodejs-with-mongodb-a-step-by-step-guide-3mac</guid>
      <description>&lt;p&gt;Node.js is a popular JavaScript runtime that is widely used for building web applications. MongoDB, on the other hand, is a NoSQL document database that is known for its flexibility and scalability. In this blog post, we'll show you how to connect Node.js with MongoDB and perform basic CRUD operations using example source code.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Setting up the Development Environment&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Before we can connect Node.js with MongoDB, we need to set up our development environment. First, we need to install Node.js and MongoDB on our machine. You can download Node.js from the official website (&lt;a href="https://nodejs.org/en/" rel="noopener noreferrer"&gt;https://nodejs.org/en/&lt;/a&gt;) and MongoDB from the official website (&lt;a href="https://www.mongodb.com/" rel="noopener noreferrer"&gt;https://www.mongodb.com/&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Once we have Node.js and MongoDB installed, we need to create a MongoDB instance and a database. We can do this by running the following command in the terminal:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;mongod --dbpath /path/to/data/directory&lt;br&gt;
&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;This will start a MongoDB instance and create a database at the specified data directory.&lt;/p&gt;

&lt;p&gt;Next, we need to install the necessary Node.js modules. We'll be using the mongodb module, which we can install by running the following command in the terminal:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;npm install mongodb&lt;br&gt;
&lt;/code&gt;&lt;br&gt;
Connecting to MongoDB from Node.js&lt;/p&gt;

&lt;p&gt;Now that we have our development environment set up, we can start connecting Node.js with MongoDB. We'll be using the MongoClient module to establish a connection. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017/mydatabase";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

client.connect(err =&amp;gt; {
  if (err) {
    console.error(err);
    return;
  }
  console.log("Connected successfully to server");

  // perform CRUD operations here

  client.close();
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we first require the MongoClient module and define the URI of our MongoDB instance. We then create a new instance of the MongoClient class and call the connect() method to establish a connection. If there is an error, we log it to the console. If the connection is successful, we log a message to the console and perform any necessary CRUD operations.&lt;/p&gt;

&lt;p&gt;Performing CRUD Operations with MongoDB&lt;/p&gt;

&lt;p&gt;Now that we have a connection to MongoDB, we can perform basic CRUD (Create, Read, Update, Delete) operations using Node.js. Let's take a look at some example code:&lt;/p&gt;

&lt;p&gt;Creating a Document:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const insertDocument = function(db, callback) {
  const collection = db.collection('users');
  collection.insertOne({ name: "John", age: 30 }, function(err, result) {
    if (err) {
      console.error(err);
      return;
    }
    console.log("Document inserted successfully");
    callback(result);
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above code, we define a function that takes in a database object and a callback function. We then define a collection named 'users' and insert a new document with the name "John" and age 30. If there is an error, we log it to the console. If the insertion is successful, we log a message to the console and call the callback function with the result.&lt;/p&gt;

&lt;p&gt;Retrieving Documents:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const findDocuments = function(db, callback) {
  const collection = db.collection('users');
  collection.find({}).toArray(function(err, documents) {
    if (err) {
      console.error(err);
      return;
    }
    console.log("Documents retrieved successfully");
    console.log(documents);
    callback(documents);
  });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>career</category>
      <category>ai</category>
      <category>productivity</category>
      <category>discuss</category>
    </item>
    <item>
      <title>Test</title>
      <dc:creator>phin</dc:creator>
      <pubDate>Sat, 25 Feb 2023 05:53:04 +0000</pubDate>
      <link>https://forem.com/saiphin/test-dp</link>
      <guid>https://forem.com/saiphin/test-dp</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frfo6by7ghsholuzdhih4.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frfo6by7ghsholuzdhih4.jpg" alt=" " width="800" height="600"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;dsdsdsd&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;dsds&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>githubcopilot</category>
      <category>ai</category>
      <category>productivity</category>
      <category>career</category>
    </item>
  </channel>
</rss>
