File

src/users/users.service.ts

Description

Injectable decorator marks this class as a provider that can be injected into other components

Index

Methods

Constructor

constructor(prisma: PrismaService)

Constructor that injects PrismaService

Parameters :
Name Type Optional Description
prisma PrismaService No
  • An instance of PrismaService for database interactions

Methods

createToken
createToken()

Generates a custom token for the user

Returns : string

A generated token in the format 'AAAA-1234-AB12'

createUser
createUser(data: CreateUserDto)

Creates a new user with the provided data

Parameters :
Name Type Optional Description
data CreateUserDto No
  • The DTO for creating a user
Returns : any

The created user

Async deleteUserById
deleteUserById(id: number)

Deletes a user by their ID

Parameters :
Name Type Optional Description
id number No
  • The ID of the user
Returns : unknown

The deleted user

getUserById
getUserById(id: number)

Retrieves a user by their ID

Parameters :
Name Type Optional Description
id number No
  • The ID of the user
Returns : any

The user with the specified ID

getUsers
getUsers()

Retrieves all users

Returns : any

An array of all users

Async updateUserById
updateUserById(id: number, data: Prisma.UserUpdateInput)

Updates a user by their ID with the provided data

Parameters :
Name Type Optional Description
id number No
  • The ID of the user
data Prisma.UserUpdateInput No
  • The data to update the user with
Returns : unknown

The updated user

import { HttpException, HttpStatus, Injectable } from '@nestjs/common';

import { Prisma } from '@prisma/client';

import PrismaService from '@/prisma/prisma.service';

import { CreateUserDto } from './dtos/create-user.dto';
import { generateCustomUuid } from 'custom-uuid';

/**
 * Injectable decorator marks this class as a provider that can be injected into other components
 */
@Injectable()
export class UsersService {
  /**
   * Constructor that injects PrismaService
   *
   * @param prisma - An instance of PrismaService for database interactions
   */
  constructor(private prisma: PrismaService) {}

  /**
   * Creates a new user with the provided data
   *
   * @param data - The DTO for creating a user
   * @returns The created user
   */
  createUser(data: CreateUserDto) {
    return this.prisma.user.create({
      data: {
        ...data,
        token: this.createToken(),
      },
    });
  }

  /**
   * Retrieves all users
   *
   * @returns An array of all users
   */
  getUsers() {
    return this.prisma.user.findMany();
  }

  /**
   * Retrieves a user by their ID
   *
   * @param id - The ID of the user
   * @returns The user with the specified ID
   */
  getUserById(id: number) {
    return this.prisma.user.findUnique({
      where: { id },
    });
  }

  /**
   * Updates a user by their ID with the provided data
   *
   * @param id - The ID of the user
   * @param data - The data to update the user with
   * @returns The updated user
   * @throws HttpException if the user is not found, if the token is being updated, or if the email already exists
   */
  async updateUserById(id: number, data: Prisma.UserUpdateInput) {
    if (data.token) {
      throw new HttpException(
        'Token cannot be updated',
        HttpStatus.BAD_REQUEST,
      );
    }

    const findUserId = await this.getUserById(id);
    if (!findUserId)
      throw new HttpException('User not found', HttpStatus.NOT_FOUND);

    if (data.email) {
      const findUserEmail = await this.prisma.user.findUnique({
        where: { email: data.email as string },
      });
      if (findUserEmail)
        throw new HttpException('Email already exists', HttpStatus.CONFLICT);
    }

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

  /**
   * Deletes a user by their ID
   *
   * @param id - The ID of the user
   * @returns The deleted user
   * @throws HttpException if the user is not found
   */
  async deleteUserById(id: number) {
    const findUser = await this.getUserById(id);
    if (!findUser)
      throw new HttpException('User not found', HttpStatus.NOT_FOUND);

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

  /**
   * Generates a custom token for the user
   *
   * @returns A generated token in the format 'AAAA-1234-AB12'
   */
  createToken() {
    const letters = generateCustomUuid('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4);
    const numbers = generateCustomUuid('1234567890', 4);
    const combined = generateCustomUuid(
      'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890',
      4,
    );

    return `${letters}-${numbers}-${combined}`;
  }
}

export default UsersService;

results matching ""

    No results matching ""