To ensure that regular users can only access their own carts while admins retain the ability to view all carts, you'll need to implement a separate controller function for fetching a user's carts. Below are the detailed steps to achieve this:
- Update the Routes in
cartRoutes.ts
- Create the
getUserCarts Controller Function
- Ensure Proper Typing for
req.user
- Optional: Optimize Database Queries
- Ensure Caching is Handled Appropriately
Let's go through each step in detail.
1. Update the Routes in cartRoutes.ts
You need to differentiate between routes accessible to regular users and those restricted to admins. Specifically:
- Regular Users: Should access their own carts via
GET /carts.
- Admins: Should access all carts via
GET /carts/all.
Here's how to update your cartRoutes.ts:
// src/routes/cartRoutes.ts
import express from 'express';
import { body } from 'express-validator';
import { validateRequest } from '../middleware/validateRequest';
import { isAuthenticated } from '../middleware/isAuthenticated';
import * as cartController from '../controllers/cartController';
import { isAdmin } from "../middleware/authMiddleware";
import { deleteCart, getAllCarts, updateCart, getUserCarts } from "../controllers/cartController";
const router = express.Router();
// Create a new cart with items
router.post(
'/',
[
body('notes').optional().isString().withMessage('Notes is not valid'),
body('full_name').optional().isString().withMessage('Full name must be provided'),
body('governorate').isString().withMessage('Governorate must be provided'),
body('city').optional().isString().withMessage('City is not valid'),
body('address').isString().withMessage('Address must be provided'),
body('closest_point').optional().isString().withMessage('Closest point is not valid'),
body('phone_number').isString().withMessage('Phone number must be provided'),
body('type')
.optional({ values: "falsy" })
.isString()
.withMessage('Type must be home, work, or other'),
body('coupon_id')
.optional({ nullable: true })
.custom((value) => {
if (value === null) return true;
return Number.isInteger(Number(value));
})
.withMessage('Coupon is not valid'),
body('items').isArray({ min: 1 }).withMessage('Items array is required'),
body('items.*.product_id').isInt().withMessage('Product ID must be an integer'),
body('items.*.size_id').optional({ values: "falsy" }).isInt().withMessage('Size ID must be an integer'),
body('items.*.color_id').optional({ values: "falsy" }).isInt().withMessage('Color ID must be an integer'),
body('items.*.quantity').isInt({ min: 1 }).withMessage('Quantity must be greater than zero'),
],
validateRequest,
cartController.createCart
);
// Route for regular users to get their own carts
router.get('/', isAuthenticated, cartController.getUserCarts);
// Route for admins to get all carts
router.get('/all', isAdmin, getAllCarts);
router.put(
'/:id',
[
body('status').isString().withMessage('Status is required'),
],
validateRequest,
updateCart
);
router.delete('/:id', isAdmin, deleteCart);
export default router;
Explanation:
-
Regular Users Route (GET /carts): Uses isAuthenticated middleware and the new getUserCarts controller to fetch only the authenticated user's carts.
-
Admin Route (GET /carts/all): Uses isAdmin middleware and the existing getAllCarts controller to fetch all carts.
2. Create the getUserCarts Controller Function
Implement a new controller function getUserCarts that fetches carts belonging only to the authenticated user.
// src/controllers/cartController.ts
import { Request, Response, NextFunction } from 'express';
import { query } from "../config/database";
import {
deleteCartById,
updateCartStatus
} from "../models/cartModel";
import {
decreaseProductQtyInCache,
increaseColorSoldInCache,
increaseProductSoldInCache,
increaseSizeSoldInCache
} from "../cacheHelper";
import { cartCache, flushAllCarts, flushCartCache } from "../cache";
/**
* Existing controller functions...
*/
// New Controller Function to Get Authenticated User's Carts
export async function getUserCarts(req: Request, res: Response, next: NextFunction) {
try {
const userId = req.user?.userId; // Extract userId from the authenticated user
if (!userId) {
return res.status(401).json({ message: 'Unauthorized: User ID not found' });
}
const { page = 1, limit = 10 } = req.query;
const pageNumber = parseInt(page as string, 10);
const limitNumber = parseInt(limit as string, 10);
const cacheKey = `userCarts_user_${userId}_page_${pageNumber}_limit_${limitNumber}`;
// Check if data is in cache
const cachedCarts = cartCache.get(cacheKey);
if (cachedCarts) {
return res.json(cachedCarts);
}
const offset = (pageNumber - 1) * limitNumber;
// Fetch user's carts with pagination
const cartsResult = await query(
`SELECT * FROM carts WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`,
[userId, limitNumber, offset]
);
const carts = cartsResult.rows;
// Fetch total number of user's carts for pagination
const totalResult = await query(
`SELECT COUNT(*) FROM carts WHERE user_id = $1`,
[userId]
);
const total = parseInt(totalResult.rows[0].count, 10);
// Fetch items for each cart
for (const cart of carts) {
const itemsResult = await query(
`SELECT * FROM cart_items WHERE cart_id = $1`,
[cart.id]
);
cart.items = itemsResult.rows;
}
const response = { carts, total, page: pageNumber, limit: limitNumber };
// Store in cache
cartCache.set(cacheKey, response);
res.json(response);
} catch (error) {
console.error('Error fetching user carts:', error);
next(error);
}
}
/**
* Existing controller functions...
*/
Explanation:
-
Extract userId from req.user: This assumes your isAuthenticated middleware properly decodes the JWT and attaches the user information to req.user.
-
Pagination Parameters: Defaults to page 1 and limit 10 if not provided.
-
Caching: Before making a database query, the function checks if the result is already cached to improve performance.
-
Database Queries:
- Fetch Carts: Retrieves carts belonging to the authenticated user with pagination.
- Fetch Total Count: Keeps track of the total number of carts for pagination purposes.
- Fetch Cart Items: For each cart, it fetches the associated items.
-
Respond with Data: Returns the carts along with pagination metadata.
3. Ensure Proper Typing for req.user
Since you're adding a user property to the Request object, TypeScript needs to be aware of this. You can achieve this by extending the Express Request interface.
Create a types directory if it doesn't exist and add an express type declaration:
// src/types/express/index.d.ts
import { DecodedToken } from '../../middleware/isAuthenticated';
declare global {
namespace Express {
interface Request {
user?: DecodedToken;
}
}
}
Explanation:
-
Extended Interface: This extends the existing Request interface to include an optional user property of type DecodedToken.
-
Avoid TypeScript Errors: This ensures that when you access req.user in your controllers, TypeScript recognizes it and doesn't throw type errors.
Ensure Type Declaration is Included:
Make sure that your tsconfig.json includes the types directory or the specific type declaration file.
// tsconfig.json
{
"compilerOptions": {
// ... other options
"typeRoots": ["./node_modules/@types", "./src/types"]
},
// ... other configurations
}
4. Optional: Optimize Database Queries
Fetching items for each cart individually can lead to performance issues, especially with a large number of carts. To optimize, you can perform a single query to fetch all cart items for the retrieved carts.
Here's how you can modify the getUserCarts function:
// src/controllers/cartController.ts
export async function getUserCarts(req: Request, res: Response, next: NextFunction) {
try {
const userId = req.user?.userId;
if (!userId) {
return res.status(401).json({ message: 'Unauthorized: User ID not found' });
}
const { page = 1, limit = 10 } = req.query;
const pageNumber = parseInt(page as string, 10);
const limitNumber = parseInt(limit as string, 10);
const cacheKey = `userCarts_user_${userId}_page_${pageNumber}_limit_${limitNumber}`;
// Check if data is in cache
const cachedCarts = cartCache.get(cacheKey);
if (cachedCarts) {
return res.json(cachedCarts);
}
const offset = (pageNumber - 1) * limitNumber;
// Fetch user's carts with pagination
const cartsResult = await query(
`SELECT * FROM carts WHERE user_id = $1 ORDER BY created_at DESC LIMIT $2 OFFSET $3`,
[userId, limitNumber, offset]
);
const carts = cartsResult.rows;
// Fetch all cart IDs
const cartIds = carts.map(cart => cart.id);
let items = [];
if (cartIds.length > 0) {
const itemsResult = await query(
`SELECT * FROM cart_items WHERE cart_id = ANY($1::int[])`,
[cartIds]
);
items = itemsResult.rows;
}
// Assign items to their respective carts
const cartsWithItems = carts.map(cart => {
return {
...cart,
items: items.filter(item => item.cart_id === cart.id),
};
});
// Fetch total number of user's carts for pagination
const totalResult = await query(
`SELECT COUNT(*) FROM carts WHERE user_id = $1`,
[userId]
);
const total = parseInt(totalResult.rows[0].count, 10);
const response = { carts: cartsWithItems, total, page: pageNumber, limit: limitNumber };
// Store in cache
cartCache.set(cacheKey, response);
res.json(response);
} catch (error) {
console.error('Error fetching user carts:', error);
next(error);
}
}
Benefits:
-
Reduced Number of Queries: Instead of making one query per cart to fetch its items, you fetch all relevant items in a single query.
-
Improved Performance: Especially beneficial when dealing with a large number of carts and items.
5. Ensure Caching is Handled Appropriately
Caching is a powerful tool to enhance performance, but it's crucial to manage cache invalidation correctly to prevent stale data.
Current Implementation:
- Carts Caching: You're caching the response of fetching carts based on the user ID, page, and limit.
Updating Cache on Modifications:
-
Create Cart: Invalidate the user's cache when a new cart is created.
-
Update Cart: Invalidate the specific cart's cache or the user's cache.
-
Delete Cart: Invalidate the user's cache.
Example: Invalidating Cache After Creating a Cart
// After successfully creating a cart in createCart function
flushCartCache(userId); // Implement this function to remove all cache entries related to this user
Implementing flushCartCache Function:
You need a way to invalidate all cache entries related to a specific user. If you're using a caching library like node-cache, you can implement a pattern to track cache keys per user.
// src/cache.ts
import NodeCache from 'node-cache';
export const cartCache = new NodeCache();
// Helper to store user-specific cache keys
const userCacheKeys: { [userId: number]: string[] } = {};
/**
* Store cache with tracking
*/
export function setCartCache(key: string, value: any, userId: number) {
cartCache.set(key, value);
if (!userCacheKeys[userId]) {
userCacheKeys[userId] = [];
}
userCacheKeys[userId].push(key);
}
/**
* Flush cart cache for a specific user
*/
export function flushCartCache(userId: number) {
const keys = userCacheKeys[userId];
if (keys && keys.length > 0) {
cartCache.del(keys);
userCacheKeys[userId] = [];
}
}
/**
* Flush all carts cache (for admin actions)
*/
export function flushAllCarts() {
cartCache.flushAll();
Object.keys(userCacheKeys).forEach(userId => {
userCacheKeys[userId] = [];
});
}
Explanation:
-
Tracking Cache Keys: By maintaining a userCacheKeys object, you can keep track of all cache keys associated with a particular user.
-
Setting Cache: Use setCartCache instead of directly using cartCache.set to ensure that cache keys are tracked.
-
Flushing Cache: When a cart is created, updated, or deleted, call flushCartCache(userId) to remove all cached data related to that user.
Update Controller Functions to Use setCartCache
Modify the getUserCarts function to use setCartCache:
// src/controllers/cartController.ts
import { setCartCache } from '../cache';
// Inside getUserCarts function
// Replace cartCache.set(cacheKey, response); with:
setCartCache(cacheKey, response, userId);
Final Implementation Overview
- Routes: Separated routes for regular users and admins to access carts.
- Controllers:
getUserCarts: Fetches carts belonging only to the authenticated user with pagination and caching.
getAllCarts: Existing function remains for admins.
- Middleware: Ensures that
req.user is correctly typed and populated.
- Caching: Implemented user-specific cache invalidation to prevent stale data.
Summary
By following the above steps, you ensure that:
-
Security: Regular users can only access their own carts, while admins retain broader access.
-
Performance: Efficient database queries and effective caching mechanisms are in place.
-
Scalability: The system is designed to handle a growing number of users and carts without significant performance degradation.
Implementing these changes will enhance the robustness and reliability of your cart management system in your Express.js application.