DEV Community

Ankit Sahu
Ankit Sahu

Posted on

Mastering Prisma: A Comprehensive Guide for Beginners

πŸš€ Initializing the Project πŸš€

To kick off our journey with Prisma, let's start by creating a new project and installing the necessary dependencies. Open your terminal and run the following commands:

yarn init -y
yarn add --dev typescript ts-node @types/node nodemon
Enter fullscreen mode Exit fullscreen mode

Next, let's initialize TypeScript in our project and add the Prisma CLI:

yarn tsc --init
yarn add --dev prisma
Enter fullscreen mode Exit fullscreen mode

Now, we need to set up Prisma to work with PostgreSQL:

yarn prisma init --datasource-provider postgresql
Enter fullscreen mode Exit fullscreen mode

πŸ“Š Creating a Basic Model πŸ“Š

Once Prisma is set up, let's create a simple model in the _schema.prisma file. In this example, we'll create a User model with an id and a name:

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

After defining the model, it's time to create the corresponding database tables using Prisma Migrate:

yarn prisma migrate dev --name init
Enter fullscreen mode Exit fullscreen mode

πŸ“ Sending Queries to the Database πŸ“

Now, let's explore how to interact with the database using Prisma Client. Create a file called script.ts and add the following code:

import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

async function main() {
  // ... you will write your Prisma Client queries here
}

main()
  .catch(e => {
    console.log(e.message)
  })
  .finally(async () => {
    await prisma.$disconnect()
  })
Enter fullscreen mode Exit fullscreen mode

In the script.ts file, you can use Prisma Client to send queries to the database. For example, to add a new user, you can use the following code:

const user = await prisma.user.create({ data: { name: "Steve Rogers" } })
Enter fullscreen mode Exit fullscreen mode

And to retrieve all users from the database:

const users = await prisma.user.findMany()
console.log(users)
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Tip: Don't forget to install the Prisma Client and generate the Prisma Client code before running the script:

yarn add @prisma/client
yarn prisma generate
Enter fullscreen mode Exit fullscreen mode

πŸŽ‰ Adding Nodemon for Automatic Refresh πŸŽ‰

To make development more efficient, let's set up Nodemon to automatically refresh the script when changes are made. Add the following script to your package.json:

"scripts": {
  "devStart": "nodemon script.ts"
}
Enter fullscreen mode Exit fullscreen mode

Now, you can run the following command to start your development server:

yarn devStart
Enter fullscreen mode Exit fullscreen mode

✨ Advanced Schema with Relations and Enums ✨

Now, let's dive into more advanced concepts in Prisma and create a schema with relations and an enum. You can use this as a reference for building more complex data models.

// SCHEMA
model User {
  id               String          @id @default(uuid())
  name             String
  age              Int
  email            String          @unique
  isAdmin          Role            @default(BASIC)
  authoredPosts    Post[]          @relation("AuthoredPosts") // One to Many
  bookmarkedPosts  Post[]          @relation("BookmarkedPosts")
  userPreference   UserPreference? @relation(fields: [userPreferenceId], references: [id])
  userPreferenceId String?         @unique

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

// One to One Relation
model UserPreference {
  id           String  @id @default(uuid())
  user         User?
  emailUpdates Boolean @default(false)
}

model Post {
  id             String     @id @default(uuid())
  title          String
  rating         Float
  createdAt      DateTime   @default(now())
  updatedAt      DateTime   @updatedAt
  author         User       @relation("AuthoredPosts", fields: [authorId], references: [id])
  authorId       String
  bookmarkedBy   User?      @relation("BookmarkedPosts", fields: [bookmarkedById], references: [id])
  bookmarkedById String?
  categories     Category[]
}

// Many to Many Relation
model Category {
  id    String @id @default(uuid())
  posts Post[]
}

enum Role {
  BASIC
  ADMIN
}
Enter fullscreen mode Exit fullscreen mode

πŸ› οΈ CRUD Operations with Prisma Client πŸ› οΈ

To perform CRUD (Create, Read, Update, Delete) operations using Prisma Client, let's dive into some code examples.

Creating a User:

async function create() {
  const user = await prisma.user.create({
    data: {
      name: "Lizard Zuck",
      email: "zuckiscuck@gmail.com",
      userPreference: {
        create: {
          emailUpdates: true,
        },
      },
    },
    select: {
      name: true,
      userPreference: { select: { id: true } },
    },
  })
  return user
}
Enter fullscreen mode Exit fullscreen mode

Reading a User by Email:

const user = await prisma.user.findUnique({
  where: {
    email: "ankit1042002@gmail.com",
  },
})
console.log(user)
Enter fullscreen mode Exit fullscreen mode

Filtering Users with Complex Conditions:

const user = await prisma.user.findMany({
  where: {
    name: { not: "Ankit" },
    age: { lt: 20 }, // lt -> less than
    email: { contains: "@gmail.com", startsWith: "an" },
  },
})
Enter fullscreen mode Exit fullscreen mode

Updating User Data:

const updatedUser = await prisma.user.update({
  where: {
    email_name: {
      email: "ankit.ks@yahoo.com",
      name: "Ankit",
    },
  },
  data: {
    email: "ankit.ks@yahoo.com",
  },
})
console.log(updatedUser)
Enter fullscreen mode Exit fullscreen mode

Deleting a User:

const deletedUser = await prisma.user.delete({
  where: {
    email_name: {
      email: "ankit.ks@yahoo.com",
      name: "Ankit",
    },
  },
})
console.log(deletedUser)
Enter fullscreen mode Exit fullscreen mode

πŸ”— Connecting and Disconnecting Relations πŸ”—

To connect and disconnect relations, such as connecting a User to their UserPreference, you can use the following examples:

Connecting UserPreference:

const preference = await prisma.userPreference.create({
  data: {
    emailUpdates: true,
  },
})

const user = await prisma.user.update({
  where: {
    email_name: {
      email: "ankit.ks@yahoo.com",
      name: "Ankit",
    },
  },
  data: {
    userPreference: {
      connect: {
        id: preference.id,
      },
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

Disconnecting UserPreference:

const user = await prisma.user.update({
  where

: {
    email_name: {
      name: "Ankit",
      email: "ankit.ks@yahoo.com",
    },
  },
  data: {
    userPreference: {
      disconnect: true,
    },
  },
})
Enter fullscreen mode Exit fullscreen mode

πŸ” Fetching Posts with Relations πŸ”

To fetch posts related to users, you can use Prisma Client to perform queries like this:

async function main() {
  const posts = await prisma.user.findMany({
    where: {
      authoredPosts: {
        every: {
          title: {
            startsWith: "T",
          },
        },
      },
    },
  })
  console.log(posts)
}
Enter fullscreen mode Exit fullscreen mode

πŸ“„ Conclusion πŸ“„

Congratulations! You've now learned the essentials of using Prisma.
Now, my coding Jedi, may the Prisma force be with you. Remember, even Darth Bugs will fear your skills!.

Top comments (0)