Learn Prisma
Learn Prisma
Exploring Prisma as an ORM for Node Projects
Introduction
Prisma abstracts the underlying database and provides a simple, type-safe and expressive API for working with data. By using Prisma, you can write less code, reduce the risk of bugs, and improve the performance of your application, making it a good choice for your data management needs.
📓 Exploring Prisma as an ORM for Node Projects
Setup Process
The Setup Process for Prisma is Divided into different phases as listed below.
- Installing Dev Dependencies
- Initializing TypeScript
- Adding Prisma
- Adding Prisma Client
- Creating Database
1. Installing Dev Dependencies
To use Prisma ORM you need some of the core dependencies except prisma. Run yarn add -D typescript ts-node @types/node
this will install root level packages as development dependency that prisma requires.
2. Initializing TypeScript
After we have installed dependencies we need to initialize typescript as Prisma is a TypeORM. Run yarn tsc --init
command to initialize typescript. On successfully installation you will see a tsconfig.json
on root directory.
3. Adding Prisma
After initializing typescript lets add prisma as dev dependency using yarn add -D prisma
, so that we can now use prisma to define schema and start working.
4. Adding Prisma Client
Prisma client library is used to query the database so we will be needing it while consuming data from database. To add prisma client run yarn add @prisma/client
5. Creating Database
After completely adding up dependencies lets first create a database that can be used by prisma. I will be using mysql
bust you can use any database of your choice.
- Login to mysql shell using
mysql -u root -p
, enter the password. - Run
CREATE DATABASE [dbName];
command. - Use
SHOW Databases;
command to verify the database.
For security reasons its better to create a new user and assign a basic privileges like CREATE,READ,UPDATE,DELETE
but for now we wont be doing that.
Creating Prisma Schema
After creating database we need to create a schema for prisma to use. Prisma schema is a file that defines the database schema and the models that can be used to query the database. Run yarn prisma init --datasource-provider mysql
command to initialize prisma. This will create a prisma
directory on root directory and a schema.prisma
file inside it.
1 | datasource db { |
This is the default schema that is created by prisma. We will be modifying this schema to define our database schema and models.
You will also see a .env
file at root of the directory that contains the database url. This is the url that prisma will use to connect to the database. You can change the database url to your database url.
1 | DATABASE_URL="mysql://johndoe:randompassword@localhost:3306/mydb" |
Replace the database url with your database url.
Creating Models
Now that we have created a database and a schema we can start defining our models. Open the schema.prisma
file and add the following code.
1 | model User { |
After defining the models we need to migrate the database. Run yarn prisma migrate dev
command to migrate the database. This will create a migrations
directory that contains the migration files. You can also use yarn prisma migrate dev --name [migrationName]
to name the migration.
Generating Prisma Client
After defining the models we need to generate prisma client. Prisma client is the library that is used to query the database. Run yarn prisma generate
command to generate prisma client. This will create a node_modules/@prisma/client
directory that contains the prisma client library.
1 | Environment variables loaded from .env |
Using Prisma Client
Before we start using prisma client lets create a index.ts
file on root directory so that we can invoke all the required functions from there. We are trying to mimic a function call but since we are not creating a rest api we will be using console.log
to print the output.
Setting up index.ts file
Lets create a index.ts
file on root directory and add the following code.
1 | // Path: index.ts |
When you run yarn ts-node index.ts
command you will see the following output.
1 | APP: Application Started |
Lets create a dev command on package.json
file to run the application. Add the following code to package.json
file.
1 | { |
Now you can run yarn dev
command to run the application.
Creating common Prisma Error Handler
Lets also create a common error handler that will be used to handle all the prisma errors. Create a Tables
directory and inside inside that directory, create a PrismaError.ts
file and add the following code.
1 | // Path: Tables\PrismaError.ts |
Here we are handling all the prisma errors and returning a custom error message. You can customize the error message as per your requirement.
Creating User Handler
After setting up the index.ts
file lets create a UserTable.ts
file that will contain all the functions related to user. Create a directory named Tabes
on root directory and create a UserTable.ts
file inside it. Add the following code to UserTable.ts
file.
1 | // Path: Tables\UserTable.ts |
Create User
Now lets import prisma client and implement the create function first. Our create function will take only few arguments and will return the created user. Add the following code to UserTable.ts
file.
1 | // Path: Tables\UserTable.ts |
Update User
Lets implement update functions. Add the following code to UserTable.ts
file.
1 | import { PrismaClient,User } from "@prisma/client"; |
Delete User
Lets implement delete functions. Add the following code to UserTable.ts
file.
1 |
|
Get All Users
Lets implement get all users functions. Add the following code to UserTable.ts
file.
1 | ... |
Get User By Id
Finally lets implement get user by id functions. Add the following code to UserTable.ts
file.
1 | ... |
Using User Handler
Now lets use the user handler in our index.ts
file. Add the following code to index.ts
file.
1 | ... |
Similarly you can create other tables and use them in your application.
Conclusion
In a nutshell we have learned how to setup, create and use prisma and prisma client in our application. For further reading you can check out the Prisma Documentation. If you have any questions or suggestions please feel free to comment below and hope you enjoyed exploring Prisma with me.