getsProductById should get from the cache directly...
import { Request, Response } from 'express';
import {query} from "../config/database";
import {brandsCache, productCache} from "../cache";
import {
Brand,
BrandsCacheData,
CacheData, Category, Color, CreateProductInput,
Image,
ImageInput,
Product, Size,
UpdateProductInput
} from "product";
import {addProductToCache, deleteProductFromCache, updateProductInCache} from "../cacheHelper";
const fetchCategoryDetails = async (subcategoryIds: number[]) => {
const categoriesResult = await query(
SELECT sc.id AS subcategory_id, sc.name AS subcategory_name, c.id AS main_category_id, c.name AS main_category_name FROM subcategories sc JOIN categories c ON sc.category_id = c.id WHERE sc.id = ANY($1::int[]),
[subcategoryIds]
);
};
export const loadAndCacheAllProducts = async (): Promise => {
const q = SELECT p.id, p.name, p.description, p.brand_id, p.has_color, p.has_size, p.product_type, p.price, p.qty, p.sold, p.created_at, p.updated_at, sc.id AS subcategory_id, sc.name AS subcategory_name, c.id AS main_category_id, c.name AS main_category_name, s.id AS size_id, s.name AS size_name, s.price AS size_price, s.qty AS size_qty, s.sold AS size_sold, cl.id AS color_id, cl.name AS color_name, cl.price AS color_price, cl.qty AS color_qty, cl.sold AS color_sold, i.id AS image_id, i.url AS image_url, i.color_id AS image_color_id, i.size_id AS image_size_id FROM products p LEFT JOIN product_categories pc ON p.id = pc.product_id LEFT JOIN subcategories sc ON pc.category_id = sc.id LEFT JOIN categories c ON sc.category_id = c.id LEFT JOIN colors cl ON p.id = cl.product_id LEFT JOIN sizes s ON p.id = s.product_id LEFT JOIN images i ON (p.id = i.product_id AND (cl.id = i.color_id OR i.color_id IS NULL) AND (s.id = i.size_id OR i.size_id IS NULL)) ;
try {
const result = await query(q, []);
const productsMap: Record<number, Product> = {};
// Temporary map to hold sizes that need to be assigned to colors
const sizesMap: Record<number, Size> = {};
// First pass: Initialize products and collect sizes
result.rows.forEach((row: any) => {
const productId = Number(row.id);
// Initialize the product in the map if it doesn't exist
if (!productsMap[productId]) {
productsMap[productId] = {
id: productId,
name: row.name,
description: row.description,
brand_id: Number(row.brand_id),
has_color: Boolean(row.has_color),
has_size: Boolean(row.has_size),
product_type: row.product_type,
price: Number(row.price),
qty: Number(row.qty),
sold: Number(row.sold),
created_at: new Date(row.created_at).toISOString(),
updated_at: new Date(row.updated_at).toISOString(),
categories: [],
colors: [],
sizes: [], // Will be populated only if has_color is false
images: []
};
}
const product = productsMap[productId];
// Add category if present and not already added
if (
row.subcategory_id &&
row.subcategory_name &&
row.main_category_id &&
row.main_category_name
) {
const categoryId = Number(row.subcategory_id);
const mainCategoryId = Number(row.main_category_id);
const existingCategory = product.categories.find(cat => cat.id === categoryId);
if (!existingCategory) {
product.categories.push({
id: categoryId,
name: row.subcategory_name,
main_category_id: mainCategoryId,
main_category_name: row.main_category_name,
});
}
}
// Add color if present and not already added
if (row.color_id && row.color_name && row.has_size !== undefined) {
const colorId = Number(row.color_id);
let color = product.colors.find(color => color.id === colorId);
if (!color) {
color = {
id: colorId,
name: row.color_name,
price: Number(row.color_price),
qty: Number(row.color_qty),
sold: Number(row.color_sold),
has_size: Boolean(row.has_size),
sizes: [], // Will be populated if has_size is true
images: []
};
product.colors.push(color);
}
}
// Collect sizes to assign later based on color association
if (row.size_id && row.size_name) {
const sizeId = Number(row.size_id);
const colorId = row.color_id ? Number(row.color_id) : null;
// If the size is associated with a color, store it for later assignment
if (colorId && product.has_color) {
sizesMap[sizeId] = {
id: sizeId,
name: row.size_name,
price: Number(row.size_price),
qty: Number(row.size_qty),
sold: Number(row.size_sold),
color_id: colorId,
images: []
};
} else if (!product.has_color && product.has_size) {
// If the product has sizes but no colors, assign size directly
if (!product.sizes.find(s => s.id === sizeId)) {
product.sizes.push({
id: sizeId,
name: row.size_name,
price: Number(row.size_price),
qty: Number(row.size_qty),
sold: Number(row.size_sold),
color_id: null,
images: []
});
}
}
}
// Collect images to assign
if (row.image_id && row.image_url) {
const imageId = Number(row.image_id);
// Avoid duplicate images
if (!product.images.find(img => img.id === imageId)) {
product.images.push({
id: imageId,
url: row.image_url,
color_id: row.image_color_id ? Number(row.image_color_id) : null,
size_id: row.image_size_id ? Number(row.image_size_id) : null
});
}
// Associate image with color if applicable
if (row.image_color_id) {
const colorId = Number(row.image_color_id);
const color = product.colors.find(c => c.id === colorId);
if (color && !color.images.includes(row.image_url)) {
color.images.push(row.image_url);
}
}
// Associate image with size if applicable and size is within a color
if (row.image_size_id) {
const sizeId = Number(row.image_size_id);
const size = sizesMap[sizeId];
if (size) {
if (!size.images.includes(row.image_url)) {
size.images.push(row.image_url);
}
} else {
// If the product does not have colors, associate with product's sizes
const standaloneSize = product.sizes.find(s => s.id === Number(row.image_size_id));
if (standaloneSize && !standaloneSize.images.includes(row.image_url)) {
standaloneSize.images.push(row.image_url);
}
}
}
}
});
// Second pass: Assign sizes to their respective colors
Object.values(productsMap).forEach(product => {
if (product.has_color) {
// Initialize all product.sizes as empty
product.sizes = [];
// Iterate over collected sizes and assign to colors
Object.values(sizesMap).forEach(size => {
if (size.color_id === null) return; // Skip sizes without color_id
const color = product.colors.find(c => c.id === size.color_id);
if (color) {
color.sizes.push({
id: size.id,
name: size.name,
price: size.price,
qty: size.qty,
sold: size.sold,
color_id: size.color_id,
images: size.images
});
}
});
// Update has_size for each color based on whether it has sizes
product.colors.forEach(color => {
color.has_size = color.sizes.length > 0;
});
}
// If has_color is false, sizes are already assigned directly to product.sizes
});
const allProducts = Object.values(productsMap);
// Calculate min and max prices across all products
let minPrice = Infinity;
let maxPrice = -Infinity;
allProducts.forEach(product => {
// Product price
if (product.price < minPrice) minPrice = product.price;
if (product.price > maxPrice) maxPrice = product.price;
// Prices from colors and their sizes
product.colors.forEach(color => {
if (color.price < minPrice) minPrice = color.price;
if (color.price > maxPrice) maxPrice = color.price;
color.sizes.forEach(size => {
if (size.price < minPrice) minPrice = size.price;
if (size.price > maxPrice) maxPrice = size.price;
});
});
// Prices from standalone sizes
product.sizes.forEach(size => {
if (size.price < minPrice) minPrice = size.price;
if (size.price > maxPrice) maxPrice = size.price;
});
});
// Fallback in case no prices are present
if (minPrice === Infinity) minPrice = 0;
if (maxPrice === -Infinity) maxPrice = 0;
// Cache the data with a consistent key
const cacheData: CacheData = { allProducts, minPrice, maxPrice };
productCache.set('allProducts', cacheData);
console.log(`Cached ${allProducts.length} products with minPrice: ${minPrice} and maxPrice: ${maxPrice}.`);
return cacheData;
} catch (error) {
console.error('Error loading products from DB:', error);
throw error; // Propagate error to be handled by caller
}
Assistant
};
/**
Fetches all brands from the database and caches them.
@returns {Promise} A promise that resolves to the cached brand data.
*/
const loadAndCacheAllBrands = async (): Promise => {
const q = SELECT s.*, c.name as category_name FROM subcategories s JOIN categories c ON s.category_id = c.id AND c.is_brand ORDER BY c.name, s.name ;
if (!cacheData) {
// Cache : Load from DB and cache
cacheData = await loadAndCacheAllProducts();
console.log('Loaded products from database and cached them.');
} else {
console.log('Loaded products from cache.');
}
const { allProducts, minPrice, maxPrice } = cacheData;
// Log total products before any filtering
console.log(`Total products before filtering: ${allProducts.length}`);
// Extract and sanitize query parameters
let {
search = '',
c,
sc,
b,
minPriceA = '0',
maxPriceA = '',
availability = 'all',
sortBy = '',
page = '1',
itemsPerPage = '15',
} = req.query;
// Parse numerical values
const pageNum = parseInt(page as string, 10) || 1;
const itemsPerPageNum = parseInt(itemsPerPage as string, 10) || 15;
const minPriceANum = parseFloat(minPriceA as string) || 0;
let maxPriceANum = maxPriceA ? parseFloat(maxPriceA as string) : Infinity;
// If maxPriceA is less than minPriceA, reset to Infinity
if (!isNaN(maxPriceANum) && maxPriceANum < minPriceANum) {
console.warn('Provided maxPriceA is less than minPriceA. Resetting maxPriceANum to Infinity.');
maxPriceANum = Infinity;
} else if (isNaN(maxPriceANum)) {
maxPriceANum = Infinity;
}
// Parse c, sc, b as numbers if present
const cNum = c ? parseInt(c as string, 10) : undefined;
const scNum = sc ? parseInt(sc as string, 10) : undefined;
const bNum = b ? parseInt(b as string, 10) : undefined;
// Initialize brand-related variables if 'b' is provided
let allBrands: Brand[] = [];
if (bNum !== undefined && !isNaN(bNum)) {
// Retrieve cached brands
let brandsCacheData: BrandsCacheData | undefined = brandsCache.get('allBrands');
if (!brandsCacheData) {
// Cache miss: Load from DB and cache
brandsCacheData = await loadAndCacheAllBrands();
console.log('Loaded brands from database and cached them.');
} else {
console.log('Loaded brands from cache.');
}
console.log(brandsCacheData)
allBrands = brandsCacheData.allBrands;
// Check if 'bNum' is a valid brand ID
const isValidBrand = allBrands.some(brand => brand.category_id === bNum);
if (!isValidBrand) {
console.warn(`Brand ID ${bNum} is invalid.`);
// Return zero products since 'b' is invalid
res.json({
products: [],
total: 0,
page: pageNum,
itemsPerPage: itemsPerPageNum,
totalPages: 0,
hasMore: false,
minPrice,
maxPrice,
});
return;
}
}
// Start with all products
let filteredProducts = [...allProducts];
// Apply Search Filter
if (search && typeof search === 'string') {
const searchLower = search.toLowerCase();
const searchWords = searchLower.split(/\s+/).filter(Boolean);
filteredProducts = filteredProducts.filter(product =>
searchWords.every(word => product.name.toLowerCase().includes(word))
);
}
// Apply Category Filter (c)
if (cNum !== undefined && !isNaN(cNum)) {
filteredProducts = filteredProducts.filter(product =>
product.categories.some(cat => cat.main_category_id === cNum)
);
}
// Apply Subcategory Filter (sc)
if (scNum !== undefined && !isNaN(scNum)) {
filteredProducts = filteredProducts.filter(product =>
product.brand_id === scNum ||
product.categories.some(cat => cat.id === scNum)
);
}
// Apply Brand Filter (b)
if (bNum !== undefined && !isNaN(bNum)) {
console.log(`Applying Brand Filter: brand_id === ${bNum}`);
const preFilterCount = filteredProducts.length;
allBrands = allBrands.filter(brand => brand.category_id === bNum)
filteredProducts = filteredProducts.filter(product =>
allBrands.some(brand => brand.id === product.brand_id)
);
console.log(`Filtered from ${preFilterCount} to ${filteredProducts.length} products after applying brand filter.`);
}
// Apply Price Range Filter
if (minPriceANum > 0 || maxPriceANum < Infinity) {
filteredProducts = filteredProducts.filter(product => {
const productPrices = product.sizes.map(size => size.price);
if (productPrices.length === 0) return false;
const productMinPrice = Math.min(...productPrices);
const productMaxPrice = Math.max(...productPrices);
return productMinPrice >= minPriceANum && productMaxPrice <= maxPriceANum;
});
}
// Apply Availability Filter
if (availability === 'in_stock') {
filteredProducts = filteredProducts.filter(product =>
product.sizes.some(size => size.qty > 0)
);
} else if (availability === 'out_of_stock') {
filteredProducts = filteredProducts.filter(product =>
product.sizes.every(size => size.qty === 0)
);
}
// Log total after filtering
console.log(`Total products after filtering: ${filteredProducts.length}`);
// Apply Sorting
if (sortBy && typeof sortBy === 'string') {
switch (sortBy) {
case 'Price: Low to High':
filteredProducts.sort((a, b) => {
const aMin = Math.min(...a.sizes.map(s => s.price));
const bMin = Math.min(...b.sizes.map(s => s.price));
return aMin - bMin;
});
break;
case 'Price: High to Low':
filteredProducts.sort((a, b) => {
const aMax = Math.max(...a.sizes.map(s => s.price));
const bMax = Math.max(...b.sizes.map(s => s.price));
return bMax - aMax;
});
break;
case 'Name: A to Z':
filteredProducts.sort((a, b) => a.name.localeCompare(b.name));
break;
case 'Name: Z to A':
filteredProducts.sort((a, b) => b.name.localeCompare(a.name));
break;
case 'Best Selling':
filteredProducts.sort((a, b) => b.sold - a.sold);
break;
case 'Newest Arrivals':
filteredProducts.sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());
break;
default:
// If sortBy parameter doesn't match any case, do not sort
break;
}
}
// Apply Pagination
const totalFilteredProducts = filteredProducts.length;
const totalPages = Math.ceil(totalFilteredProducts / itemsPerPageNum);
const startIdx = (pageNum - 1) * itemsPerPageNum;
const endIdx = startIdx + itemsPerPageNum;
const paginatedProducts = filteredProducts.slice(startIdx, endIdx);
// Construct Response
const response = {
products: paginatedProducts,
total: totalFilteredProducts,
page: pageNum,
itemsPerPage: itemsPerPageNum,
totalPages,
hasMore: endIdx < totalFilteredProducts,
minPrice, // Global minPrice across all products
maxPrice, // Global maxPrice across all products
};
// Send Response
res.json(response);
} catch (error) {
console.error('Error fetching products:', error);
res.status(500).json({ error: 'Internal server error' });
} finally {
// Optional: Any cleanup operations can be performed here
// For example, monitoring memory usage or logging request completion
}
};
export const getProductById = async (req: Request, res: Response) => {
const { id } = req.params;
try {
const productQuery = SELECT p.id AS product_id, p.name AS product_name, p.description, p.brand_id, p.has_color, p.has_size, p.product_type, p.price AS product_price, p.qty AS product_qty, p.sold AS product_sold, p.created_at, p.updated_at, pc.category_id, sc.name AS category_name, cl.id AS color_id, cl.name AS color_name, cl.price AS color_price, cl.qty AS color_qty, cl.sold AS color_sold, s.id AS size_id, s.name AS size_name, s.price AS size_price, s.qty AS size_qty, s.sold AS size_sold, i.id AS image_id, i.url AS image_url FROM products p LEFT JOIN product_categories pc ON p.id = pc.product_id LEFT JOIN subcategories sc ON pc.category_id = sc.id LEFT JOIN colors cl ON p.id = cl.product_id LEFT JOIN sizes s ON (p.id = s.product_id AND (cl.id = s.color_id OR s.color_id IS NULL)) LEFT JOIN images i ON (p.id = i.product_id AND (cl.id = i.color_id OR i.color_id IS NULL) AND (s.id = i.size_id OR i.size_id IS NULL)) WHERE p.id = $1 ORDER BY pc.category_id, cl.id, s.id, i.id ;
const result = await query(productQuery, [id]);
if (result.rows.length === 0) {
return res.status(404).json({ error: 'Product not found' });
}
// Process the result to group related data
let product: {
sold: any;
has_size: any;
images: any[];
description: any;
created_at: any;
colors: any[];
brand_id: any;
has_color: any;
product_type: any;
updated_at: any;
sizes: any[];
price: any;
qty: any;
name: any;
id: number;
categories: any[]
};
product = {
id: result.rows[0].product_id,
name: result.rows[0].product_name,
description: result.rows[0].description,
brand_id: result.rows[0].brand_id,
has_color: result.rows[0].has_color,
has_size: result.rows[0].has_size,
product_type: result.rows[0].product_type,
price: result.rows[0].product_price,
qty: result.rows[0].product_qty,
sold: result.rows[0].product_sold,
created_at: result.rows[0].created_at,
updated_at: result.rows[0].updated_at,
categories: [],
colors: [],
sizes: [],
images: []
};
for (const row of result.rows) {
if (row.category_id && !product.categories.some(c => c.id === row.category_id)) {
product.categories.push({
id: row.category_id,
name: row.category_name
});
}
// Add color if not already added
if (row.color_id && !product.colors.some(c => c.id === row.color_id)) {
product.colors.push({
id: row.color_id,
name: row.color_name,
price: row.color_price,
qty: row.color_qty,
sold: row.color_sold,
images: [],
sizes: []
});
}
// Add size if not already added
if (row.size_id && !product.sizes.some(s => s.id === row.size_id)) {
const newSize = {
id: row.size_id,
name: row.size_name,
price: row.size_price,
qty: row.size_qty,
sold: row.size_sold,
color_id: row.color_id,
// @ts-ignore
images: []
};
product.sizes.push(newSize);
// Add size to the corresponding color
if (row.color_id) {
const color = product.colors.find(c => c.id === row.color_id);
if (color && !color.sizes.some((s: { id: any; }) => s.id === row.size_id)) {
color.sizes.push(newSize);
}
}
}
if (row.image_id && !product.images.some(i => i.id === row.image_id)) {
const newImage = {
id: row.image_id,
url: row.image_url,
color_id: row.color_id,
size_id: row.size_id
};
product.images.push(newImage);
if (row.color_id) {
const color = product.colors.find(c => c.id === row.color_id);
if (color && !color.images.includes(row.image_url)) {
color.images.push(row.image_url);
}
}
if (row.size_id) {
const size = product.sizes.find(s => s.id === row.size_id);
if (size && !size.images.includes(row.image_url)) {
size.images.push(row.image_url);
}
}
}
}
res.json({ product });
} catch (error) {
console.error('Error fetching product by ID:', error);
res.status(500).json({ error: 'Internal server error' });
}
if (isNaN(productId)) {
return res.status(400).json({ error: 'Invalid product ID' });
}
try {
await query('BEGIN');
// Delete related data first
await query('DELETE FROM product_categories WHERE product_id = $1', [productId]);
await query('DELETE FROM images WHERE product_id = $1', [productId]);
await query('DELETE FROM sizes WHERE product_id = $1', [productId]);
await query('DELETE FROM colors WHERE product_id = $1', [productId]);
// Delete the product
const result = await query('DELETE FROM products WHERE id = $1 RETURNING *', [productId]);
if (result.rows.length === 0) {
await query('ROLLBACK');
return res.status(404).json({ error: 'Product not found' });
}
// Delete the product from the cache
deleteProductFromCache(productId);
await query('COMMIT');
res.json({ message: 'Product and related data deleted successfully' });
} catch (error) {
await query('ROLLBACK');
console.error('Error deleting product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
cacheHelper.ts:
// src/cacheHelper.ts
import { productCache } from "./cache";
import { Product, CacheData, Color, Size } from "product"; // Adjust the import path as necessary
/**
Adds a new product to the cache.
*/
export const addProductToCache = (newProduct: Product) => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (cacheData) {
cacheData.allProducts.push(newProduct);
// Extract all prices from the new product
const productPrices: number[] = [newProduct.price];
newProduct.colors.forEach((color: Color) => {
productPrices.push(color.price);
color.sizes.forEach((size: Size) => productPrices.push(size.price));
});
newProduct.sizes.forEach((size: Size) => productPrices.push(size.price));
// Update minPrice and maxPrice
if (productPrices.length > 0) {
cacheData.minPrice = Math.min(cacheData.minPrice, ...productPrices);
cacheData.maxPrice = Math.max(cacheData.maxPrice, ...productPrices);
}
productCache.set('allProducts', cacheData);
console.log('Added new product to cache.');
} else {
// Flush cache to force reload on next access
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache.');
}
Decreases product, size, or color quantity in the cache based on identifiers.
@param productId - ID of the product
@param sizeId - ID of the size (optional)
@param colorId - ID of the color (optional)
@param quantity - Quantity to decrease
*/
export const decreaseProductQtyInCache = (productId: number, sizeId: number | null, colorId: number | null, quantity: number): void => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (!cacheData) {
// Cache is unavailable; nothing to update
return;
}
const product = cacheData.allProducts.find(p => p.id === productId);
if (!product) {
// Product not found in cache; nothing to update
return;
}
if (sizeId) {
// Decrease quantity in the specific size
const size = product.sizes.find(s => s.id === sizeId);
if (size) {
size.qty = size.qty - quantity;
if (size.qty < 0) size.qty = 0; // Prevent negative stock
}
// Also, if color_id is present, update the associated color's size
if (colorId) {
const color = product.colors.find(c => c.id === colorId);
if (color) {
const colorSize = color.sizes.find(s => s.id === sizeId);
if (colorSize) {
colorSize.qty = colorSize.qty - quantity;
if (colorSize.qty < 0) colorSize.qty = 0;
}
}
}
} else if (colorId) {
// Decrease quantity in the specific color
const color = product.colors.find(c => c.id === colorId);
if (color) {
color.qty = color.qty - quantity;
if (color.qty < 0) color.qty = 0; // Prevent negative stock
}
} else {
// Decrease quantity in the product itself
product.qty = product.qty - quantity;
if (product.qty < 0) product.qty = 0; // Prevent negative stock
}
// Update the cache
productCache.set('allProducts', cacheData);
console.log('Decreased product quantity in cache.');
} catch (error) {
console.error('Error decreasing product quantity in cache:', error);
// Decide whether to flush the cache or handle the error differently
productCache.del('allProducts');
}
};
/**
Increases product, size, or color quantity in the cache based on identifiers.
@param productId - ID of the product
@param sizeId - ID of the size (optional)
@param colorId - ID of the color (optional)
@param quantity - Quantity to increase
*/
export const increaseProductQtyInCache = (productId: number, sizeId: number | null, colorId: number | null, quantity: number): void => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (!cacheData) {
// Cache is unavailable; nothing to update
return;
}
const product = cacheData.allProducts.find(p => p.id === productId);
if (!product) {
// Product not found in cache; nothing to update
return;
}
if (sizeId) {
// Increase quantity in the specific size
const size = product.sizes.find(s => s.id === sizeId);
if (size) {
size.qty += quantity;
}
// Also, if color_id is present, update the associated color's size
if (colorId) {
const color = product.colors.find(c => c.id === colorId);
if (color) {
const colorSize = color.sizes.find(s => s.id === sizeId);
if (colorSize) {
colorSize.qty += quantity;
}
}
}
} else if (colorId) {
// Increase quantity in the specific color
const color = product.colors.find(c => c.id === colorId);
if (color) {
color.qty += quantity;
}
} else {
// Increase quantity in the product itself
product.qty += quantity;
}
// Update the cache
productCache.set('allProducts', cacheData);
console.log('Increased product quantity in cache.');
} catch (error) {
console.error('Error increasing product quantity in cache:', error);
// Decide whether to flush the cache or handle the error differently
productCache.del('allProducts');
}
};
/**
Decreases the 'sold' count for a size in the cache.
*/
export const decreaseSizeSoldInCache = (productId: number, sizeId: number, quantity: number): void => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (!cacheData) {
// Cache is unavailable; nothing to update
return;
}
const product = cacheData.allProducts.find(p => p.id === productId);
if (!product) {
// Product not found in cache; nothing to update
return;
}
const size = product.sizes.find(s => s.id === sizeId);
if (size) {
size.sold -= quantity;
if (size.sold < 0) size.sold = 0; // Prevent negative sold counts
// Ensure cache is updated
productCache.set('allProducts', cacheData);
console.log(`Decreased sold count for size ID ${sizeId} in cache.`);
}
} catch (error) {
console.error('Error decreasing size sold in cache:', error);
// Optionally, decide to flush the cache or handle the error differently
productCache.del('allProducts');
}
};
/**
Decreases the 'sold' count for a color in the cache.
*/
export const decreaseColorSoldInCache = (productId: number, colorId: number, quantity: number): void => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (!cacheData) {
// Cache is unavailable; nothing to update
return;
}
const product = cacheData.allProducts.find(p => p.id === productId);
if (!product) {
// Product not found in cache; nothing to update
return;
}
const color = product.colors.find(c => c.id === colorId);
if (color) {
color.sold -= quantity;
if (color.sold < 0) color.sold = 0; // Prevent negative sold counts
// Ensure cache is updated
productCache.set('allProducts', cacheData);
console.log(`Decreased sold count for color ID ${colorId} in cache.`);
}
} catch (error) {
console.error('Error decreasing color sold in cache:', error);
// Optionally, decide to flush the cache or handle the error differently
productCache.del('allProducts');
}
};
/**
Decreases the 'sold' count for a product in the cache.
*/
export const decreaseProductSoldInCache = (productId: number, quantity: number): void => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (!cacheData) {
// Cache is unavailable; nothing to update
return;
}
const product = cacheData.allProducts.find(p => p.id === productId);
if (product) {
product.sold -= quantity;
if (product.sold < 0) product.sold = 0; // Prevent negative sold counts
// Ensure cache is updated
productCache.set('allProducts', cacheData);
console.log(`Decreased sold count for product ID ${productId} in cache.`);
}
} catch (error) {
console.error('Error decreasing product sold in cache:', error);
// Optionally, decide to flush the cache or handle the error differently
productCache.del('allProducts');
}
};
/**
Increases the 'sold' count for a size in the cache.
*/
export const increaseSizeSoldInCache = (productId: number, sizeId: number, quantity: number): void => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (!cacheData) {
// Cache is unavailable; nothing to update
return;
}
const product = cacheData.allProducts.find(p => p.id === productId);
if (!product) {
// Product not found in cache; nothing to update
return;
}
const size = product.sizes.find(s => s.id === sizeId);
if (size) {
size.sold += quantity;
// Ensure cache is updated
productCache.set('allProducts', cacheData);
console.log(`Increased sold count for size ID ${sizeId} in cache.`);
}
} catch (error) {
console.error('Error increasing size sold in cache:', error);
// Optionally, decide to flush the cache or handle the error differently
productCache.del('allProducts');
}
};
/**
Increases the 'sold' count for a color in the cache.
*/
export const increaseColorSoldInCache = (productId: number, colorId: number, quantity: number): void => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (!cacheData) {
// Cache is unavailable; nothing to update
return;
}
const product = cacheData.allProducts.find(p => p.id === productId);
if (!product) {
// Product not found in cache; nothing to update
return;
}
const color = product.colors.find(c => c.id === colorId);
if (color) {
color.sold += quantity;
// Ensure cache is updated
productCache.set('allProducts', cacheData);
console.log(`Increased sold count for color ID ${colorId} in cache.`);
}
} catch (error) {
console.error('Error increasing color sold in cache:', error);
// Optionally, decide to flush the cache or handle the error differently
productCache.del('allProducts');
}
};
/**
Increases the 'sold' count for a product in the cache.
*/
export const increaseProductSoldInCache = (productId: number, quantity: number): void => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (!cacheData) {
// Cache is unavailable; nothing to update
return;
}
const product = cacheData.allProducts.find(p => p.id === productId);
if (product) {
product.sold += quantity;
// Ensure cache is updated
productCache.set('allProducts', cacheData);
console.log(`Increased sold count for product ID ${productId} in cache.`);
}
} catch (error) {
console.error('Error increasing product sold in cache:', error);
// Optionally, decide to flush the cache or handle the error differently
productCache.del('allProducts');
}
};
Certainly! Improving the getProductById function to leverage caching effectively can significantly enhance the performance of your application by reducing redundant database queries. Below, I'll guide you through modifying the getProductById controller to fetch product data directly from the cache when available. Additionally, I'll provide recommendations to optimize your caching strategy further.
Overview
Current Scenario:
The getProductById function currently fetches product data directly from the database.
The application already caches all products using the loadAndCacheAllProducts function under the key 'allProducts' in productCache.
Proposed Improvement:
Modify getProductById to first attempt retrieving the requested product from the cached 'allProducts'.
If the product is found in the cache, return it directly without querying the database.
If the cache is missing or the product isn't found, fallback to querying the database, then update the cache accordingly.
Further Optimization (Optional but Recommended):
Implement per-product caching by storing individual products with keys like 'product_{id}'. This approach can make fetching individual products more efficient, especially as the number of products grows.
Step-by-Step Implementation
1. Modify getProductById to Use the Cache
Let's update the getProductById function to first check the cache before querying the database.
// Import necessary modules and types
import { Request, Response } from 'express';
import { query } from "../config/database";
import { productCache } from "../cache";
import { Product } from "product"; // Adjust the import path as necessary
export const getProductById = async (req: Request, res: Response) => {
const { id } = req.params;
const productId = parseInt(id, 10);
if (isNaN(productId)) {
return res.status(400).json({ error: 'Invalid product ID' });
}
try {
// Attempt to retrieve the cached products
let cacheData = productCache.get('allProducts') as CacheData | undefined;
if (cacheData) {
console.log('Loaded products from cache.');
} else {
// Cache miss: Load all products and cache them
cacheData = await loadAndCacheAllProducts();
console.log('Loaded products from database and cached them.');
}
// Find the product in the cached data
const cachedProduct = cacheData.allProducts.find(product => product.id === productId);
if (cachedProduct) {
console.log(`Product ID ${productId} found in cache.`);
return res.json({ product: cachedProduct });
} else {
console.log(`Product ID ${productId} not found in cache. Fetching from database.`);
// Fallback: Fetch the product from the database
const productFromDb = await fetchProductByIdFromDb(productId);
if (productFromDb) {
// Add the fetched product to the cache
addProductToCache(productFromDb);
return res.json({ product: productFromDb });
} else {
// Product not found in the database
return res.status(404).json({ error: 'Product not found' });
}
}
} catch (error) {
console.error('Error fetching product by ID:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
/**
* Fetches a single product by ID directly from the database.
* @param productId - ID of the product to fetch.
* @returns {Promise<Product | null>} The product if found, else null.
*/
const fetchProductByIdFromDb = async (productId: number): Promise<Product | null> => {
const productQuery = `
SELECT
p.id,
p.name,
p.description,
p.brand_id,
p.has_color,
p.has_size,
p.product_type,
p.price,
p.qty,
p.sold,
p.created_at,
p.updated_at,
sc.id AS subcategory_id,
sc.name AS subcategory_name,
c.id AS main_category_id,
c.name AS main_category_name,
cl.id AS color_id,
cl.name AS color_name,
cl.price AS color_price,
cl.qty AS color_qty,
cl.sold AS color_sold,
s.id AS size_id,
s.name AS size_name,
s.price AS size_price,
s.qty AS size_qty,
s.sold AS size_sold,
i.id AS image_id,
i.url AS image_url
FROM products p
LEFT JOIN product_categories pc ON p.id = pc.product_id
LEFT JOIN subcategories sc ON pc.category_id = sc.id
LEFT JOIN categories c ON sc.category_id = c.id
LEFT JOIN colors cl ON p.id = cl.product_id
LEFT JOIN sizes s ON (p.id = s.product_id AND (cl.id = s.color_id OR s.color_id IS NULL))
LEFT JOIN images i ON (p.id = i.product_id AND (cl.id = i.color_id OR i.color_id IS NULL) AND (s.id = i.size_id OR i.size_id IS NULL))
WHERE p.id = $1
ORDER BY pc.category_id, cl.id, s.id, i.id
`;
try {
const result = await query(productQuery, [productId]);
if (result.rows.length === 0) {
return null;
}
// Process the result to construct the Product object
let product: Product = {
id: result.rows[0].id,
name: result.rows[0].name,
description: result.rows[0].description,
brand_id: result.rows[0].brand_id,
has_color: result.rows[0].has_color,
has_size: result.rows[0].has_size,
product_type: result.rows[0].product_type,
price: result.rows[0].price,
qty: result.rows[0].qty,
sold: result.rows[0].sold,
created_at: new Date(result.rows[0].created_at).toISOString(),
updated_at: new Date(result.rows[0].updated_at).toISOString(),
categories: [],
colors: [],
sizes: [],
images: []
};
// Iterate through the rows to populate categories, colors, sizes, and images
for (const row of result.rows) {
// Categories
if (row.subcategory_id && row.subcategory_name && row.main_category_id && row.main_category_name) {
const existingCategory = product.categories.find(cat => cat.id === row.subcategory_id);
if (!existingCategory) {
product.categories.push({
id: row.subcategory_id,
name: row.subcategory_name,
main_category_id: row.main_category_id,
main_category_name: row.main_category_name,
});
}
}
// Colors
if (row.color_id && row.color_name) {
let color = product.colors.find(c => c.id === row.color_id);
if (!color) {
color = {
id: row.color_id,
name: row.color_name,
price: row.color_price,
qty: row.color_qty,
sold: row.color_sold,
has_size: row.has_size,
sizes: [],
images: []
};
product.colors.push(color);
}
}
// Sizes
if (row.size_id && row.size_name) {
const size: Size = {
id: row.size_id,
name: row.size_name,
price: row.size_price,
qty: row.size_qty,
sold: row.size_sold,
color_id: row.color_id || null,
images: []
};
// Associate size with color if applicable
if (row.color_id) {
const color = product.colors.find(c => c.id === row.color_id);
if (color) {
const existingSize = color.sizes.find(s => s.id === size.id);
if (!existingSize) {
color.sizes.push(size);
}
}
} else if (product.has_size) {
const existingSize = product.sizes.find(s => s.id === size.id);
if (!existingSize) {
product.sizes.push(size);
}
}
}
// Images
if (row.image_id && row.image_url) {
const image = {
id: row.image_id,
url: row.image_url,
color_id: row.color_id || null,
size_id: row.size_id || null
};
// Avoid duplicate images
if (!product.images.some(img => img.id === image.id)) {
product.images.push(image);
}
// Associate image with color if applicable
if (row.color_id) {
const color = product.colors.find(c => c.id === row.color_id);
if (color && !color.images.includes(row.image_url)) {
color.images.push(row.image_url);
}
}
// Associate image with size if applicable
if (row.size_id) {
if (row.color_id) {
const color = product.colors.find(c => c.id === row.color_id);
const size = color?.sizes.find(s => s.id === row.size_id);
if (size && !size.images.includes(row.image_url)) {
size.images.push(row.image_url);
}
} else {
const size = product.sizes.find(s => s.id === row.size_id);
if (size && !size.images.includes(row.image_url)) {
size.images.push(row.image_url);
}
}
}
}
}
return product;
} catch (error) {
console.error('Error fetching product from DB:', error);
throw error; // Let the caller handle the error
}
};
2. Explanation of the Changes
Cache Retrieval:
The function first attempts to retrieve 'allProducts' from the productCache.
If the cache exists, it searches for the product with the specified productId within the cached allProducts array.
Cache Hit:
If the product is found in the cache, it is returned immediately, avoiding a database query.
Cache Miss:
If the cache is missing or the product isn't found within the cached data, the function falls back to querying the database using a helper function fetchProductByIdFromDb.
After fetching from the DB, it adds the newly fetched product to the cache using addProductToCache, ensuring that future requests for this product can be served from the cache.
Error Handling:
Comprehensive error handling ensures that any issues during cache retrieval or database queries are logged, and appropriate HTTP responses are sent.
3. Implement the addProductToCache Function
Ensure that the addProductToCache function correctly adds a single product to the existing cache. Given your current implementation, it updates the 'allProducts' array and adjusts minPrice and maxPrice.
Here's an example implementation (assuming your addProductToCache already does this):
// src/cacheHelper.ts
import { productCache } from "./cache";
import { Product, CacheData } from "product"; // Adjust the import path as necessary
/**
* Adds a new product to the cache.
*/
export const addProductToCache = (newProduct: Product) => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (cacheData) {
// Avoid adding duplicate products
if (!cacheData.allProducts.some(p => p.id === newProduct.id)) {
cacheData.allProducts.push(newProduct);
// Extract all prices from the new product
const productPrices: number[] = [newProduct.price];
newProduct.colors.forEach((color) => {
productPrices.push(color.price);
color.sizes.forEach((size) => productPrices.push(size.price));
});
newProduct.sizes.forEach((size) => productPrices.push(size.price));
// Update minPrice and maxPrice
if (productPrices.length > 0) {
cacheData.minPrice = Math.min(cacheData.minPrice, ...productPrices);
cacheData.maxPrice = Math.max(cacheData.maxPrice, ...productPrices);
}
productCache.set('allProducts', cacheData);
console.log(`Added new product ID ${newProduct.id} to cache.`);
} else {
console.log(`Product ID ${newProduct.id} already exists in cache.`);
}
} else {
// If cache is missing, reload all products
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache to force reload.');
}
} catch (error) {
console.error('Error adding product to cache:', error);
productCache.del('allProducts'); // Flushing cache to maintain consistency
}
};
4. Optional: Implement Per-Product Caching for Enhanced Efficiency
While the current caching strategy caches all products under 'allProducts', fetching a single product requires iterating through the array. For larger datasets, this can become inefficient. Implementing per-product caching can optimize retrieval times.
a. Update Cache Structure
Store individual products with keys like 'product_{id}' in addition to keeping the 'allProducts' array.
b. Modify getProductById for Per-Product Cache
export const getProductById = async (req: Request, res: Response) => {
const { id } = req.params;
const productId = parseInt(id, 10);
if (isNaN(productId)) {
return res.status(400).json({ error: 'Invalid product ID' });
}
try {
const productCacheKey = `product_${productId}`;
// Attempt to retrieve the product from the cache
let cachedProduct = productCache.get(productCacheKey) as Product | undefined;
if (cachedProduct) {
console.log(`Product ID ${productId} retrieved from cache.`);
return res.json({ product: cachedProduct });
} else {
console.log(`Product ID ${productId} not found in cache. Fetching from database.`);
// Fetch the product from the database
const productFromDb = await fetchProductByIdFromDb(productId);
if (productFromDb) {
// Add the fetched product to the cache with individual key
productCache.set(productCacheKey, productFromDb);
console.log(`Product ID ${productId} added to cache.`);
return res.json({ product: productFromDb });
} else {
// Product not found in the database
return res.status(404).json({ error: 'Product not found' });
}
}
} catch (error) {
console.error('Error fetching product by ID:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
c. Update Cache Helpers
Ensure that when products are added, updated, or deleted, the individual cache keys are also managed accordingly.
Example for addProductToCache:
export const addProductToCache = (newProduct: Product) => {
try {
// Add to 'allProducts' cache
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (cacheData) {
if (!cacheData.allProducts.some(p => p.id === newProduct.id)) {
cacheData.allProducts.push(newProduct);
const productPrices: number[] = [newProduct.price];
newProduct.colors.forEach((color) => {
productPrices.push(color.price);
color.sizes.forEach((size) => productPrices.push(size.price));
});
newProduct.sizes.forEach((size) => productPrices.push(size.price));
cacheData.minPrice = Math.min(cacheData.minPrice, ...productPrices);
cacheData.maxPrice = Math.max(cacheData.maxPrice, ...productPrices);
productCache.set('allProducts', cacheData);
console.log(`Added new product ID ${newProduct.id} to 'allProducts' cache.`);
}
} else {
// If 'allProducts' cache doesn't exist, reload it
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache to force reload.');
}
// Add individual product to cache
const productCacheKey = `product_${newProduct.id}`;
productCache.set(productCacheKey, newProduct);
console.log(`Added product ID ${newProduct.id} to individual cache.`);
} catch (error) {
console.error('Error adding product to cache:', error);
productCache.del('allProducts'); // Flush cache to maintain consistency
}
};
Similarly, update updateProductInCache and deleteProductFromCache to handle individual cache keys:
export const updateProductInCache = (updatedProduct: Product) => {
try {
// Update 'allProducts' cache
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (cacheData) {
const index = cacheData.allProducts.findIndex(p => p.id === updatedProduct.id);
if (index !== -1) {
cacheData.allProducts[index] = updatedProduct;
// Recalculate minPrice and maxPrice
const allPrices: number[] = [];
cacheData.allProducts.forEach(product => {
allPrices.push(product.price);
product.colors.forEach(color => {
allPrices.push(color.price);
color.sizes.forEach(size => allPrices.push(size.price));
});
product.sizes.forEach(size => allPrices.push(size.price));
});
cacheData.minPrice = allPrices.length > 0 ? Math.min(...allPrices) : 0;
cacheData.maxPrice = allPrices.length > 0 ? Math.max(...allPrices) : 0;
productCache.set('allProducts', cacheData);
console.log(`Updated product ID ${updatedProduct.id} in 'allProducts' cache.`);
} else {
// Product not found in 'allProducts'; flush cache
productCache.del('allProducts');
console.log('Product not found in cache. Flushed product cache.');
}
}
// Update individual product cache
const productCacheKey = `product_${updatedProduct.id}`;
productCache.set(productCacheKey, updatedProduct);
console.log(`Updated product ID ${updatedProduct.id} in individual cache.`);
} catch (error) {
console.error('Error updating product in cache:', error);
productCache.del('allProducts'); // Flush cache to maintain consistency
}
};
export const deleteProductFromCache = (productId: number) => {
try {
// Delete from 'allProducts' cache
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (cacheData) {
const initialLength = cacheData.allProducts.length;
cacheData.allProducts = cacheData.allProducts.filter(p => p.id !== productId);
if (cacheData.allProducts.length < initialLength) {
// Recalculate minPrice and maxPrice
const allPrices: number[] = [];
cacheData.allProducts.forEach(product => {
allPrices.push(product.price);
product.colors.forEach(color => {
allPrices.push(color.price);
color.sizes.forEach(size => allPrices.push(size.price));
});
product.sizes.forEach(size => allPrices.push(size.price));
});
cacheData.minPrice = allPrices.length > 0 ? Math.min(...allPrices) : 0;
cacheData.maxPrice = allPrices.length > 0 ? Math.max(...allPrices) : 0;
productCache.set('allProducts', cacheData);
console.log(`Deleted product ID ${productId} from 'allProducts' cache.`);
} else {
// Product not found; flush cache
productCache.del('allProducts');
console.log('Product not found in "allProducts" cache. Flushed product cache.');
}
}
// Delete individual product from cache
const productCacheKey = `product_${productId}`;
productCache.del(productCacheKey);
console.log(`Deleted product ID ${productId} from individual cache.`);
} catch (error) {
console.error('Error deleting product from cache:', error);
productCache.del('allProducts'); // Flush cache to maintain consistency
}
};
5. Ensuring Cache Consistency Across CRUD Operations
Create Product: After successfully creating a product, use addProductToCache to add it to both 'allProducts' and its individual cache.
Update Product: Use updateProductInCache to update both caches.
Delete Product: Use deleteProductFromCache to remove the product from both caches.
This ensures that all CRUD operations reflect accurately in the cache, maintaining data consistency.
6. Benefits of Per-Product Caching
Efficiency: Fetching a single product becomes faster as it doesn't require iterating through the entire allProducts array.
Scalability: As the number of products grows, individual caching prevents performance degradation that can occur when handling large arrays.
Flexibility: Allows for more granular cache invalidation and updates, leading to better cache management.
Final Thoughts and Recommendations
Cache Expiration:
Consider setting an expiration time for your cache entries to ensure data freshness. Libraries like Node-Cache or Redis support TTL (Time-To-Live) settings.
Error Handling:
Robust error handling is crucial. Always handle scenarios where the cache might be unavailable or corrupted.
Monitoring Cache Performance:
Implement logging and monitoring to track cache hits and misses. This data can help optimize cache usage patterns.
Testing:
Thoroughly test the caching mechanism, especially the synchronization between the cache and the database during concurrent operations.
Cache Invalidation:
Ensure that any update or deletion of products appropriately invalidates or updates the corresponding cache entries to prevent serving stale data.
By implementing these changes, your getProductById function will efficiently utilize the cache, resulting in faster response times and reduced load on your database.