All files / db db.service.ts

54.87% Statements 107/195
14.75% Branches 9/61
61.54% Functions 32/52
55.68% Lines 103/185

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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678          18x 18x 18x 18x 18x 18x 18x 18x 18x         18x 643x           18x 458x                                                                     18x   34x 34x 34x 34x     34x 34x                                       34x 34x 34x 34x 34x 34x 34x 34x   34x           34x                                                 1584x 1584x 2055x   1584x                           1584x   1584x   1584x 1584x 1584x 1584x                                                                                                                                                                                                                                                                                                                                                                                         2x     2x 2x   48x 48x     2x                                                                                                                             111x     390x     390x   111x   111x 111x                   490x 490x   490x 490x                   680x     723x   680x   680x 680x                             6x   6x 6x                         19x     19x   19x 19x                             51x     51x     51x     51x   51x 51x                                 4x     4x   4x 4x                             35x     42x       35x   35x 35x                             9x     9x       9x     9x   9x 9x                                 1x     1x       1x   1x 1x                 90x 90x   90x                       21x     38x   21x   21x                           2x   2x      
/**
 * Database service.
 * @packageDocumentation
 */
 
import { Injectable, Inject, forwardRef } from '@nestjs/common';
import { Pool, types } from 'pg';
import * as fs from 'fs';
import * as path from 'path';
import * as csv from 'csv';
import { ResourceService } from '../resource/resource.service';
import { UserService } from '../user/user.service';
import { VerifyService } from '../verify/verify.service';
import { PasswordResetService } from '../password-reset/password-reset.service';
 
/**
 * Parse timestamp type.
 */
types.setTypeParser(1114, (timestamp) =>
  new Date(timestamp + '+0000').getTime(),
);
 
/**
 * Parse money type.
 */
types.setTypeParser(790, (amount) =>
  parseFloat(amount.slice(1).replace(/,/g, '')),
);
 
/**
 * Map of fields to values.
 */
interface FieldMap {
  [fieldName: string]: any;
}
 
/**
 * Query sort order options.
 */
type SortOrder = 'ASC' | 'DESC';
 
/**
 * Order options.
 */
interface OrderOptions {
  fieldName: string;
  sortOrder: SortOrder;
}
 
/**
 * Database initialization options
 */
interface InitDBOptions {
  populateStatic?: boolean;
  prune?: boolean;
}
 
/**
 * Database service.
 */
@Injectable()
export class DBService {
  private pool: Pool;
  private closed = false;
  private sqlPath = path.join('src', 'sql');
  private testing = !!parseInt(process.env.TESTING);
  private dbURL = !this.testing
    ? process.env.DATABASE_URL
    : process.env.HEROKU_POSTGRESQL_SILVER_URL;
  private logErrors = true;
  private tables = [
    'NB_RESOURCE',
    'NB_IMAGE',
    'NB_USER',
    'NB_SESSION',
    'NB_VERIFY',
    'NB_PASSWORD_RESET',
    'NB_DEPARTMENT',
    'NB_BOOK_CONDITION',
    'NB_BOOK',
    'NB_REPORT',
    'NB_MESSAGE',
    'NB_SEARCH_SORT',
    'NB_FEEDBACK',
    'NB_USER_INTEREST',
    'NB_REFERRAL',
    'NB_BLOCK',
  ];
 
  constructor(
    @Inject(forwardRef(() => ResourceService))
    private readonly resourceService: ResourceService,
    @Inject(forwardRef(() => UserService))
    private readonly userService: UserService,
    @Inject(forwardRef(() => VerifyService))
    private readonly verifyService: VerifyService,
    @Inject(forwardRef(() => PasswordResetService))
    private readonly passwordResetService: PasswordResetService,
  ) {
    this.pool = new Pool({
      connectionString: this.dbURL,
      ssl: { rejectUnauthorized: false },
      max: 20,
    });
 
    Iif (!this.testing) {
      this.initDB({ populateStatic: true, prune: true });
    }
  }
 
  /**
   * Provides information on an error.
   *
   * @param stmt The SQL statement.
   * @param params The query parameters.
   * @param res The query response.
   * @param err The error thrown.
   */
  private logError(stmt: string, params: any[], res: any, err: Error) {
    const msg = `\n\n######### ERROR #########\n\n\nStatement:\n${stmt}\n\nParameters:\n${params}\n\nResponse:\n${res}\n\nError:\n${err}`;
    console.error(msg);
  }
 
  /**
   * Transforms question mark query param indicators.
   *
   * @param stmt The SQL statement.
   * @returns The query with transformed parameters.
   */
  private transformParams(stmt: string): string {
    let paramCount = 0;
    while (stmt.includes('?')) {
      stmt = stmt.replace('?', `$${++paramCount}`);
    }
    return stmt;
  }
 
  /**
   * Execute a SQL query.
   *
   * @param stmt SQL statement.
   * @param params Values to be inserted into the statement.
   * @returns Query results.
   */
  public async execute<T = void>(
    stmt: string,
    params: any[] = [],
  ): Promise<T[]> {
    const conn = await this.pool.connect();
 
    stmt = this.transformParams(stmt);
 
    try {
      const res = await conn.query(stmt, params);
      conn.release();
      return res.rows;
    } catch (err) {
      if (this.logErrors) {
        this.logError(stmt, params, undefined, err);
      }
      conn.release();
      throw err;
    }
  }
 
  /**
   * Execute multiple SQL queries, each one right after the last
   *
   * @param stmts SQL statement.
   * @param params Values to be inserted into the statement.
   * @returns Results of all queries.
   */
  public async executeMany<T = void>(
    stmts: string[],
    params: any[][] = [],
  ): Promise<T[][]> {
    const conn = await this.pool.connect();
    const res: T[][] = [];
 
    stmts = stmts.map((stmt) => this.transformParams(stmt));
 
    for (let i = 0; i < stmts.length; i++) {
      try {
        const results = await conn.query(stmts[i], params[i] || []);
        res.push(results.rows);
      } catch (err) {
        if (this.logErrors) {
          this.logError(stmts[i], params[i], undefined, err);
        }
        conn.release();
        throw err;
      }
    }
 
    return res;
  }
 
  /**
   * Execute a SQL file.
   *
   * @param filename The SQL file to execute.
   * @param params Values to be inserted into the statement.
   * @param sqlPath The SQL files path.
   * @returns Query results.
   */
  public async executeFile<T = void>(
    filename: string,
    params: any[] = [],
    sqlPath: string = null,
  ): Promise<T[]> {
    sqlPath = sqlPath || this.sqlPath;
    const filepath = sqlPath ? path.join(sqlPath, filename) : filename;
    const sql = await fs.promises.readFile(filepath);
    const stmt = this.transformParams(sql.toString());
    const res = await this.execute<T>(stmt, params);
    return res;
  }
 
  /**
   * Execute multiple SQL files.
   *
   * @param filenames The SQL files to execute.
   * @param params Values to be inserted into the statement.
   * @param sqlPath The SQL files path.
   * @returns Results of all queries.
   */
  public async executeFiles<T = void>(
    filenames: string[],
    params: any[][] = [],
    sqlPath: string = null,
  ): Promise<T[][]> {
    const res: T[][] = [];
 
    for (let i = 0; i < filenames.length; i++) {
      sqlPath = sqlPath || this.sqlPath;
      const filepath = sqlPath
        ? path.join(sqlPath, filenames[i])
        : filenames[i];
      const sql = await fs.promises.readFile(filepath);
      const stmt = this.transformParams(sql.toString());
      const results = await this.execute<T>(stmt, params[i] || []);
      res.push(results);
    }
 
    return res;
  }
 
  /**
   * Execute all SQL files in a directory.
   *
   * @param directory The directory containing SQL files.
   * @param ext The extension of the SQL files.
   * @param sqlPath The SQL files path.
   * @returns Results of all queries.
   */
  public async executeAllFiles<T = void>(
    directory: string,
    ext = '.sql',
    sqlPath: string = null,
  ): Promise<T[][]> {
    sqlPath = sqlPath || this.sqlPath;
    const dirpath = sqlPath ? path.join(sqlPath, directory) : directory;
    const filenames = (await fs.promises.readdir(dirpath)).filter((filename) =>
      filename.endsWith(ext),
    );
    return this.executeFiles(filenames, [], dirpath);
  }
 
  /**
   * Close the connection to the database.
   */
  public async close(): Promise<void> {
    if (!this.closed) {
      await this.pool.end();
      this.closed = true;
    }
  }
 
  /**
   * Populates a database table.
   *
   * @param tableName The table to populate.
   * @param values Values to be inserted into the table.
   */
  private async populateTable<T>(
    tableName: string,
    values: T[],
  ): Promise<void> {
    const rows = await this.execute<any>(`SELECT * FROM "${tableName}";`);
 
    if (rows.length === 0) {
      const columns = Object.keys(values[0])
        .map((columnName) => `"${columnName}"`)
        .join(', ');
      const queryValues = values
        .map(
          (row) =>
            `(${Object.values(row)
              .map((value) => `'${value}'`)
              .join(', ')})`,
        )
        .join(', ');
 
      const sql = `INSERT INTO "${tableName}" (${columns}) VALUES ${queryValues};`;
      await this.execute(sql);
    }
  }
 
  /**
   * Populates a static database table from a CSV file.
   *
   * @param tableName The table to populate.
   */
  private async populateStaticTable(tableName: string): Promise<void> {
    const rows = await this.execute<any>(`SELECT * FROM "${tableName}";`);
 
    if (rows.length === 0) {
      const data = await fs.promises.readFile(
        path.join('src', 'sql', 'tables', `${tableName}.csv`),
      );
      const parser = csv.parse(data, { columns: true });
 
      for await (const row of parser) {
        const keys = Object.keys(row)
          .map((key) => `"${key}"`)
          .join(', ');
        const values = Object.values(row)
          .map(() => '?')
          .join(', ');
 
        const sql = `INSERT INTO "${tableName}" (${keys}) VALUES (${values});`;
        const params = Object.values(row);
        await this.execute(sql, params);
      }
    }
  }
 
  /**
   * Get a static table's values.
   *
   * @param tableName The table name.
   * @returns The table values.
   */
  public async getStaticTable(tableName: string): Promise<any[]> {
    const data = await fs.promises.readFile(
      path.join('src', 'sql', 'tables', `${tableName}.csv`),
    );
    const parser = csv.parse(data, { columns: true });
    const table = [];
 
    for await (const row of parser) {
      table.push(row);
    }
 
    return table;
  }
 
  /**
   * Prune records from the database.
   */
  private async pruneRecords(): Promise<void> {
    await this.userService.pruneUnverifiedUsers();
    await this.verifyService.pruneVerifications();
    await this.passwordResetService.prunePasswordResets();
  }
 
  /**
   * Initialize the database.
   */
  public async initDB(options: InitDBOptions = {}): Promise<void> {
    await this.executeFiles(this.tables.map((table) => `init/${table}.sql`));
 
    if (options.populateStatic ?? true) {
      await this.populateStaticTable('NB_RESOURCE');
      await this.populateStaticTable('NB_DEPARTMENT');
      await this.populateStaticTable('NB_BOOK_CONDITION');
      await this.populateStaticTable('NB_SEARCH_SORT');
    }
 
    if (options.prune ?? true) {
      const pruneInterval = await this.resourceService.getResource<number>(
        'PRUNE_INTERVAL',
      );
 
      await this.pruneRecords();
      setInterval(async () => {
        await this.pruneRecords();
      }, pruneInterval * 1000);
    }
  }
 
  /**
   * Wipe the test database.
   */
  public async wipeTestDB(): Promise<void> {
    const testPool = new Pool({
      connectionString: process.env.HEROKU_POSTGRESQL_SILVER_URL,
      ssl: { rejectUnauthorized: false },
      max: 20,
    });
 
    const tablesReversed = [].concat(this.tables).reverse();
 
    for (const table of tablesReversed) {
      await testPool.query(`DROP TABLE IF EXISTS "${table}";`);
    }
 
    await testPool.end();
  }
 
  /**
   * Create a new record in the table.
   *
   * @param fields Field values to create in the new record.
   * @returns The new record.
   */
  public async create<T>(tableName: string, fields: FieldMap): Promise<T> {
    const sql = `
      INSERT INTO "${tableName}" (
        ${Object.keys(fields)
          .map((fieldName) => `"${fieldName}"`)
          .join(', ')}
      ) VALUES (
        ${Object.values(fields).map(() => '?')}
      ) RETURNING *;`;
    const params = Object.values(fields);
 
    const res = await this.execute<T>(sql, params);
    return res[0];
  }
 
  /**
   * Get a record in the table by ID.
   *
   * @param id The record's ID.
   * @returns The record with the given ID.
   */
  public async getByID<T>(tableName: string, id: any): Promise<T> {
    const sql = `SELECT * FROM "${tableName}" WHERE "id" = ?;`;
    const params = [id];
 
    const res = await this.execute<T>(sql, params);
    return res[0];
  }
 
  /**
   * Get a record by field values.
   *
   * @param fields Fields to query by.
   * @returns The first record matching the field values.
   */
  public async getByFields<T>(tableName: string, fields: FieldMap): Promise<T> {
    const sql = `
      SELECT * FROM "${tableName}" WHERE
      ${Object.keys(fields)
        .map((fieldName) => `"${fieldName}" = ?`)
        .join(' AND ')};`;
    const params = Object.values(fields);
 
    const res = await this.execute<T>(sql, params);
    return res[0];
  }
 
  /**
   * Get a record using a custom where clause.
   *
   * @param whereClause The where clause to use in the SQL query.
   * @param params The query parameters.
   * @returns The first record from the resulting set.
   */
  public async getCustom<T>(
    tableName: string,
    whereClause: string,
    params: any[] = [],
  ): Promise<T> {
    const sql = `SELECT * FROM "${tableName}" WHERE ${whereClause};`;
 
    const res = await this.execute<T>(sql, params);
    return res[0];
  }
 
  /**
   * List all records in the table.
   *
   * @param orderOptions Options for ordering the results.
   * @returns All records, ordered if applicable.
   */
  public async list<T>(
    tableName: string,
    orderOptions?: OrderOptions,
  ): Promise<T[]> {
    const orderClause = orderOptions
      ? ` ORDER BY "${orderOptions.fieldName}" ${orderOptions.sortOrder}`
      : '';
    const sql = `SELECT * FROM "${tableName}"${orderClause};`;
 
    const res = await this.execute<T>(sql);
    return res;
  }
 
  /**
   * List all records matching provided query values.
   *
   * @param fields Fields to query by.
   * @param orderOptions Options for ordering the results.
   * @returns All records matching the provided query values, ordered if applicable.
   */
  public async listByFields<T>(
    tableName: string,
    fields: FieldMap,
    orderOptions?: OrderOptions,
  ): Promise<T[]> {
    const orderClause = orderOptions
      ? ` ORDER BY "${orderOptions.fieldName}" ${orderOptions.sortOrder}`
      : '';
    const sql = `
      SELECT * FROM "${tableName}" WHERE
      ${Object.keys(fields)
        .map((fieldName) => `"${fieldName}" = ?`)
        .join(' AND ')}
      ${orderClause};`;
    const params = Object.values(fields);
 
    const res = await this.execute<T>(sql, params);
    return res;
  }
 
  /**
   * List all records using a custom where clause.
   *
   * @param whereClause The where clause to use in the SQL query.
   * @param orderOptions Options for ordering the results.
   * @param params The query parameters.
   * @returns All records from the resulting set.
   */
  public async listCustom<T>(
    tableName: string,
    whereClause: string,
    orderOptions?: OrderOptions,
    params: any[] = [],
  ): Promise<T[]> {
    const orderClause = orderOptions
      ? ` ORDER BY "${orderOptions.fieldName}" ${orderOptions.sortOrder}`
      : '';
    const sql = `SELECT * FROM "${tableName}" WHERE ${whereClause}${orderClause};`;
 
    const res = await this.execute<T>(sql, params);
    return res;
  }
 
  /**
   * Update a record in the table by ID.
   *
   * @param id The record's ID.
   * @param fieldValues The updated field values.
   * @returns The updated record.
   */
  public async updateByID<T>(
    tableName: string,
    id: any,
    fieldValues: FieldMap,
  ): Promise<T> {
    const sql = `
      UPDATE "${tableName}" SET
      ${Object.keys(fieldValues)
        .map((fieldName) => `"${fieldName}" = ?`)
        .join(', ')}
      WHERE "id" = ?
      RETURNING *;`;
    const params = [...Object.values(fieldValues), id];
 
    const res = await this.execute<T>(sql, params);
    return res[0];
  }
 
  /**
   * Update records matching provided query values.
   *
   * @param fields Fields to query by.
   * @param fieldValues The updated field values.
   * @returns The updated records.
   */
  public async updateByFields<T>(
    tableName: string,
    fields: FieldMap,
    fieldValues: FieldMap,
  ): Promise<T[]> {
    const sql = `
      UPDATE "${tableName}" SET
      ${Object.keys(fieldValues)
        .map((fieldName) => `"${fieldName}" = ?`)
        .join(', ')}
      WHERE
      ${Object.keys(fields)
        .map((fieldName) => `"${fieldName}" = ?`)
        .join(' AND ')}
      RETURNING *;`;
    const params = [...Object.values(fieldValues), ...Object.values(fields)];
 
    const res = await this.execute<T>(sql, params);
    return res;
  }
 
  /**
   * Update records using a custom where clause.
   *
   * @param whereClause The where clause to use in the SQL query.
   * @param fieldValues The updated field values.
   * @param params The query parameters.
   * @returns The updated records.
   */
  public async updateCustom<T>(
    tableName: string,
    whereClause: string,
    fieldValues: FieldMap,
    params: any[] = [],
  ): Promise<T[]> {
    const sql = `
      UPDATE "${tableName}" SET
      ${Object.keys(fieldValues)
        .map((fieldName) => `"${fieldName}" = ?`)
        .join(', ')}
      WHERE ${whereClause}
      RETURNING *;`;
    params = [...Object.values(fieldValues), ...params];
 
    const res = await this.execute<T>(sql, params);
    return res;
  }
 
  /**
   * Delete a record in the table by ID.
   *
   * @param id The record's ID.
   */
  public async deleteByID(tableName: string, id: any): Promise<void> {
    const sql = `DELETE FROM "${tableName}" WHERE "id" = ?;`;
    const params = [id];
 
    await this.execute(sql, params);
  }
 
  /**
   * Delete records matching provided query values.
   *
   * @param fields Fields to query by.
   */
  public async deleteByFields(
    tableName: string,
    fields: FieldMap,
  ): Promise<void> {
    const sql = `
      DELETE FROM "${tableName}" WHERE
      ${Object.keys(fields)
        .map((fieldName) => `"${fieldName}" = ?`)
        .join(' AND ')};`;
    const params = Object.values(fields);
 
    await this.execute(sql, params);
  }
 
  /**
   * Delete records using a custom where clause.
   *
   * @param whereClause The where clause to use in the SQL query.
   * @param params The query parameters.
   */
  public async deleteCustom(
    tableName: string,
    whereClause: string,
    params: any[] = [],
  ): Promise<void> {
    const sql = `DELETE FROM "${tableName}" WHERE ${whereClause};`;
 
    await this.execute(sql, params);
  }
}