Nest.js Tutorial

Modifying data using PUT and PATCH methods with Prisma

Marcin Wanago
NestJS

Developing a REST API requires us to create endpoints using various HTTP methods such as GET, POST, and DELETE. People utilizing our API expect that making a GET request lists data instead of deleting it. It’s the developer’s role to ensure that the API is easy to understand and follows the best practices. While most HTTP methods are straightforward, we can use either POST or the PATCH method to modify existing data. In this article, we learn how to use both of them and outline their differences.

PUT

In the previous parts of this series, we’ve defined a model of a post.

postSchema.prisma
1model Post {
2  id         Int        @id @default(autoincrement())
3  title      String
4  paragraphs String[]
5  author     User       @relation(fields: [authorId], references: [id])
6  authorId   Int
7  categories Category[]
8 
9  scheduledDate DateTime? @db.Timestamptz
10 
11  @@index([authorId])
12}

It has a few required properties and the optional scheduledDate. First, let’s take a look at one of the existing posts.

1GET /posts/1
Response:
1{
2    "id": 1,
3    "title": "Hello world!",
4    "paragraphs": [
5        "Lorem ipsum"
6    ],
7    "authorId": 1,
8    "scheduledDate": "2023-07-13T10:00:00.000Z"
9}

One way of modifying existing posts would be by using a PUT method. It changes existing entities by replacing them. Therefore, if the request does not contain a particular field, the field should be removed.

1PUT /posts/1
Request body:
1{
2    "id": 1,
3    "title": "The first article",
4    "paragraphs": [
5        "Lorem ipsum"
6    ],
7    "authorId": 1
8}
Response:
1{
2    "id": 1,
3    "title": "Hello world!",
4    "paragraphs": [
5        "Lorem ipsum"
6    ],
7    "authorId": 1,
8    "scheduledDate": null
9}

Since our request body does not contain the scheduledDate property, it should be set to null.

Implementing the PUT method with Prisma

The update method is the most straightforward way to modify an entity using Prisma.

1this.prismaService.post.update({
2  data: {
3    id: 1,
4    title: 'The first article',
5    paragraphs: [
6      'Lorem ipsum'
7    ],
8    authorId: 1
9  },
10  where: {
11    id: 1,
12  },
13});

The most important thing about the update method is that it only affects the properties provided explicitly. This means that to remove the scheduledDate property, we need to mark it as null explicitly.

1this.prismaService.post.update({
2  data: {
3    id: 1,
4    title: 'The first article',
5    paragraphs: [
6      'Lorem ipsum'
7    ],
8    authorId: 1,
9    scheduledDate: null,
10  },
11  where: {
12    id: 1,
13  },
14});

To deal with this problem, we can create a Data Transfer Object that assigns null as a default value.

replacePost.dto.ts
1import {IsString, IsNotEmpty, IsNumber, IsOptional, IsISO8601} from 'class-validator';
2 
3export class ReplacePostDto {
4  @IsNumber()
5  id: number;
6 
7  @IsString()
8  @IsNotEmpty()
9  title: string;
10 
11  @IsString({ each: true })
12  @IsNotEmpty()
13  paragraphs: string[];
14 
15  @IsISO8601({
16    strict: true,
17  })
18  @IsOptional()
19  scheduledDate: string | null = null;
20}
It is worth noting that we use the @IsOptional() decorator above that allows scheduledDate to be undefined, or null.

We can now use the above DTO in our service. To prevent Prisma from modifying the id of existing posts, we can provide undefined as the id.

posts.service.ts
1import { Injectable } from '@nestjs/common';
2import { PrismaService } from '../prisma/prisma.service';
3import { Prisma } from '@prisma/client';
4import { PrismaError } from '../utils/prismaError';
5import { PostNotFoundException } from './exceptions/postNotFound.exception';
6import { ReplacePostDto } from './dto/replacePost.dto';
7 
8@Injectable()
9export class PostsService {
10  constructor(private readonly prismaService: PrismaService) {}
11 
12  async replacePost(id: number, post: ReplacePostDto) {
13    try {
14      return await this.prismaService.post.update({
15        data: {
16          ...post,
17          id: undefined,
18        },
19        where: {
20          id,
21        },
22      });
23    } catch (error) {
24      if (
25        error instanceof Prisma.PrismaClientKnownRequestError &&
26        error.code === PrismaError.RecordDoesNotExist
27      ) {
28        throw new PostNotFoundException(id);
29      }
30      throw error;
31    }
32  }
33 
34  // ...
35}

An important thing above is that we are using the PrismaError enum we created in some of the previous parts of this series. It helps us understand the error that happened and allows us to act accordingly.

prismaError.ts
1export enum PrismaError {
2  RecordDoesNotExist = 'P2025',
3  UniqueConstraintFailed = 'P2002',
4}

The last step is to add a PUT method handler to our controller.

posts.controller.ts
1import {
2  Body,
3  Controller,
4  Param,
5  Put,
6} from '@nestjs/common';
7import { PostsService } from './posts.service';
8import { FindOneParams } from '../utils/findOneParams';
9import { ReplacePostDto } from './dto/replacePost.dto';
10 
11@Controller('posts')
12export default class PostsController {
13  constructor(private readonly postsService: PostsService) {}
14 
15  @Put(':id')
16  async replacePost(
17    @Param() { id }: FindOneParams,
18    @Body() post: ReplacePostDto,
19  ) {
20    return this.postsService.replacePost(id, post);
21  }
22 
23  // ...
24}

Thanks to using our DTO, if the users make a PUT request without providing the scheduledDate, we change it to null.

PATCH

Another approach to modifying existing entities is through a PATCH method. The HTTP protocol describes it as modifying an entity partially through a set of instructions. The most straightforward way of implementing it is by sending a request body with the partial entity.

1PATCH /posts/1
Request body:
1{
2    "id": 1,
3    "title": "The first article",
4    "paragraphs": [
5        "Lorem ipsum"
6    ],
7    "authorId": 1
8}
Response:
1{
2    "id": 1,
3    "title": "The first article",
4    "paragraphs": [
5        "Lorem ipsum"
6    ],
7    "authorId": 1,
8    "scheduledDate": "2023-07-13T10:00:00.000Z"
9}

The crucial thing about the above request is that we don’t provide the scheduledDate property when modifying our post. To delete a property, we need to send null explicitly. Thanks to that, we can avoid removing values by accident.

Implementing the PATCH method with Prisma

Let’s start by creating a new Data Transfer Object for the PATCH method. Since with sending a PATCH request, all properties are optional, we might think of using the @IsOptional() decorator.

updatePost.dto.ts
1import {
2  IsString,
3  IsNotEmpty,
4  IsNumber,
5  IsISO8601,
6  IsOptional,
7} from 'class-validator';
8 
9export class UpdatePostDto {
10  @IsNumber()
11  @IsOptional()
12  id?: number;
13 
14  @IsString()
15  @IsNotEmpty()
16  @IsOptional()
17  title?: string;
18 
19  @IsString({ each: true })
20  @IsNotEmpty()
21  @IsOptional()
22  paragraphs?: string[];
23 
24  @IsISO8601({
25    strict: true,
26  })
27  @IsOptional()
28  scheduledDate?: string | null;
29}

However, there is one big issue with it. Unfortunately, it causes the class-validator to allow both undefined and null as the value for the decorated property. This can cause an Internal server error in our application because most of our columns are not nullable. We can solve this problem by using the ValidateIf decorator.

updatePost.dto.ts
1import {
2  IsString,
3  IsNotEmpty,
4  IsNumber,
5  IsISO8601,
6  ValidateIf,
7} from 'class-validator';
8 
9export class UpdatePostDto {
10  @IsNumber()
11  @ValidateIf((object, value) => value !== undefined)
12  id?: number;
13 
14  @IsString()
15  @IsNotEmpty()
16  @ValidateIf((object, value) => value !== undefined)
17  title?: string;
18 
19  @IsString({ each: true })
20  @IsNotEmpty()
21  @ValidateIf((object, value) => value !== undefined)
22  paragraphs?: string[];
23 
24  @IsISO8601({
25    strict: true,
26  })
27  @ValidateIf((object, value) => value !== undefined && value !== null)
28  scheduledDate?: string | null;
29}

With the above code, we validate the properties only if they match the provided condition. We can simplify our DTO a lot by creating two custom decorators that use ValidateIf() under the hood.

canBeNull.ts
1import { ValidateIf } from 'class-validator';
2 
3export function CanBeNull() {
4  return ValidateIf((object, value) => value !== null);
5}
canBeUndefined.ts
1import { ValidateIf } from 'class-validator';
2 
3export function CanBeUndefined() {
4  return ValidateIf((object, value) => value !== undefined);
5}

Thanks to our new decorators, our code can be cleaner and shorter.

updatePost.dto.ts
1import { IsString, IsNotEmpty, IsNumber, IsISO8601 } from 'class-validator';
2import { CanBeUndefined } from '../../utils/canBeUndefined';
3import { CanBeNull } from '../../utils/canBeNull';
4 
5export class UpdatePostDto {
6  @IsNumber()
7  @CanBeUndefined()
8  id?: number;
9 
10  @IsString()
11  @IsNotEmpty()
12  @CanBeUndefined()
13  title?: string;
14 
15  @IsString({ each: true })
16  @IsNotEmpty()
17  @CanBeUndefined()
18  paragraphs?: string[];
19 
20  @IsISO8601({
21    strict: true,
22  })
23  @CanBeUndefined()
24  @CanBeNull()
25  scheduledDate?: string | null;
26}

Implementing the PATCH method with Prisma is very straightforward, thanks to how the update method works. It modifies only the explicitly provided properties, which is precisely what we need.

posts.service.ts
1import { Injectable } from '@nestjs/common';
2import { PrismaService } from '../prisma/prisma.service';
3import { UpdatePostDto } from './dto/updatePost.dto';
4import { Prisma } from '@prisma/client';
5import { PrismaError } from '../utils/prismaError';
6import { PostNotFoundException } from './exceptions/postNotFound.exception';
7 
8@Injectable()
9export class PostsService {
10  constructor(private readonly prismaService: PrismaService) {}
11 
12  async updatePost(id: number, post: UpdatePostDto) {
13    try {
14      return await this.prismaService.post.update({
15        data: {
16          ...post,
17          id: undefined,
18        },
19        where: {
20          id,
21        },
22      });
23    } catch (error) {
24      if (
25        error instanceof Prisma.PrismaClientKnownRequestError &&
26        error.code === PrismaError.RecordDoesNotExist
27      ) {
28        throw new PostNotFoundException(id);
29      }
30      throw error;
31    }
32  }
33  
34  // ...
35}

Finally, we need to add the PUT method handler to our controller.

posts.controller.ts
1import { Body, Controller, Param, Put } from '@nestjs/common';
2import { PostsService } from './posts.service';
3import { FindOneParams } from '../utils/findOneParams';
4import { ReplacePostDto } from './dto/replacePost.dto';
5 
6@Controller('posts')
7export default class PostsController {
8  constructor(private readonly postsService: PostsService) {}
9 
10  @Put(':id')
11  async replacePost(
12    @Param() { id }: FindOneParams,
13    @Body() post: ReplacePostDto,
14  ) {
15    return this.postsService.replacePost(id, post);
16  }
17 
18  // ...
19}

Thanks to all of the above, we can now support a PUT method.

Summary

Both the PUT and PATCH method have their use cases and can be useful. However, with the PATCH method, we don’t expect the user to know about all of the properties of our entity. Since deleting a value requires the users to provide null explicitly, it is less likely that they will remove a property by accident.

Since, in this article, we’ve gone through both PUT and PATCH and implemented them in our application with NestJS in Prisma, you now have the necessary knowledge to use the approach that suits your project the most.