How does Prisma Work??

Feb 02 2024

Prisma is an Object Relational Mapping (ORM) tool that helps developers interact with database in type-safe manner.

Why Prisma is better than Traditional ORM?

We can call it better than traditional ORM, because it is type-safe and it is easy to use. It is also easy to integrate with any database.

Traditional

What are the problems with Traditional ORM?

  • Two sources of Truth have to maintain both model and schema separately. Changes in one leads to problem and have to change all
  • Object Oriented Mapping have to create classes to represent tables in the database. involves manually mapping the structure of database to objects in the code
  • complex configuration

Prisma Approach

  1. Single source of truth
  2. Decleartive Schema including tables, fields, and relationships
  3. Type-safe
  4. Easy to use
  5. Easy to integrate

Prisma in node.js

installing prisma and editing the schema

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

async function main() {
    const allUsers = await prisma.user.findMany();
    console.log(allUsers);
}

Omit and Partial Concept in Prisma

<span>Omit and Partial</span> are the two concepts that are used in prisma. Omit helps to omit the fields that are not required. Partial helps to update the fields that are only required. like partial update.

import { prisma } from "@/infrastructure";
import { User } from "@prisma/client";

const createUser = async (
  payload: Omit<User, 'id' | 'createdAt' | 'deletedAt' | 'updatedAt'>
) => {
  return await prisma.user.create({
    data: payload,
  })
}

const updateUser = async (payload: Partial<User>) => {
  return await prisma.user.update({
    data: {
      ...payload,
    },
    where: {
      id: payload.id,
    },
  })
}