DEV Community

Farai Bvuma
Farai Bvuma

Posted on

Basic CRUD with Prisma, Fastify and Node

Introduction

This is a simple guide meant to demonstrate how you can perform CRUD operations using Prisma, Fastify and Node.js.

Fastify

Fastify is an incredibly fast, schema based, TypeScript ready web framework. It can be used in lieu of Express. To get started, the project can be initiated by installing both Fastify and TypeScript using the following commands:

npm init -y
npm i fastify
npm i -D typescript @types/node
Enter fullscreen mode Exit fullscreen mode

To run TypeScript, install tsx(TypeScript Execute) which is a CLI command alternative to node.

npm i tsx -D
Enter fullscreen mode Exit fullscreen mode

At this point it is worth adding the following line to the scripts property of the package.json file.

 "scripts": {
    "dev": "tsx watch src/server.ts"
  },
Enter fullscreen mode Exit fullscreen mode

This sets tsx to watch mode, where the specified file will be rerun after any changes are made. In this case a server.ts file was created in the src folder as shown below.

server.ts in src folder

Prisma

Prisma is an open source ORM that provides a type-safe API and simplified database access. It consists of Prisma Client, Prisma Migrate and Prisma Studio. Prisma can be installed by typing the following in the terminal:

npm i prisma -D
Enter fullscreen mode Exit fullscreen mode

Prisma can then be set up using its CLI.

npx prisma init --datasource-provider sqlite
Enter fullscreen mode Exit fullscreen mode

This command will create a Prisma directory within the project and configure SQLite as the database.

prisma folder

Prisma provides a range of database connectors, a list of which can be found here.

Now the schema can be modeled in the schema.prisma file. For this example, professor and course models were created as shown below.

prisma models

Prisma Migrate

In order to create the SQLite database with the professor and course tables as represented by in the models, it is necessary to run Prisma Migration with the following command:

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

This will create a migration as shown below.

prisma migration

Migrations allow for the management of changes to the database schema.

Prisma Client

Prisma Client is a type-safe auto-generated query builder that is used to send queries to the database. In this example, a prisma.ts file was created in the lib folder and the Prisma Client was set to log all queries.

prisma client

CRUD

CRUD stands for Create, Read, Update and Delete. CRUD operations can be performed using Prisma Studio or Prisma Client.

To perform CRUD operations with Prisma Client, a Fastify plugin was created to register the routes. This was done by creating a professors.ts file in the routes folder.

routes

The routes can be set up in the professors.ts file by following the example below, where the function accepts app which has a type of FastifyInstance.

export async function professors(app: FastifyInstance) {
 app.get('/professors',  async() => {
      ...
    })
Enter fullscreen mode Exit fullscreen mode

The plugin must then be registered in the server.ts file using Fastify's register function as shown below.

const app = fastify();

app.register(professors)
Enter fullscreen mode Exit fullscreen mode

Create

In order to create a record, use create query to create a single record, or createMany to create multiple records. Below is an example of how a new professor record is added to the database.

  app.post('/professors', async (request) => {
    const professor = await prisma.professor.create({
      data: {
        firstName: professorFirstName,
        lastName: professorLastName,
        email: professorEmail,
      }
    })
    return professor
  })
Enter fullscreen mode Exit fullscreen mode

Read

To read an individual record, use the findUnique query.

const professor = await prisma.professor.findUnique({
      where:{
        id: professorId
      }
    })
Enter fullscreen mode Exit fullscreen mode

To read all records, use the findMany query.

Update

To update a single record, use the update query:

const professor = await prisma.professor.update({
      where: {
        id: professorId
      },
      data: {
        lastName: updatedLastName
      }
    })
Enter fullscreen mode Exit fullscreen mode

To update multiple records, use the updateMany query.

Delete

To delete a single record, use the delete query.

 const professor = await prisma.professor.delete({
      where: {
        id: professorId
      }
    })
Enter fullscreen mode Exit fullscreen mode

To delete multiple records, use the deleteMany query.

CRUD operations can also be performed using the Prisma Studio graphical user interface.

Prisma Studio

In order to manipulate data in the newly created database, open Prisma Studio with the following command:

npx prisma studio
Enter fullscreen mode Exit fullscreen mode

Prisma Studio will open in the browser, showing the previously created models:

prisma studio models

Select a model and click Add record:

professor model

Then proceed to add as many records as necessary:

professor records

course records

To update a record, double click on a field, update with the desired changes and then save.

update prisma studio

To delete a record, select a record then click delete.

delete prisma studio

A popup will appear asking to confirm the deletion.

confirm delete prisma studio

Conclusion

Fastify is an interesting option for anyone looking for a lightweight web framework that is faster than Express. Prisma is an interesting option for anyone looking for a type-safe ORM.

References

  1. Fastify
  2. Prisma
  3. tsx

Top comments (0)