All files / report report.service.ts

100% Statements 61/61
100% Branches 18/18
100% Functions 17/17
100% Lines 59/59

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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260          18x 18x 18x 18x 18x     18x         18x           18x   34x 34x 34x 34x 34x 34x 34x 34x                                 6x       6x   6x 5x   5x 4x 3x           1x         1x     1x                     2x       2x                   3x         3x 2x   1x                   4x                                 3x       3x                           2x         2x 1x   1x                     3x       3x         3x                   4x   4x 3x   1x                     4x   4x 3x             3x 3x   1x                     3x   3x 2x   1x                   2x                 1x   1x      
/**
 * Report service.
 * @packageDocumentation
 */
 
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { DBService } from '../db/db.service';
import { ResourceService } from '../resource/resource.service';
import { UserService } from '../user/user.service';
import { BookService, bookTableName } from '../book/book.service';
import { NBReport } from './report.interface';
import { NBBook } from '../../services/book/book.interface';
import { ServiceException } from '../service.exception';
 
/**
 * Report table name.
 */
export const reportTableName = 'NB_REPORT';
 
/**
 * Report table service.
 */
@Injectable()
export class ReportService {
  constructor(
    @Inject(forwardRef(() => DBService))
    private readonly dbService: DBService,
    @Inject(forwardRef(() => ResourceService))
    private readonly resourceService: ResourceService,
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    @Inject(forwardRef(() => BookService))
    private readonly bookService: BookService,
  ) {}
 
  /**
   * Report a book.
   *
   * @param userID The ID of the user reporting the book.
   * @param bookID The book's ID.
   * @param reason The reason for reporting.
   * @returns The new book record.
   */
  public async reportBook(
    userID: string,
    bookID: string,
    reason: string,
  ): Promise<NBReport> {
    const reportReasonMaxLength =
      await this.resourceService.getResource<number>(
        'REPORT_REASON_MAX_LENGTH',
      );
 
    const userExists = await this.userService.userExists(userID);
 
    if (userExists) {
      const bookExists = await this.bookService.bookExists(bookID);
 
      if (bookExists) {
        if (reason.length >= 1 && reason.length <= reportReasonMaxLength) {
          return this.dbService.create<NBReport>(reportTableName, {
            bookID,
            userID,
            reason,
          });
        } else {
          throw new ServiceException(
            `Report reason must be between 1 and ${reportReasonMaxLength} characters`,
          );
        }
      } else {
        throw new ServiceException('Book does not exist');
      }
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Determine whether or not a report exists.
   *
   * @param reportID The report's ID.
   * @returns Whether or not the report exists.
   */
  public async reportExists(reportID: string): Promise<boolean> {
    const report = await this.dbService.getByID<NBReport>(
      reportTableName,
      reportID,
    );
    return !!report;
  }
 
  /**
   * Get a report.
   *
   * @param reportID The report's ID.
   * @returns The report record.
   */
  public async getReport(reportID: string): Promise<NBReport> {
    const report = await this.dbService.getByID<NBReport>(
      reportTableName,
      reportID,
    );
 
    if (report) {
      return report;
    } else {
      throw new ServiceException('Report does not exist');
    }
  }
 
  /**
   * Get all reports.
   *
   * @returns All reports.
   */
  public async getReports(): Promise<NBReport[]> {
    return this.dbService.list<NBReport>(reportTableName, {
      fieldName: 'reportTime',
      sortOrder: 'ASC',
    });
  }
 
  /**
   * Determine whether or not a user has reported a book.
   *
   * @param userID The user's ID.
   * @param bookID The book's ID.
   * @returns Whether or not the user has reported the book.
   */
  public async userReportedBook(
    userID: string,
    bookID: string,
  ): Promise<boolean> {
    const report = await this.dbService.getByFields<NBReport>(reportTableName, {
      userID,
      bookID,
    });
    return !!report;
  }
 
  /**
   * Get a user report for a book.
   *
   * @param userID The user's ID.
   * @param bookID The book's ID.
   * @returns The report.
   */
  public async getUserBookReport(
    userID: string,
    bookID: string,
  ): Promise<NBReport> {
    const report = await this.dbService.getByFields<NBReport>(reportTableName, {
      userID,
      bookID,
    });
 
    if (report) {
      return report;
    } else {
      throw new ServiceException('Report does not exist');
    }
  }
 
  /**
   * Determine whether or not a user has recently reported a book.
   *
   * @param userID The user's ID.
   * @returns Whether or not the user has recently reported a book.
   */
  public async userReportedRecently(userID: string): Promise<boolean> {
    const userReportCooldown = await this.resourceService.getResource<number>(
      'USER_REPORT_COOLDOWN',
    );
 
    const report = await this.dbService.getCustom<NBReport>(
      reportTableName,
      '"userID" = ? AND EXTRACT(EPOCH FROM NOW() - "reportTime") <= ?',
      [userID, userReportCooldown],
    );
    return !!report;
  }
 
  /**
   * Get all reports made by a user.
   *
   * @param userID The user's ID.
   * @returns All reports made by the user.
   */
  public async getUserBookReports(userID: string): Promise<NBReport[]> {
    const userExists = await this.userService.userExists(userID);
 
    if (userExists) {
      return this.dbService.listByFields<NBReport>(reportTableName, { userID });
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Get all books reported by a user.
   *
   * @param userID The user's ID.
   * @returns All books reported by the user.
   */
  public async getUserReportedBooks(userID: string): Promise<NBBook[]> {
    const userExists = await this.userService.userExists(userID);
 
    if (userExists) {
      const sql = `
        SELECT "${bookTableName}".*
          FROM "${reportTableName}"
          JOIN "${bookTableName}"
            ON "${reportTableName}"."bookID" = "${bookTableName}".id
        WHERE "${reportTableName}"."userID" = ?
        ORDER BY "${reportTableName}"."reportTime" ASC;`;
      const params = [userID];
      return this.dbService.execute<NBBook>(sql, params);
    } else {
      throw new ServiceException('User does not exist');
    }
  }
 
  /**
   * Get all reports for a book.
   *
   * @param bookID The book's ID.
   * @returns All reports for the book.
   */
  public async getBookReports(bookID: string): Promise<NBReport[]> {
    const bookExists = await this.bookService.bookExists(bookID);
 
    if (bookExists) {
      return this.dbService.listByFields<NBReport>(reportTableName, { bookID });
    } else {
      throw new ServiceException('Book does not exist');
    }
  }
 
  /**
   * Delete a report.
   *
   * @param reportID The report's ID.
   */
  public async deleteReport(reportID: string): Promise<void> {
    await this.dbService.deleteByID(reportTableName, reportID);
  }
 
  /**
   * Delete a reported book and all reports associated with it.
   *
   * @param reportID The report's ID.
   */
  public async deleteReportedBook(reportID: string): Promise<void> {
    const report = await this.getReport(reportID);
 
    await this.bookService.deleteBook(report.bookID, false);
  }
}