User logic

Let's then implement the CRUD logic, but now following Prisma's pattern.

First, let's inject a PrismaService in the UsersService, which will give us an interface for interacting with the database, much like TypeORM's Repository.

private readonly prisma: PrismaService

Now, we shall implement each one of the methods. Note that the interface offered by Prisma is very intuitive and succint. Instead of needing a repository for each entity, prisma simply accesses the desired entity and then the operation.

create(createUserDto: CreateUserDto) {
  return this.prisma.user.create({ data: createUserDto });
}

findAll() {
  return this.prisma.user.findMany();
}

findOne(id: number) {
  return this.prisma.user.findUniqueOrThrow({ where: { id } });
}

update(id: number, updateUserDto: UpdateUserDto) {
  return this.prisma.user.update({ where: { id }, data: updateUserDto });
}

remove(id: number) {
  return this.prisma.user.delete({ where: { id } });
}

A huge advantage that Prisma has in comparison to TypeORM is the type safety offered when fetching entities. For instance, if an entity is fetched without a certain relation, then a dynamic type is generated to prevent it from being accessible.

Commit - Implementing user logic

Last updated