DEV Community

Nabilla Trisnani
Nabilla Trisnani

Posted on

Step 3: Setup Backend

Installation

For my backend, I’m going to use Prisma. This is my first time ever to use Prisma, so… any feedbacks are welcome. Anyway, let’s move to the first step.

1. Install Prisma

npm install prisma --save-dev
npm install @prisma/client
npm install @prisma/adapter-pg
npm install pg
Enter fullscreen mode Exit fullscreen mode

2. Init Prisma

npx prisma init
Enter fullscreen mode Exit fullscreen mode

It will create something like this:

prisma/
    schema.prisma
Enter fullscreen mode Exit fullscreen mode

Inside the schema.prisma, it will look something like this:

generator client {
  provider = "prisma-client"
  output   = "../src/generated/prisma"
}

datasource db {
  provider = "postgresql"
}
Enter fullscreen mode Exit fullscreen mode

3. Setup Database

Since I’m using PostgreSQL, in the .env file, I’m going to change it to something like this:

DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/NAMA_DB"
Enter fullscreen mode Exit fullscreen mode

For example:

DATABASE_URL="postgresql://postgres:123456@localhost:5432/mydb"
Enter fullscreen mode Exit fullscreen mode

Don’t forget to run PostgreSQL and create the database. For this project, I’m going to create the database by running:

CREATE DATABASE note_taking_app;
Enter fullscreen mode Exit fullscreen mode

That line is going to create a database called note_taking_app.

Once everything is set, run this command to open Prisma Studio GUI

npx prisma studio
Enter fullscreen mode Exit fullscreen mode

Basic Test

For basic test, I’m going to create a table called “Users” and create a seed for the table.

In the prisma/schema.prisma add these lines:

model Users {
  id    Int     @id @default(autoincrement())
  name  String
  email String  @unique
}
Enter fullscreen mode Exit fullscreen mode

Let’s breakdown those lines.

  • model Users: is the name of the table. If you want to change the name of the table, change the Users to anything that you like.
  • id Int @id @default(autoincrement()): column id with integer as data type. @id @default(autoincrement()) means that it is the primary key with auto increment (ex: 1, 2, 3, 4, …)
  • name String: column name with string as data type.
  • email String @unique: column email with String as data type. @unique means the value of email must be different from one another (unique).

Another thing that I like to mention is if you want to create a column that is optional, you can add question mark at the end of the data type. For example, if you want to create column name as optional, you can:

model Users {
  id    Int     @id @default(autoincrement())
  name  String?
  email String  @unique
}
Enter fullscreen mode Exit fullscreen mode

But for this test, I’m going to make everything required.

After you input the code above, run this command to create the table in database:

npx prisma migrate dev --name create_user
Enter fullscreen mode Exit fullscreen mode

Then run:

npx prisma generate
Enter fullscreen mode Exit fullscreen mode

Create Seed

For this step, I’m going to try to create seed. First, don’t forget to run this command before you start.

npx prisma generate
Enter fullscreen mode Exit fullscreen mode

Once you’re done running that command, create seed.ts in:

prisma/
    seed.ts
Enter fullscreen mode Exit fullscreen mode

Inside the seed.ts, copy this code:

import "dotenv/config";
import { Pool } from "pg";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from '../src/generated/prisma/client'
const connectionString = `${process.env.DATABASE_URL}`;
const pool = new Pool({ connectionString });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });

async function main() {
    const user = await prisma.user.create({
        data: {
            name: "Jane",
            email: "jane@email.com"
        }
    })

    console.log(user)
}

main()
    .then(() => {
        console.log("Seed User done")
    })
    .catch((e) => {
        console.error(e)
    })
    .finally(async () => {
        await prisma.$disconnect()
    })
Enter fullscreen mode Exit fullscreen mode

Or, if you want insert multiple object, you can do it like this:

import "dotenv/config";
import { Pool } from "pg";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from '../src/generated/prisma/client'
const connectionString = `${process.env.DATABASE_URL}`;
const pool = new Pool({ connectionString });
const adapter = new PrismaPg(pool);
const prisma = new PrismaClient({ adapter });

async function main() {
    const user = await prisma.user.createMany({
        data: [
            {
                name: "Jane",
                email: "jane@email.com"
            },
            {
                name: "John",
                email: "john@email.com"
            },
        ]
    })

    console.log(user)
}

main()
    .then(() => {
        console.log("Seed User done")
    })
    .catch((e) => {
        console.error(e)
    })
    .finally(async () => {
        await prisma.$disconnect()
    })
Enter fullscreen mode Exit fullscreen mode

After seed.ts is set, let’s move to prisma.config.ts. Change the file to this:

import "dotenv/config";
import { defineConfig } from "prisma/config";

export default defineConfig({
  schema: "prisma/schema.prisma",
  migrations: {
    path: "prisma/migrations",
    seed: "tsx prisma/seed.ts", //add this
  },
  datasource: {
    url: process.env["DATABASE_URL"],
  },
});
Enter fullscreen mode Exit fullscreen mode

Then run:

npx prisma db seed
Enter fullscreen mode Exit fullscreen mode

If there’s an error during the seeding process, or if the new data doesn’t appear in the table, run this command:

npm install -D tsx
npx prisma generate
Enter fullscreen mode Exit fullscreen mode

then run the seed command again.

After everything is done, the data should appear like this:

I’m not gonna lie, this step is a challenge for me because as I said earlier, this is my first ever time to use Prisma. After reading through the docs, I can finally create not just one, but two tables. As always, I’ll be more than happy to get any feedback that you can give me.

Thanks for coming by and Peace ✌


Author

Top comments (0)