Basic CRUD with Prisma, Fastify and Node
Tags: beginners, fastify, crud, prisma
Published: 2023-05-30 19:09:54

## 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
```
To run TypeScript, install `tsx`(TypeScript Execute) which is a CLI command alternative to node. 

```
npm i tsx -D
```
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"
  },
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct9aui3ob8sl29mj1t3z.png)


### 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
```
`Prisma` can then be set up using its CLI.

```
npx prisma init --datasource-provider sqlite
```
This command will create a `Prisma` directory within the project and configure SQLite as the database. 

![prisma folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/deuspapyhyxlypiqslld.png)

`Prisma` provides a range of database connectors, a [list](https://www.prisma.io/docs/concepts/database-connectors) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vrsgryufs2z7emjpe52a.png)

#### 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
```
This will create a migration as shown below.  


![prisma migration](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wtpf4ca3kfddpyazh9ny.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0tk4m5qekv5f3chrc23j.png)


## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oq6qem3lgsdw5ofhr7jd.png)

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() => {
      ...
    })
```

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)
```

### 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
  })
```

### Read

To read an individual record, use the `findUnique` query.

```
const professor = await prisma.professor.findUnique({
      where:{
        id: professorId
      }
    })
```

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
      }
    })
```

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
      }
    })
```

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
```
`Prisma Studio` will open in the browser, showing the previously created models:

![prisma studio models](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ac0luzs4zar8vpesv8uu.png)

Select a model and click `Add record`:

![professor model](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/duzkjflx2t8pglwt16ro.png)

Then proceed to add as many records as necessary:

![professor records](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2t52txfp6e8sikn4bqfc.png)

![course records](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78c68i53jvajuzgzeb85.png)

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


![update prisma studio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdbz5yjglbin72kynztj.png)

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

![delete prisma studio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ltka78cngt6l2wl9k22.png)

A popup will appear asking to confirm the deletion.

![confirm delete prisma studio](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zkw8siv5mako8f8spii2.png)


## 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](https://www.fastify.io/docs/latest/)
2. [Prisma](https://www.prisma.io/docs)
3. [tsx](https://www.npmjs.com/package/tsx)