All files / db/services lastwill.service.ts

100% Statements 25/25
100% Branches 2/2
100% Functions 8/8
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 706x 6x         6x     6x 5x     5x             4x 4x       4x       2x       5x     5x 2x               3x 3x         3x 1x       2x 2x       6x       6x 6x      
import { InjectModel } from '@m8a/nestjs-typegoose'
import { Injectable, Logger, NotFoundException } from '@nestjs/common'
import { ReturnModelType } from '@typegoose/typegoose'
import { ObjectId } from 'mongoose'
import { CreateLastWillDto } from '../../lastwill/dto/create-lastwill.dto'
import { UpdateLastWillDto } from '../../lastwill/dto/update-lastwill.dto'
import { LastWill } from '../entities/lastwill.entity'
 
@Injectable()
export class LastWillDBService {
  private readonly logger = new Logger(LastWillDBService.name)
  constructor(
    @InjectModel(LastWill)
    private readonly lastWillModel: ReturnModelType<typeof LastWill>,
  ) {}
 
  async createOne(
    createLastWillDto: CreateLastWillDto,
    userId: ObjectId,
  ): Promise<LastWill> {
    this.logger.log('Creating new Lastwill')
    const createdLastWill = await this.lastWillModel.create({
      ...createLastWillDto,
      accountId: userId,
    })
    return createdLastWill.toObject() satisfies LastWill
  }
 
  async findAllByUser(userId: ObjectId): Promise<LastWill[]> {
    return await this.lastWillModel.find({ accountId: userId }).lean()
  }
 
  async findFullById(id: string, userId: ObjectId): Promise<LastWill> {
    const lastWill = await this.lastWillModel
      .findOne({ _id: id, accountId: userId })
      .lean()
    if (!lastWill) throw new NotFoundException('Last will not found')
    return lastWill
  }
 
  async updateOneById(
    id: string,
    userId: ObjectId,
    updateLastWillDto: UpdateLastWillDto,
  ): Promise<LastWill> {
    this.logger.log('Updating last will')
    const updatedLastWill = await this.lastWillModel
      .findOneAndUpdate({ _id: id, accountId: userId }, updateLastWillDto, {
        new: true,
      })
      .lean()
    if (!updatedLastWill) throw new NotFoundException('Last will not found')
    return updatedLastWill
  }
 
  async deleteOneById(id: string, userId: ObjectId): Promise<void> {
    this.logger.log('Deleting last will')
    await this.lastWillModel.deleteOne({ _id: id, accountId: userId })
  }
 
  async countDocuments(accountId: ObjectId): Promise<number> {
    return await this.lastWillModel.countDocuments({ accountId })
  }
 
  async deleteAllByUser(accountId: ObjectId): Promise<void> {
    this.logger.log('Deleting all last wills for user')
    await this.lastWillModel.deleteMany({ accountId })
  }
}