DEV Community

Alex Spinov
Alex Spinov

Posted on

Prisma Has a Free API — Here's How to Build Type-Safe Database Apps in TypeScript

Prisma is a next-generation ORM for TypeScript and Node.js. It generates a fully typed client from your schema, making database queries feel like regular TypeScript code.

Installation

npm install prisma @prisma/client
npx prisma init
Enter fullscreen mode Exit fullscreen mode

Schema Definition

// prisma/schema.prisma
generator client {
  provider = "prisma-client-js"
}

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

model User {
  id        String   @id @default(cuid())
  email     String   @unique
  name      String
  role      Role     @default(USER)
  posts     Post[]
  createdAt DateTime @default(now())
}

model Post {
  id        Int      @id @default(autoincrement())
  title     String
  content   String?
  published Boolean  @default(false)
  author    User     @relation(fields: [authorId], references: [id])
  authorId  String
  tags      Tag[]
}

model Tag {
  id    Int    @id @default(autoincrement())
  name  String @unique
  posts Post[]
}

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

Generate Client and Migrate

npx prisma migrate dev --name init
npx prisma generate
Enter fullscreen mode Exit fullscreen mode

CRUD Operations

import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

// Create with relation
const user = await prisma.user.create({
  data: {
    email: "dev@example.com",
    name: "Dev",
    posts: {
      create: [
        { title: "First Post", content: "Hello World", published: true },
        { title: "Draft", content: "WIP" }
      ]
    }
  },
  include: { posts: true }
});

// Find with filters
const publishedPosts = await prisma.post.findMany({
  where: { published: true, author: { role: "ADMIN" } },
  include: { author: { select: { name: true, email: true } }, tags: true },
  orderBy: { id: "desc" },
  take: 10
});

// Update
await prisma.post.update({
  where: { id: 1 },
  data: { published: true }
});

// Delete
await prisma.user.delete({ where: { email: "dev@example.com" } });
Enter fullscreen mode Exit fullscreen mode

Aggregations

const stats = await prisma.post.aggregate({
  _count: { id: true },
  _avg: { id: true },
  where: { published: true }
});

const groupedByAuthor = await prisma.post.groupBy({
  by: ["authorId"],
  _count: { id: true },
  orderBy: { _count: { id: "desc" } }
});
Enter fullscreen mode Exit fullscreen mode

Transactions

const [user, post] = await prisma.$transaction([
  prisma.user.create({ data: { email: "a@b.com", name: "A" } }),
  prisma.post.create({ data: { title: "Post", authorId: "known-id" } })
]);
Enter fullscreen mode Exit fullscreen mode

Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)