All files / src/services/db price.db.ts

56.16% Statements 41/73
100% Branches 6/6
50% Functions 1/2
57.81% Lines 37/64

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 642x 2x 2x 2x 2x 2x 2x 2x   24x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 11x 2x 2x 2x 10x 2x 2x                           10x 10x 9x       9x   1x                  
// src/services/db/price.db.ts
import type { Logger } from 'pino';
import type { PriceHistoryData } from '../../types';
import { getPool } from './connection.db';
import { handleDbError } from './errors.db';
 
/**
 * Repository for fetching price-related data.
 */
export const priceRepo = {
  /**
   * Fetches the historical price data for a given list of master item IDs.
   * It retrieves the price in cents and the start date of the flyer for each item.
   *
   * @param masterItemIds An array of master grocery item IDs.
   * @param logger The pino logger instance.
   * @param limit The maximum number of records to return.
   * @param offset The number of records to skip.
   * @returns A promise that resolves to an array of price history data points.
   */
  async getPriceHistory(
    masterItemIds: number[],
    logger: Logger,
    limit: number = 1000,
    offset: number = 0,
  ): Promise<PriceHistoryData[]> {
    if (masterItemIds.length === 0) {
      return [];
    }
 
    const query = `
      SELECT
        fi.master_item_id,
        fi.price_in_cents,
        f.valid_from AS date
      FROM public.flyer_items fi
      JOIN public.flyers f ON fi.flyer_id = f.flyer_id
      WHERE
        fi.master_item_id = ANY($1::int[])
        AND f.valid_from IS NOT NULL
        AND fi.price_in_cents IS NOT NULL
      ORDER BY
        fi.master_item_id, f.valid_from ASC
      LIMIT $2 OFFSET $3;
    `;

    try {
      const result = await getPool().query(query, [masterItemIds, limit, offset]);
      logger.debug(
        { count: result.rows.length, itemIds: masterItemIds.length, limit, offset },
        'Fetched price history from database.',
      );
      return result.rows;
    } catch (error) {
      handleDbError(
        error,
        logger,
        'Database error in getPriceHistory',
        { masterItemIds, limit, offset },
        { defaultMessage: 'Failed to retrieve price history.' },
      );
    }
  },
};