- 1. API with NestJS #1. Controllers, routing and the module structure
- 2. API with NestJS #2. Setting up a PostgreSQL database with TypeORM
- 3. API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
- 4. API with NestJS #4. Error handling and data validation
- 5. API with NestJS #5. Serializing the response with interceptors
- 6. API with NestJS #6. Looking into dependency injection and modules
- 7. API with NestJS #7. Creating relationships with Postgres and TypeORM
- 8. API with NestJS #8. Writing unit tests
- 9. API with NestJS #9. Testing services and controllers with integration tests
- 10. API with NestJS #10. Uploading public files to Amazon S3
- 11. API with NestJS #11. Managing private files with Amazon S3
- 12. API with NestJS #12. Introduction to Elasticsearch
- 13. API with NestJS #13. Implementing refresh tokens using JWT
- 14. API with NestJS #14. Improving performance of our Postgres database with indexes
- 15. API with NestJS #15. Defining transactions with PostgreSQL and TypeORM
- 16. API with NestJS #16. Using the array data type with PostgreSQL and TypeORM
- 17. API with NestJS #17. Offset and keyset pagination with PostgreSQL and TypeORM
- 18. API with NestJS #18. Exploring the idea of microservices
- 19. API with NestJS #19. Using RabbitMQ to communicate with microservices
- 20. API with NestJS #20. Communicating with microservices using the gRPC framework
- 21. API with NestJS #21. An introduction to CQRS
- 22. API with NestJS #22. Storing JSON with PostgreSQL and TypeORM
- 23. API with NestJS #23. Implementing in-memory cache to increase the performance
- 24. API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster
- 25. API with NestJS #25. Sending scheduled emails with cron and Nodemailer
- 26. API with NestJS #26. Real-time chat with WebSockets
- 27. API with NestJS #27. Introduction to GraphQL. Queries, mutations, and authentication
- 28. API with NestJS #28. Dealing in the N + 1 problem in GraphQL
- 29. API with NestJS #29. Real-time updates with GraphQL subscriptions
- 30. API with NestJS #30. Scalar types in GraphQL
- 31. API with NestJS #31. Two-factor authentication
- 32. API with NestJS #32. Introduction to Prisma with PostgreSQL
- 33. API with NestJS #33. Managing PostgreSQL relationships with Prisma
- 34. API with NestJS #34. Handling CPU-intensive tasks with queues
- 35. API with NestJS #35. Using server-side sessions instead of JSON Web Tokens
- 36. API with NestJS #36. Introduction to Stripe with React
- 37. API with NestJS #37. Using Stripe to save credit cards for future use
- 38. API with NestJS #38. Setting up recurring payments via subscriptions with Stripe
- 39. API with NestJS #39. Reacting to Stripe events with webhooks
- 40. API with NestJS #40. Confirming the email address
- 41. API with NestJS #41. Verifying phone numbers and sending SMS messages with Twilio
- 42. API with NestJS #42. Authenticating users with Google
- 43. API with NestJS #43. Introduction to MongoDB
- 44. API with NestJS #44. Implementing relationships with MongoDB
- 45. API with NestJS #45. Virtual properties with MongoDB and Mongoose
- 46. API with NestJS #46. Managing transactions with MongoDB and Mongoose
- 47. API with NestJS #47. Implementing pagination with MongoDB and Mongoose
- 48. API with NestJS #48. Definining indexes with MongoDB and Mongoose
- 49. API with NestJS #49. Updating with PUT and PATCH with MongoDB and Mongoose
- 50. API with NestJS #50. Introduction to logging with the built-in logger and TypeORM
- 51. API with NestJS #51. Health checks with Terminus and Datadog
- 52. API with NestJS #52. Generating documentation with Compodoc and JSDoc
- 53. API with NestJS #53. Implementing soft deletes with PostgreSQL and TypeORM
- 54. API with NestJS #54. Storing files inside a PostgreSQL database
- 55. API with NestJS #55. Uploading files to the server
- 56. API with NestJS #56. Authorization with roles and claims
- 57. API with NestJS #57. Composing classes with the mixin pattern
- 58. API with NestJS #58. Using ETag to implement cache and save bandwidth
- 59. API with NestJS #59. Introduction to a monorepo with Lerna and Yarn workspaces
- 60. API with NestJS #60. The OpenAPI specification and Swagger
- 61. API with NestJS #61. Dealing with circular dependencies
- 62. API with NestJS #62. Introduction to MikroORM with PostgreSQL
- 63. API with NestJS #63. Relationships with PostgreSQL and MikroORM
- 64. API with NestJS #64. Transactions with PostgreSQL and MikroORM
- 65. API with NestJS #65. Implementing soft deletes using MikroORM and filters
- 66. API with NestJS #66. Improving PostgreSQL performance with indexes using MikroORM
- 67. API with NestJS #67. Migrating to TypeORM 0.3
- 68. API with NestJS #68. Interacting with the application through REPL
- 69. API with NestJS #69. Database migrations with TypeORM
- 70. API with NestJS #70. Defining dynamic modules
- 71. API with NestJS #71. Introduction to feature flags
- 72. API with NestJS #72. Working with PostgreSQL using raw SQL queries
- 73. API with NestJS #73. One-to-one relationships with raw SQL queries
- 74. API with NestJS #74. Designing many-to-one relationships using raw SQL queries
- 75. API with NestJS #75. Many-to-many relationships using raw SQL queries
- 76. API with NestJS #76. Working with transactions using raw SQL queries
- 77. API with NestJS #77. Offset and keyset pagination with raw SQL queries
- 78. API with NestJS #78. Generating statistics using aggregate functions in raw SQL
- 79. API with NestJS #79. Implementing searching with pattern matching and raw SQL
- 80. API with NestJS #80. Updating entities with PUT and PATCH using raw SQL queries
- 81. API with NestJS #81. Soft deletes with raw SQL queries
- 82. API with NestJS #82. Introduction to indexes with raw SQL queries
- 83. API with NestJS #83. Text search with tsvector and raw SQL
- 84. API with NestJS #84. Implementing filtering using subqueries with raw SQL
- 85. API with NestJS #85. Defining constraints with raw SQL
- 86. API with NestJS #86. Logging with the built-in logger when using raw SQL
- 87. API with NestJS #87. Writing unit tests in a project with raw SQL
- 88. API with NestJS #88. Testing a project with raw SQL using integration tests
- 89. API with NestJS #89. Replacing Express with Fastify
- 90. API with NestJS #90. Using various types of SQL joins
- 91. API with NestJS #91. Dockerizing a NestJS API with Docker Compose
- 92. API with NestJS #92. Increasing the developer experience with Docker Compose
- 93. API with NestJS #93. Deploying a NestJS app with Amazon ECS and RDS
- 94. API with NestJS #94. Deploying multiple instances on AWS with a load balancer
- 95. API with NestJS #95. CI/CD with Amazon ECS and GitHub Actions
- 96. API with NestJS #96. Running unit tests with CI/CD and GitHub Actions
- 97. API with NestJS #97. Introduction to managing logs with Amazon CloudWatch
- 98. API with NestJS #98. Health checks with Terminus and Amazon ECS
- 99. API with NestJS #99. Scaling the number of application instances with Amazon ECS
- 100. API with NestJS #100. The HTTPS protocol with Route 53 and AWS Certificate Manager
- 101. API with NestJS #101. Managing sensitive data using the AWS Secrets Manager
- 102. API with NestJS #102. Writing unit tests with Prisma
- 103. API with NestJS #103. Integration tests with Prisma
- 104. API with NestJS #104. Writing transactions with Prisma
- 105. API with NestJS #105. Implementing soft deletes with Prisma and middleware
- 106. API with NestJS #106. Improving performance through indexes with Prisma
- 107. API with NestJS #107. Offset and keyset pagination with Prisma
- 108. API with NestJS #108. Date and time with Prisma and PostgreSQL
- 109. API with NestJS #109. Arrays with PostgreSQL and Prisma
- 110. API with NestJS #110. Managing JSON data with PostgreSQL and Prisma
- 111. API with NestJS #111. Constraints with PostgreSQL and Prisma
- 112. API with NestJS #112. Serializing the response with Prisma
- 113. API with NestJS #113. Logging with Prisma
- 114. API with NestJS #114. Modifying data using PUT and PATCH methods with Prisma
- 115. API with NestJS #115. Database migrations with Prisma
- 116. API with NestJS #116. REST API versioning
- 117. API with NestJS #117. CORS – Cross-Origin Resource Sharing
- 118. API with NestJS #118. Uploading and streaming videos
- 119. API with NestJS #119. Type-safe SQL queries with Kysely and PostgreSQL
- 120. API with NestJS #120. One-to-one relationships with the Kysely query builder
- 121. API with NestJS #121. Many-to-one relationships with PostgreSQL and Kysely
So far, in this series, we’ve been using TypeORM to manage our data and connect to our Postgres database. In this article, we look into Prisma, which is a capable alternative.
With Prisma, we describe our data using a Prisma schema file. It uses its own data modeling language and acts as a single source of truth. This differs from traditional ORMs that provide an object-oriented way of working with the database.
Every time we make changes to the schema file, we need to generate the Prisma client. In this process, Prisma parses our schema and creates a client along with all the TypeScript typings. This means that we no longer map SQL tables to model classes through the TypeScript code manually.
The Prisma client is a set of Node.js functions that we can call from within our code. Under the hood, the client connects to a query engine written in Rust.
Although it is possible to migrate from TypeORM to Prisma, in this aricle we set up our project from scratch.
You can find all of the code from this article in this repository.
Setting up PostgreSQL and Prisma
In this series, we are using PostgreSQL. The most straightforward way to add Postgres to our project is to do it with docker. In the second part of this series, we set up PostgreSQL with TypeORM. Let’s reuse the docker-compose file provided there:
docker-compose.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
version: "3" services: postgres: container_name: nestjs-postgres image: postgres:latest ports: - "5432:5432" volumes: - /data/postgres:/data/postgres env_file: - docker.env networks: - postgres pgadmin: links: - postgres:postgres container_name: nestjs-pgadmin image: dpage/pgadmin4 ports: - "8080:80" volumes: - /data/pgadmin:/root/.pgadmin env_file: - docker.env networks: - postgres networks: postgres: driver: bridge |
We also need to create a file that contains environment variables for our docker container.
docker.env
1 2 3 4 5 |
POSTGRES_USER=admin POSTGRES_PASSWORD=admin POSTGRES_DB=nestjs PGADMIN_DEFAULT_EMAIL=admin@admin.com PGADMIN_DEFAULT_PASSWORD=admin |
To start using Prisma, we first need to install it.
1 |
npm install prisma |
Once that’s done, we can start using the Prisma CLI. The first thing we want to do is to initialize our configuration.
1 |
npx prisma init |
Doing the above creates two files for us:
- schema.prisma: contains the database schema and specifies the connection with the database
- .env: contains environment variables
We need to modify the above .env file to adjust to the contents of docker.env:
.env
1 |
DATABASE_URL="postgresql://admin:admin@localhost:5432/nestjs?schema=public" |
Within the schema.prisma file, we have access to our environment variables. Let’s use the DATABASE_URL variable to set up the connection.
schema.prisma
1 2 3 4 5 6 7 8 |
datasource db { provider = "postgresql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } |
Installing and using the Prisma Client
To start using the Prisma Client, we first need to install it.
1 |
npm install @prisma/client |
Let’s create a PrismaService class that initializes the PrismaClient.
prisma.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common'; import { PrismaClient } from '@prisma/client'; @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { async onModuleInit() { await this.$connect(); } async onModuleDestroy() { await this.$disconnect(); } } |
We also need to create a module that exports the above service.
prisma.module.ts
1 2 3 4 5 6 7 8 9 10 |
import { Module } from '@nestjs/common'; import { PrismaService } from './prisma.service'; @Module({ imports: [], controllers: [], providers: [PrismaService], exports: [PrismaService], }) export class PrismaModule {} |
Managing basic tables with Prisma Client and Prisma Migrate
When we want to modify the structure of our database, we should create a migration. It consists of a SQL script that is supposed to make the necessary changes. Although we could write it by hand, Prisma can do it for us with the Prisma Migrate tool.
First, let’s define a simple Post model in our schema.
schema.prisma
1 2 3 4 5 6 7 |
// ... model Post { id Int @default(autoincrement()) @id title String content String } |
Above, we define the basic set of fields for our model. Above we use just the Int and String types, but there are quite a few to choose from.
Aside from defining fields, we also can define attributes. Their job is to modify the behavior of fields or models.
With the @default attribute, we define a default value for a field. When using it, we have a set of functions to choose from. Above, we use autoincrement() to create a sequence of integers.
In our Post model, we also use the @id attribute. Thanks to that, our id field becomes the primary key.
Once we’ve got our model, we can create our migration.
1 |
npx prisma migrate dev --name post --preview-feature |
Above we use the --preview-feature flag, because the Prisma Migrate tool is still in preview. It means that the functionality was validated, but there might be small bugs.
Aside from creating a file with the SQL script, running the above command also changed our database.
Using Prisma Client to manage the data
Once all of the above is done, we can start using the Prisma Client. Let’s start with the basics.
posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; @Injectable() export class PostsService { constructor(private readonly prismaService: PrismaService) {} async getPosts() { return this.prismaService.post.findMany(); } // ... } |
The prismaService.post property was created when we generated our Prisma Client based on our schema and it recognizes the properties our Post entity has.
The findMany method without any arguments returns all entities from the queried collection.
posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { PostNotFoundException } from './exceptions/postNotFound.exception'; @Injectable() export class PostsService { constructor(private readonly prismaService: PrismaService) {} async getPostById(id: number) { const post = await this.prismaService.post.findUnique({ where: { id, }, }); if (!post) { throw new PostNotFoundException(id); } return post; } // ... } |
Above, we use the findUnique method that aims to find a single entity from our collection. We need to provide it with the where property to narrow down the scope of our search.
We can also use the where property with the findMany method.
If the findUnique method returns undefined, we can assume that it didn’t find the entity. If that’s the case, we can throw an exception.
postNotFound.exception.ts
1 2 3 4 5 6 7 |
import { NotFoundException } from '@nestjs/common'; export class PostNotFoundException extends NotFoundException { constructor(postId: number) { super(`Post with id ${postId} not found`); } } |
Doing the above results in responding with the 404 Not Found status code.
If you want to know more about error handling, check out API with NestJS #4. Error handling and data validation
posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { CreatePostDto } from './dto/createPost.dto'; import { PostNotFoundException } from './exceptions/postNotFound.exception'; @Injectable() export class PostsService { constructor(private readonly prismaService: PrismaService) {} async createPost(post: CreatePostDto) { return this.prismaService.post.create({ data: post, }); } // ... } |
Above, we use the create method to save a new entity in the database. The CreatePostDto class describes all of the properties along with data validation.
createPost.dto.ts
1 2 3 4 5 6 7 8 9 10 11 |
import { IsString, IsNotEmpty } from 'class-validator'; export class CreatePostDto { @IsString() @IsNotEmpty() title: string; @IsString() @IsNotEmpty() content: string; } |
If you want to read about validation, check out API with NestJS #4. Error handling and data validation
posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { UpdatePostDto } from './dto/updatePost.dto'; import { PrismaClientKnownRequestError } from '@prisma/client/runtime'; import { PrismaError } from '../utils/prismaError'; import { PostNotFoundException } from './exceptions/postNotFound.exception'; @Injectable() export class PostsService { constructor(private readonly prismaService: PrismaService) {} async updatePost(id: number, post: UpdatePostDto) { try { return await this.prismaService.post.update({ data: { ...post, id: undefined, }, where: { id, }, }); } catch (error) { if ( error instanceof PrismaClientKnownRequestError && error.code === PrismaError.RecordDoesNotExist ) { throw new PostNotFoundException(id); } throw error; } } // ... } |
Above, we use the update method to modify an entity. It is worth noting that we ignore the id property so that the users can’t change it.
updatePost.dto.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import { IsString, IsNotEmpty, IsNumber } from 'class-validator'; export class UpdatePostDto { @IsNumber() id: number; @IsString() @IsNotEmpty() title: string; @IsString() @IsNotEmpty() content: string; } |
We need to use the try...catch to see what errors have been thrown. To do that properly, we can create an enum based on the official documentation.
prismaError.ts
1 2 3 |
export enum PrismaError { RecordDoesNotExist = 'P2025', } |
posts.service.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import { Injectable } from '@nestjs/common'; import { PrismaService } from '../prisma/prisma.service'; import { PrismaClientKnownRequestError } from '@prisma/client/runtime'; import { PrismaError } from '../utils/prismaError'; import { PostNotFoundException } from './exceptions/postNotFound.exception'; @Injectable() export class PostsService { constructor(private readonly prismaService: PrismaService) {} async deletePost(id: number) { try { return this.prismaService.post.delete({ where: { id, }, }); } catch (error) { if ( error instanceof PrismaClientKnownRequestError && error.code === PrismaError.RecordDoesNotExist ) { throw new PostNotFoundException(id); } throw error; } } // ... } |
Above with the delete method, we do a very similar thing in terms of error handling.
Once we’ve got our service ready, we can create a controller that uses it.
posts.controller.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
import { Body, Controller, Delete, Get, Param, Patch, Post, } from '@nestjs/common'; import { PostsService } from './posts.service'; import { CreatePostDto } from './dto/createPost.dto'; import { UpdatePostDto } from './dto/updatePost.dto'; import { FindOneParams } from '../utils/findOneParams'; @Controller('posts') export default class PostsController { constructor(private readonly postsService: PostsService) { } @Get() async getPosts() { return this.postsService.getPosts(); } @Get(':id') getPostById(@Param() { id }: FindOneParams) { return this.postsService.getPostById(Number(id)); } @Post() async createPost(@Body() post: CreatePostDto) { return this.postsService.createPost(post); } @Put(':id') async updatePost( @Param() { id }: FindOneParams, @Body() post: UpdatePostDto, ) { return this.postsService.updatePost(Number(id), post); } @Delete(':id') async deletePost(@Param() { id }: FindOneParams) { return this.postsService.deletePost(Number(id)); } } |
It is worth noting that above we use the FindOneParams that transforms ids from strings to numbers.
findOneParams.ts
1 2 3 4 5 6 7 8 |
import { IsNumber } from 'class-validator'; import { Transform } from 'class-transformer'; export class FindOneParams { @IsNumber() @Transform(({ value }) => Number(value)) id: number; } |
Using multiple schema files
Putting all of our schema definitions into a single file might make it difficult to maintain. Unfortunately, Prisma currently does not support multiple schema files.
To deal with this issue, we can create a simple bash script that merges multiple schemas into one.
package.json
1 2 3 4 5 6 7 8 |
{ "name": "nestjs-prisma", "scripts": { // ... "generate-schema": "cat src/*/*.prisma > prisma/schema.prisma" }, // ... } |
Running cat src/*/*.prisma > prisma/schema.prisma merges all .prisma files into the prisma/schema.prisma directory. It traverses through all of the subdirectories of src.
The cat command is available in Linux, Mac, and Windows Power Shell
We can also put the file schema.prisma into .gitignore so that we don’t have multiple sources of truth.
.gitignore
1 2 |
# ... prisma/schema.prisma |
Doing the above allows us to keep separate schema files for specific modules. Let’s split our existing schema into multiple files:
baseSchema.prisma
1 2 3 4 5 6 7 8 |
datasource db { provider = "postgresql" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } |
postSchema.prisma
1 2 3 4 5 |
model Post { id Int @default(autoincrement()) @id title String content String } |
We end up with the following file structure:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
├── docker-compose.yml ├── docker.env ├── nest-cli.json ├── package.json ├── package-lock.json ├── prisma │ ├── migrations │ │ ├── 20210327185422_post │ │ │ └── migration.sql │ │ └── migration_lock.toml │ └── schema.prisma ├── README.md ├── src │ ├── app.module.ts │ ├── main.ts │ ├── posts │ │ ├── dto │ │ │ ├── createPost.dto.ts │ │ │ └── updatePost.dto.ts │ │ ├── exceptions │ │ │ └── postNotFound.exception.ts │ │ ├── postSchema.prisma │ │ ├── posts.controller.ts │ │ ├── posts.module.ts │ │ └── posts.service.ts │ ├── prisma │ │ ├── baseSchema.prisma │ │ ├── prisma.module.ts │ │ └── prisma.service.ts │ └── utils │ ├── findOneParams.ts │ └── prismaError.ts ├── tsconfig.build.json └── tsconfig.json |
Summary
In this article, we’ve learned the basics of Prisma. We’ve got to know its main principles and we’ve created a simple CRUD API with it. To do that, we’ve had to get familiar with the basics of the data modeling language Prisma uses. It also required us to learn about the basics of the Prisma Migrate tool. There is still quite a lot to learn about Prisma, so stay tuned!
More Prisma articles please! I’d like to know more advanced features
Hi Mr Wanago,
I want to redesign my backend API service and make use of DI or existing framework so choose to start with Nestjs and following your series of article on Nestjs, it seems very promising and I am at 8th article.
I was earlier using express with bookshelf ORM.
Just want to know which ORM should I start to explore:TypeORM or Prisma as you have used both: what should I follow and why?