In Nest+GrqphQL+Prisma+React Full Stack Development series, I will lead you to learn how to use these technology stacks step by step and develop a practical application.

This is the second article, Prisma.

GraphQL

A list,

Prisma is the next generation of Node.js, TypeScript, Go database ORM (Object Relational Mappers map data models to Objects) so we don’t have to manipulate databases directly. Automatically converts to data operations.

Prisma has three parts

  • Prisma Client: Automatically generated, type-safe query builder for Node.js and TypeScript
  • Prisma Migrate: Data migration system
  • Prisma Studio: A graphical interface for querying and editing data in a database

In Nodejs community, there are many ORM libraries, such as TypeORM, Sequelize, Mongoose, Prisma and what are the differences between them? What are the advantages?

Here’s my summary of the official answer:

Prisma’s main role is to balance productivity and control while also improving work efficiency, which is its advantage. Handwritten SQL has the highest level of control but low productivity, while ORM has increased productivity but low level of control.

There are also some pitfalls with ORM, because although ORM maps tables and objects, they are different in terms of their mental models, with objects more focused on a single state and tables more focused on relationships. Moreover, the deep nesting of objects may cause slow performance of SQL queries.

Second, the component

Prisma schema

Prisma Schema files are the main configuration files in your Primsa organization, defining data sources, generators, and data models.

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

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

model User {
 id Int @id @default(autoincrement())
 createdAt DateTime @default(now())
 email String @unique
 name String?
 role Role @default(USER)
 posts Post[]
}
Copy the code

Prisma’s data model defines your data model and has the following functions:

  • Entities that constitute the application domain
  • Mapped to the databasetable(Relational databases, for examplePostgreSQL) orA collection of(mongo)
  • Constitute aPrisma Client APIIn theThe queryOn the basis of
  • In the use ofTypeScriptWhen,Prisma Client Provides for models and their variantsThe type definitionTo ensure the type security of database access

Prisma Client

Prisma Client is an automatically generated type-safe query constructor that can be customized based on your data.

It has these common CRUD methods:

  • findMany
  • findUnique
  • create
  • update
  • upsert
  • delete
  • updateMany
  • deleteMany

For more advanced uses, check out the official documentation.

Prisma Migrate

Prisma Migrate is an imperative database schema migration tool that enables you to:

  • Keep database schemas in sync with Prisma schemas
  • Maintain existing data in the database

After the migration is complete, the. SQL migration file history is generated:

├ ─ ├ ─ imp/sci-imp/sci-imp/sci-imp/sci-imp/sci-impCopy the code

This way you can easily iterate or roll back data and version management.

Three, to fit

Mysql > modify prisma/schema.prisma:

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

Database address, which you can configure in the. Env file:

DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb? schema=public"
Copy the code

Next, define your database and write prisma/schema.prisma

model Post {
 id Int @id @default(autoincrement())
 createdAt DateTime @default(now())
 updatedAt DateTime @updatedAt
 title String @db.VarChar(255)
 content String?
 published Boolean @default(false)
 author User @relation(fields: [authorId], references: [id])
 authorId Int
}
Copy the code

Create database with Prisma Migrate:

npx prisma migrate dev --name init
Copy the code

Query data using Prisma Client:

import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
 // ... you will write your Prisma Client queries here
}

main()
 .catch((e) = > {
 throw e
 })
 .finally(async() = > {await prisma.$disconnect()
 })
Copy the code