fashionAvenue / server / src / user / user.service.ts
user.service.ts
Raw
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { CreateUserDto } from './dto/create-user.dto';

@Injectable()
export class UserService {
  constructor(private prisma: PrismaService) {}
  async create(dto: CreateUserDto) {
    return this.prisma.users.create({
      data: dto,
    });
  }

  async findByUsername(username: string) {
    return await this.prisma.users.findUnique({
      where: {
        username,
      },
    });
  }

  async findById(id: number) {
    return await this.prisma.users.findUnique({
      where: {
        id,
      },
    });
  }

  async logout(id: number) {
    return await this.prisma.users.updateMany({
      where: {
        id,
        hashedRt: {
          not: null,
        },
      },
      data: {
        hashedRt: null,
      },
    });
  }

  async updateRtHash(id: number, hash: string) {
    await this.prisma.users.update({
      where: {
        id,
      },
      data: {
        hashedRt: hash,
      },
    });
  }

  async addToCart(userId: number, productId: number) {
    await this.prisma.cart.upsert({
      where: {
        productId_userId: {
          productId,
          userId,
        },
      },
      update: {
        quantity: { increment: 1 },
      },
      create: {
        userId,
        productId,
        quantity: 1,
      },
    });
  }

  async removeFromCart(userId: number, productId: number) {
    const item = await this.prisma.cart.findUnique({
      where: {
        productId_userId: {
          productId,
          userId,
        },
      },
    });
    if (item.quantity < 2) {
      await this.prisma.cart.delete({
        where: {
          productId_userId: {
            productId,
            userId,
          },
        },
      });
    } else {
      await this.prisma.cart.update({
        where: {
          productId_userId: {
            productId,
            userId,
          },
        },
        data: {
          quantity: { decrement: 1 },
        },
      });
    }
  }

  async getAllCartItems(userId: number) {
    const cartItems = await this.prisma.cart.findMany({
      where: { userId },
      include: { product: true },
      orderBy: { productId: 'asc' },
    });
    return cartItems.map((val) => {
      return {
        id: val.productId,
        name: val.product.name,
        image: val.product.image,
        quantity: val.quantity,
        price: val.product.price,
        color: val.product.color,
        season: val.product.season,
      };
    });
  }

  async deleteItem(userId: number, productId: number) {
    await this.prisma.cart.delete({
      where: {
        productId_userId: {
          productId,
          userId,
        },
      },
    });
  }
}