To implement efficient caching for product creation, update, and deletion in your productController.ts, it's essential to ensure that your cache remains consistent with the database state. Below, I'll guide you through the necessary steps to achieve this, including addressing potential issues in your current implementation and providing updated code snippets.
1. Ensure Consistent Cache Keys
Firstly, it's crucial to maintain consistency in the cache keys used throughout your application. In your current implementation:
-
Caching Products:
- Set Key:
cacheData
- Flush Key:
allProducts (in flushProductCache)
-
Caching Brands:
To maintain consistency, let's standardize the product cache key to allProducts. This adjustment ensures that caching and cache invalidation operations refer to the same key.
Update loadAndCacheAllProducts Function:
const loadAndCacheAllProducts = async (): Promise<CacheData> => {
// ... existing code ...
// 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;
};
Update flushProductCache Function in cache.ts:
export const flushProductCache = () => {
productCache.del('allProducts');
};
By standardizing the cache key to allProducts, you ensure that all cache operations target the same key, avoiding discrepancies.
2. Implement Cache Update Logic in CRUD Operations
Next, we'll enhance your createProduct, updateProduct, and deleteProduct functions to update the cache appropriately. The logic will attempt to modify the cache directly; if it fails (e.g., if the cache is not present or does not contain the expected data), it will clear the cache to ensure consistency.
Helper Functions for Cache Management
To keep your controller functions clean and maintainable, let's introduce helper functions to handle cache updates.
// cacheHelpers.ts
import { productCache } from "../cache";
import { Product, CacheData } from "../types/product";
/**
* Attempts to add a new product to the cache.
* If the cache is unavailable, it flushes the cache.
*/
export const addProductToCache = (newProduct: Product) => {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (cacheData) {
cacheData.allProducts.push(newProduct);
// Update minPrice and maxPrice
const productMinPrice = Math.min(...newProduct.sizes.map(s => s.price), cacheData.minPrice);
const productMaxPrice = Math.max(...newProduct.sizes.map(s => s.price), cacheData.maxPrice);
cacheData.minPrice = Math.min(cacheData.minPrice, productMinPrice);
cacheData.maxPrice = Math.max(cacheData.maxPrice, productMaxPrice);
productCache.set('allProducts', cacheData);
console.log('Added new product to cache.');
} else {
// Cache not available; flush to refresh on next access
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache.');
}
};
/**
* Attempts to update an existing product in the cache.
* If the cache is unavailable or the product isn't found, it flushes the cache.
*/
export const updateProductInCache = (updatedProduct: Product) => {
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 = cacheData.allProducts.flatMap(p => p.sizes.map(s => s.price));
cacheData.minPrice = Math.min(...allPrices, 0);
cacheData.maxPrice = Math.max(...allPrices, 0);
productCache.set('allProducts', cacheData);
console.log('Updated product in cache.');
} else {
// Product not found; flush cache
productCache.del('allProducts');
console.log('Product not found in cache. Flushed product cache.');
}
} else {
// Cache not available; flush to refresh on next access
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache.');
}
};
/**
* Attempts to delete a product from the cache.
* If the cache is unavailable or the product isn't found, it flushes the cache.
*/
export const deleteProductFromCache = (productId: number) => {
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 = cacheData.allProducts.flatMap(p => p.sizes.map(s => s.price));
cacheData.minPrice = Math.min(...allPrices, 0);
cacheData.maxPrice = Math.max(...allPrices, 0);
productCache.set('allProducts', cacheData);
console.log('Deleted product from cache.');
} else {
// Product not found; flush cache
productCache.del('allProducts');
console.log('Product not found in cache. Flushed product cache.');
}
} else {
// Cache not available; flush to refresh on next access
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache.');
}
};
Integrate Helper Functions into CRUD Operations
Now, update your CRUD operations to utilize these helper functions.
1. Create Product
Before Update:
At the end of the createProduct function, there's a comment:
// Invalidate the all_products cache
After Update:
Replace the comment with logic to add the new product to the cache.
import { addProductToCache } from "./cacheHelpers";
// ... other imports ...
export const createProduct = async (req: Request, res: Response) => {
try {
await query('BEGIN');
const productData = req.body;
// ... existing product creation logic ...
// Construct the new product object as it would appear in the cache
const newProduct: Product = {
id: productId,
name: productData.name,
description: productData.description,
brand_id: productData.brand_id,
has_color: productData.hasColor,
has_size: productData.hasSize,
product_type: productData.product_type,
price: productData.price,
qty: productData.qty,
sold: 0,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
categories: productData.category_ids.map((cid: number) => ({
id: cid,
name: "", // Optionally fetch category names
main_category_id: 0, // Set appropriately
main_category_name: "" // Set appropriately
})),
sizes: productData.hasSize
? productData.sizes.map((size: any) => ({
id: size.id,
name: size.name,
price: size.price,
qty: size.qty,
sold: size.sold
}))
: [],
};
// Update the cache
addProductToCache(newProduct);
await query('COMMIT');
res.status(201).json({ message: 'Product created successfully', productId });
} catch (error) {
await query('ROLLBACK');
console.error('Error creating product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
Notes:
-
Category Details: In the newProduct construction, category details (name, main_category_id, and main_category_name) are placeholders. You should fetch and populate these details based on your application's logic.
-
Date Fields: The created_at and updated_at fields are set to the current date. Adjust as necessary to reflect the actual database timestamps.
2. Update Product
Before Update:
At the end of the updateProduct function, there's a comment:
// Invalidate the all_products cache
After Update:
Replace the comment with logic to update the product in the cache.
import { updateProductInCache } from "./cacheHelpers";
// ... other imports ...
export const updateProduct = async (req: Request, res: Response) => {
const { id } = req.params;
const productData = req.body;
try {
await query('BEGIN');
// ... existing product update logic ...
// Construct the updated product object as it would appear in the cache
const updatedProduct: Product = {
id: parseInt(id, 10),
name: productData.name,
description: productData.description,
brand_id: productData.brand_id,
has_color: productData.hasColor,
has_size: productData.hasSize,
product_type: productData.product_type,
price: productData.price,
qty: productData.qty,
sold: productData.sold || 0,
created_at: result.rows[0].created_at, // Assuming retrieved from DB
updated_at: new Date().toISOString(),
categories: productData.category_ids.map((cid: number) => ({
id: cid,
name: "", // Optionally fetch category names
main_category_id: 0, // Set appropriately
main_category_name: "" // Set appropriately
})),
sizes: productData.hasSize
? productData.sizes.map((size: any) => ({
id: size.id,
name: size.name,
price: size.price,
qty: size.qty,
sold: size.sold || 0
}))
: [],
};
// Update the cache
updateProductInCache(updatedProduct);
await query('COMMIT');
res.json({ message: 'Product updated successfully', product: result.rows[0] });
} catch (error) {
await query('ROLLBACK');
console.error('Error updating product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
Notes:
-
Category Details: Similar to createProduct, ensure category details are accurately populated.
-
Date Fields: Ensure created_at is retrieved from the database and updated_at reflects the current update.
3. Delete Product
Before Update:
At the end of the deleteProduct function, there's a comment:
// Invalidate the all_products cache
After Update:
Replace the comment with logic to delete the product from the cache.
import { deleteProductFromCache } from "./cacheHelpers";
// ... other imports ...
export const deleteProduct = async (req: Request, res: Response) => {
const { id } = req.params;
try {
await query('BEGIN');
// ... existing product deletion logic ...
// Delete the product from the cache
deleteProductFromCache(parseInt(id, 10));
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' });
}
};
Notes:
- Parsing ID: Ensure the
id is correctly parsed as a number before passing it to the cache helper.
3. Handle Cache Exceptions Gracefully
While working with caches, it's possible to encounter exceptions (e.g., if the cache store becomes unavailable). To ensure that your application remains robust, wrap cache operations in try-catch blocks within the helper functions.
Update cacheHelpers.ts with Error Handling:
// cacheHelpers.ts
import { productCache } from "../cache";
import { Product, CacheData } from "../types/product";
export const addProductToCache = (newProduct: Product) => {
try {
const cacheData: CacheData | undefined = productCache.get('allProducts');
if (cacheData) {
cacheData.allProducts.push(newProduct);
// Update minPrice and maxPrice
const productMinPrice = Math.min(...newProduct.sizes.map(s => s.price), cacheData.minPrice);
const productMaxPrice = Math.max(...newProduct.sizes.map(s => s.price), cacheData.maxPrice);
cacheData.minPrice = Math.min(cacheData.minPrice, productMinPrice);
cacheData.maxPrice = Math.max(cacheData.maxPrice, productMaxPrice);
productCache.set('allProducts', cacheData);
console.log('Added new product to cache.');
} else {
// Cache not available; flush to refresh on next access
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache.');
}
} catch (error) {
console.error('Error adding product to cache:', error);
// Optional: Decide whether to flush the cache or take other actions
productCache.del('allProducts');
}
};
export const updateProductInCache = (updatedProduct: Product) => {
try {
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 = cacheData.allProducts.flatMap(p => p.sizes.map(s => s.price));
cacheData.minPrice = Math.min(...allPrices, 0);
cacheData.maxPrice = Math.max(...allPrices, 0);
productCache.set('allProducts', cacheData);
console.log('Updated product in cache.');
} else {
// Product not found; flush cache
productCache.del('allProducts');
console.log('Product not found in cache. Flushed product cache.');
}
} else {
// Cache not available; flush to refresh on next access
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache.');
}
} catch (error) {
console.error('Error updating product in cache:', error);
// Optional: Decide whether to flush the cache or take other actions
productCache.del('allProducts');
}
};
export const deleteProductFromCache = (productId: number) => {
try {
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 = cacheData.allProducts.flatMap(p => p.sizes.map(s => s.price));
cacheData.minPrice = Math.min(...allPrices, 0);
cacheData.maxPrice = Math.max(...allPrices, 0);
productCache.set('allProducts', cacheData);
console.log('Deleted product from cache.');
} else {
// Product not found; flush cache
productCache.del('allProducts');
console.log('Product not found in cache. Flushed product cache.');
}
} else {
// Cache not available; flush to refresh on next access
productCache.del('allProducts');
console.log('Cache unavailable. Flushed product cache.');
}
} catch (error) {
console.error('Error deleting product from cache:', error);
// Optional: Decide whether to flush the cache or take other actions
productCache.del('allProducts');
}
};
Benefits:
- Robustness: Ensures that cache-related errors don't crash your application.
- Consistency: By flushing the cache in case of errors, you ensure that stale or inconsistent data doesn't persist.
4. Review and Test Your Implementation
After integrating the cache management logic:
-
Review the Relationships: Ensure that relationships like categories, sizes, and brands are correctly handled when constructing the Product objects for caching.
-
Test CRUD Operations:
- Create: Verify that a newly created product appears in the cache without needing to reload all products.
- Update: Ensure that updating a product reflects immediately in the cache.
- Delete: Confirm that deleted products are removed from the cache.
-
Handle Edge Cases:
- Cache Misses: Ensure that the application gracefully handles scenarios where the cache is empty or corrupted by flushing and reloading as necessary.
- Concurrent Modifications: Consider scenarios where multiple operations might modify the cache simultaneously, potentially leading to race conditions.
-
Monitor Performance:
- Cache Efficiency: Monitor cache hit rates to ensure that caching is effectively reducing database load.
- Memory Usage: Ensure that the cache size remains manageable, especially if dealing with a large number of products.
5. Optional Enhancements
-
Selective Cache Updates: Depending on your application's size and usage patterns, you might consider more granular caching strategies (e.g., caching individual products or subsets based on categories).
-
Cache Expiration and Refresh: Implement strategies to periodically refresh the cache or invalidate it based on specific triggers or timeouts.
-
Distributed Caching: For scalability, especially in a multi-instance deployment, consider using distributed caching solutions like Redis instead of node-cache.
Complete Updated productController.ts
Here's the updated productController.ts incorporating the discussed changes:
// productController.ts
import { Request, Response } from 'express';
import { query } from "../config/database";
import { brandsCache, productCache } from "../cache";
import { Brand, BrandsCacheData, CacheData, Product } from "product";
import { addProductToCache, updateProductInCache, deleteProductFromCache } from "./cacheHelpers"; // Import helper functions
// ... existing loadAndCacheAllProducts and loadAndCacheAllBrands functions ...
export const createProduct = async (req: Request, res: Response) => {
try {
await query('BEGIN');
const productData = req.body;
// Adjust price if necessary
if (productData.price < 1000) {
productData.price *= 1000;
}
// Insert product
const productResult = await query(
`INSERT INTO products (name, description, brand_id, has_color, has_size, product_type, price, qty, sold)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 0) RETURNING id, created_at, updated_at`,
[
productData.name,
productData.description,
productData.brand_id,
productData.hasColor,
productData.hasSize,
productData.product_type,
productData.price,
productData.qty
]
);
const productId = productResult.rows[0].id;
const createdAt = productResult.rows[0].created_at;
const updatedAt = productResult.rows[0].updated_at;
// Insert category associations
const categoryInsertPromises = productData.category_ids.map((categoryId: number) =>
query(
`INSERT INTO product_categories (product_id, category_id)
VALUES ($1, $2)`,
[productId, categoryId]
)
);
await Promise.all(categoryInsertPromises);
// Insert images
const imagesInsertPromises = productData.images.map((imageUrl: string) =>
query(
`INSERT INTO images (product_id, url)
VALUES ($1, $2)`,
[productId, imageUrl]
)
);
await Promise.all(imagesInsertPromises);
// Handle colors and sizes based on product type
if (productData.hasColor) {
for (const color of productData.colors) {
// Adjust color price if necessary
if (color.price < 1000) {
color.price *= 1000;
}
// Insert color
const colorResult = await query(
`INSERT INTO colors (product_id, name, has_size, price, qty, sold)
VALUES ($1, $2, $3, $4, $5, 0) RETURNING id`,
[productId, color.name, color.hasSize, color.price, color.qty]
);
const colorId = colorResult.rows[0].id;
// Insert color images
const colorImagesInsertPromises = color.images.map((imageUrl: string) =>
query(
`INSERT INTO images (product_id, color_id, url)
VALUES ($1, $2, $3)`,
[productId, colorId, imageUrl]
)
);
await Promise.all(colorImagesInsertPromises);
if (color.hasSize) {
for (const size of color.sizes) {
// Adjust size price if necessary
if (size.price < 1000) {
size.price *= 1000;
}
// Insert size
const sizeResult = await query(
`INSERT INTO sizes (product_id, color_id, name, price, qty, sold)
VALUES ($1, $2, $3, $4, $5, 0) RETURNING id`,
[productId, colorId, size.name, size.price, size.qty]
);
const sizeId = sizeResult.rows[0].id;
// Insert size images
const sizeImagesInsertPromises = size.images.map((imageUrl: string) =>
query(
`INSERT INTO images (product_id, color_id, size_id, url)
VALUES ($1, $2, $3, $4)`,
[productId, colorId, sizeId, imageUrl]
)
);
await Promise.all(sizeImagesInsertPromises);
}
}
}
} else if (productData.hasSize) {
for (const size of productData.sizes) {
// Adjust size price if necessary
if (size.price < 1000) {
size.price *= 1000;
}
// Insert size
const sizeResult = await query(
`INSERT INTO sizes (product_id, name, price, qty, sold)
VALUES ($1, $2, $3, $4, 0) RETURNING id`,
[productId, size.name, size.price, size.qty]
);
const sizeId = sizeResult.rows[0].id;
// Insert size images
const sizeImagesInsertPromises = size.images.map((imageUrl: string) =>
query(
`INSERT INTO images (product_id, size_id, url)
VALUES ($1, $2, $3)`,
[productId, sizeId, imageUrl]
)
);
await Promise.all(sizeImagesInsertPromises);
}
}
// Construct the new product object for caching
const newProduct: Product = {
id: productId,
name: productData.name,
description: productData.description,
brand_id: productData.brand_id,
has_color: productData.hasColor,
has_size: productData.hasSize,
product_type: productData.product_type,
price: productData.price,
qty: productData.qty,
sold: 0,
created_at: createdAt.toISOString(),
updated_at: updatedAt.toISOString(),
categories: productData.category_ids.map((cid: number) => ({
id: cid,
name: "", // Optionally fetch category names
main_category_id: 0, // Set appropriately
main_category_name: "" // Set appropriately
})),
sizes: productData.hasSize
? productData.sizes.map((size: any) => ({
id: size.id,
name: size.name,
price: size.price,
qty: size.qty,
sold: 0
}))
: [],
};
// Update the cache
addProductToCache(newProduct);
await query('COMMIT');
res.status(201).json({ message: 'Product created successfully', productId });
} catch (error) {
await query('ROLLBACK');
console.error('Error creating product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
export const updateProduct = async (req: Request, res: Response) => {
const { id } = req.params;
const productData = req.body;
try {
await query('BEGIN');
// Adjust price if necessary
if (productData.price < 1000) {
productData.price *= 1000;
}
// Update product details
const result = await query(
`UPDATE products
SET name = $1,
description = $2,
brand_id = $3,
has_color = $4,
has_size = $5,
product_type = $6,
price = $7,
qty = $8,
updated_at = CURRENT_TIMESTAMP
WHERE id = $9
RETURNING *`,
[
productData.name,
productData.description,
productData.brand_id,
productData.hasColor,
productData.hasSize,
productData.product_type,
productData.price,
productData.qty,
id
]
);
if (result.rows.length === 0) {
await query('ROLLBACK');
return res.status(404).json({ error: 'Product not found' });
}
// Delete existing associations and data
await query('DELETE FROM product_categories WHERE product_id = $1', [id]);
await query('DELETE FROM images WHERE product_id = $1', [id]);
// Get existing colors and sizes
const existingColors = await query('SELECT id FROM colors WHERE product_id = $1', [id]);
const existingColorIds = new Set(existingColors.rows.map(row => row.id));
const existingSizes = await query('SELECT id FROM sizes WHERE product_id = $1', [id]);
const existingSizeIds = new Set(existingSizes.rows.map(row => row.id));
// Determine colors and sizes to delete
const updatedColorIds = new Set(
productData.colors
.map((color: { id: any }) => color.id)
.filter((id: any) => id !== undefined)
);
const colorsToDelete = [...existingColorIds].filter(id => !updatedColorIds.has(id));
const updatedSizeIds = new Set([
...productData.sizes
.map((size: { id: any }) => size.id)
.filter((id: any) => id !== undefined),
...productData.colors.flatMap((color: { sizes: any[] }) =>
color.sizes.map(size => size.id).filter(id => id !== undefined)
)
]);
const sizesToDelete = [...existingSizeIds].filter(id => !updatedSizeIds.has(id));
// Delete colors and associated sizes and images
for (const colorId of colorsToDelete) {
await query('DELETE FROM sizes WHERE color_id = $1', [colorId]);
await query('DELETE FROM images WHERE color_id = $1', [colorId]);
await query('DELETE FROM colors WHERE id = $1', [colorId]);
}
// Delete sizes and associated images
for (const sizeId of sizesToDelete) {
await query('DELETE FROM images WHERE size_id = $1', [sizeId]);
await query('DELETE FROM sizes WHERE id = $1', [sizeId]);
}
// Insert category associations
const categoryInsertPromises = productData.category_ids.map((categoryId: number) =>
query(
`INSERT INTO product_categories (product_id, category_id)
VALUES ($1, $2)`,
[id, categoryId]
)
);
await Promise.all(categoryInsertPromises);
// Insert images
const imagesInsertPromises = productData.images.map((imageUrl: string) =>
query(
`INSERT INTO images (product_id, url)
VALUES ($1, $2)`,
[id, imageUrl]
)
);
await Promise.all(imagesInsertPromises);
// Handle colors and sizes based on product type
if (productData.hasColor) {
for (const color of productData.colors) {
// Adjust color price if necessary
if (color.price < 1000) {
color.price *= 1000;
}
let colorId: number;
if (color.id) {
// Update existing color
await query(
`UPDATE colors
SET name = $1,
has_size = $2,
price = $3,
qty = $4,
sold = $5
WHERE id = $6`,
[color.name, color.hasSize, color.price, color.qty, color.sold || 0, color.id]
);
colorId = color.id;
} else {
// Insert new color
const colorResult = await query(
`INSERT INTO colors (product_id, name, has_size, price, qty, sold)
VALUES ($1, $2, $3, $4, $5, 0) RETURNING id`,
[id, color.name, color.hasSize, color.price, color.qty]
);
colorId = colorResult.rows[0].id;
}
// Insert color images
const colorImagesInsertPromises = color.images.map((imageUrl: string) =>
query(
`INSERT INTO images (product_id, color_id, url)
VALUES ($1, $2, $3)`,
[id, colorId, imageUrl]
)
);
await Promise.all(colorImagesInsertPromises);
if (color.hasSize) {
for (const size of color.sizes) {
// Adjust size price if necessary
if (size.price < 1000) {
size.price *= 1000;
}
let sizeId: number;
if (size.id) {
// Update existing size
await query(
`UPDATE sizes
SET name = $1,
price = $2,
qty = $3,
sold = $4
WHERE id = $5`,
[size.name, size.price, size.qty, size.sold || 0, size.id]
);
sizeId = size.id;
} else {
// Insert new size
const sizeResult = await query(
`INSERT INTO sizes (product_id, color_id, name, price, qty, sold)
VALUES ($1, $2, $3, $4, $5, 0) RETURNING id`,
[id, colorId, size.name, size.price, size.qty]
);
sizeId = sizeResult.rows[0].id;
}
// Insert size images
const sizeImagesInsertPromises = size.images.map((imageUrl: string) =>
query(
`INSERT INTO images (product_id, color_id, size_id, url)
VALUES ($1, $2, $3, $4)`,
[id, colorId, sizeId, imageUrl]
)
);
await Promise.all(sizeImagesInsertPromises);
}
}
}
} else if (productData.hasSize) {
for (const size of productData.sizes) {
// Adjust size price if necessary
if (size.price < 1000) {
size.price *= 1000;
}
let sizeId: number;
if (size.id) {
// Update existing size
await query(
`UPDATE sizes
SET name = $1,
price = $2,
qty = $3,
sold = $4
WHERE id = $5`,
[size.name, size.price, size.qty, size.sold || 0, size.id]
);
sizeId = size.id;
} else {
// Insert new size
const sizeResult = await query(
`INSERT INTO sizes (product_id, name, price, qty, sold)
VALUES ($1, $2, $3, $4, 0) RETURNING id`,
[id, size.name, size.price, size.qty]
);
sizeId = sizeResult.rows[0].id;
}
// Insert size images
const sizeImagesInsertPromises = size.images.map((imageUrl: string) =>
query(
`INSERT INTO images (product_id, size_id, url)
VALUES ($1, $2, $3)`,
[id, sizeId, imageUrl]
)
);
await Promise.all(sizeImagesInsertPromises);
}
}
// Construct the updated product object for caching
const updatedProduct: Product = {
id: parseInt(id, 10),
name: productData.name,
description: productData.description,
brand_id: productData.brand_id,
has_color: productData.hasColor,
has_size: productData.hasSize,
product_type: productData.product_type,
price: productData.price,
qty: productData.qty,
sold: productData.sold || 0,
created_at: result.rows[0].created_at.toISOString(),
updated_at: new Date().toISOString(),
categories: productData.category_ids.map((cid: number) => ({
id: cid,
name: "", // Optionally fetch category names
main_category_id: 0, // Set appropriately
main_category_name: "" // Set appropriately
})),
sizes: productData.hasSize
? productData.sizes.map((size: any) => ({
id: size.id,
name: size.name,
price: size.price,
qty: size.qty,
sold: size.sold || 0
}))
: [],
};
// Update the cache
updateProductInCache(updatedProduct);
await query('COMMIT');
res.json({ message: 'Product updated successfully', product: result.rows[0] });
} catch (error) {
await query('ROLLBACK');
console.error('Error updating product:', error);
res.status(500).json({ error: 'Internal server error' });
}
};
export const deleteProduct = async (req: Request, res: Response) => {
const { id } = req.params;
try {
await query('BEGIN');
// Delete related data first
await query('DELETE FROM product_categories WHERE product_id = $1', [id]);
await query('DELETE FROM images WHERE product_id = $1', [id]);
await query('DELETE FROM sizes WHERE product_id = $1', [id]);
await query('DELETE FROM colors WHERE product_id = $1', [id]);
// Delete the product
const result = await query('DELETE FROM products WHERE id = $1 RETURNING *', [id]);
if (result.rows.length === 0) {
await query('ROLLBACK');
return res.status(404).json({ error: 'Product not found' });
}
// Delete the product from the cache
deleteProductFromCache(parseInt(id, 10));
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' });
}
};
6. Summary
By following the steps above, you've enhanced your productController.ts to manage the cache effectively during product creation, updating, and deletion. This approach ensures that:
-
Consistency: The cache remains consistent with the database state, reducing the risk of serving stale or incorrect data.
-
Performance: Efficient cache updates can significantly improve application performance by minimizing database queries.
-
Robustness: Proper error handling ensures that cache-related issues do not compromise the application's stability.
Remember to thoroughly test these changes in a development environment before deploying them to production. Monitoring tools can also help track cache performance and identify potential bottlenecks or issues.