Shoulder.dev Logo Shoulder.dev

CRUD Operations

Scenario:

In this real-world example, we will explore how to perform Create, Read, Update, and Delete (CRUD) operations on data using the Prisma client in the gothinkster/node-express-realworld-example-app project. This project is a full-stack real-world example built with Node.js, Express, Prisma, and TypeScript.

Solution:

First, let's understand the Prisma client and its role in the project. Prisma is an open-source database toolkit that provides a powerful and flexible way to interact with databases. It is used extensively in the gothinkster/node-express-realworld-example-app to perform CRUD operations.

  1. Create Operation: To create a new record, we will use the Prisma client's create method. Let's create a new user:
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function createUser(data: UserCreateInput) {
  const user = await prisma.user.create({ data });
  return user;
}
  1. Read Operation: To read a record, we will use the Prisma client's findUnique or findMany methods. Let's read a user by their email:
async function getUserByEmail(email: string) {
  const user = await prisma.user.findUnique({ where: { email } });
  return user;
}
  1. Update Operation: To update a record, we will use the Prisma client's update method. Let's update a user's name:
async function updateUserName(userId: number, newName: string) {
  const user = await prisma.user.update({
    where: { id: userId },
    data: { name: newName },
  });
  return user;
}
  1. Delete Operation: To delete a record, we will use the Prisma client's delete method. Let's delete a user:
async function deleteUser(userId: number) {
  const user = await prisma.user.delete({ where: { id: userId } });
  return user;
}

Tests:

To verify the CRUD operations, we will write tests using Jest and Prisma Mock. Here's an example test for the createUser function:

import { PrismaClient } from '@prisma/client';
import { UserCreateInput } from '../src/app/models/user';
import { prisma } from '../src/prisma/prisma-client';

jest.mock('../src/prisma/prisma-client');

describe('createUser', () => {
  it('should create a new user', async () => {
    const prismaMock = prisma as jest.Mocked<PrismaClient>;
    const data: UserCreateInput = {
      email: '[email protected]',
      name: 'Test User',
      password: 'password',
    };

    prismaMock.user.create.mockResolvedValueOnce({
      id: 1,
      email: data.email,
      name: data.name,
      createdAt: new Date(),
      updatedAt: new Date(),
    });

    const result = await createUser(data);

    expect(result).toEqual({
      id: 1,
      email: data.email,
      name: data.name,
      createdAt: expect.any(Date),
      updatedAt: expect.any(Date),
    });

    expect(prismaMock.user.create).toHaveBeenCalledWith({ data });
  });
});

References:

Videos:

  • AWS re:Invent 2022 - Are you ready? Essential strategies for Kubernetes adoption (CON326)
  • Log Support in OpenTelemetry - Steve Flanders, Splunk
  • How To Build Kubernetes Policies To Ensure Compliance for Databases
  • AWS re:Invent 2022 - How Alloy synced Amazon data in real time (BWP302)