Certainly! Below is a comprehensive guide to implementing a Wishlist feature in your Node.js (Express) application with PostgreSQL. This includes:
- Database Schema for the Wishlist Table
- Controller Functions (
getWishlist, addToWishlist, removeFromWishlist)
- Connecting Controllers with Routes
- Handling Product Deletion Cascades
- Database Connection Setup
Let's go through each part step-by-step.
1. Database Schema for the Wishlist Table
First, you'll need to create a wishlist table that links users to their desired products. This table will have user_id and product_id as foreign keys referencing the users and products tables, respectively. To ensure that when a product is deleted, it is also removed from all users' wishlists, we'll use the ON DELETE CASCADE constraint.
SQL Schema
CREATE TABLE wishlist (
user_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE,
UNIQUE (user_id, product_id) -- Prevents duplicate wishlist entries
);
Notes:
created_at: Tracks when the item was added to the wishlist.
UNIQUE (user_id, product_id): Ensures that each user can add a specific product only once to their wishlist.
ON DELETE CASCADE:
- For
user_id: If a user is deleted, all their wishlist entries are automatically removed.
- For
product_id: If a product is deleted, it is automatically removed from all wishlists.
Migration Example Using pg and SQL
If you're managing migrations manually, you can run the above SQL directly. Alternatively, if you're using a migration tool like Knex.js or Sequelize, integrate the schema accordingly.
2. Controller Functions
We'll create three controller functions: getWishlist, addToWishlist, and removeFromWishlist. These functions will interact with the PostgreSQL database to perform the necessary operations.
Setting Up Database Connection
First, ensure you have a PostgreSQL client set up. We'll use the pg library along with environment variables for configuration.
npm install pg
db.js - Database Connection Module
// db.js
import { Pool } from 'pg';
const pool = new Pool({
connectionString: process.env.DATABASE_URL, // Ensure this is set in your environment
// Additional configuration options if needed
});
export default pool;
wishlistController.js
// controllers/wishlistController.js
import { Request, Response } from 'express';
import pool from '../db'; // Adjust the path based on your project structure
/**
* Get all wishlist products for the authenticated user
*/
export const getWishlist = async (req: Request, res: Response) => {
const userId = req.user.id; // Based on your isAuthenticated middleware
try {
const query = `
SELECT p.id, p.name, p.description, p.price, p.image_url
FROM wishlist w
JOIN products p ON w.product_id = p.id
WHERE w.user_id = $1
ORDER BY w.created_at DESC
`;
const { rows } = await pool.query(query, [userId]);
res.status(200).json({ wishlist: rows });
} catch (error) {
console.error('Error fetching wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
/**
* Add a product to the authenticated user's wishlist
*/
export const addToWishlist = async (req: Request, res: Response) => {
const userId = req.user.id;
const { product_id } = req.body;
if (!product_id) {
return res.status(400).json({ message: 'Product ID is required' });
}
try {
const insertQuery = `
INSERT INTO wishlist (user_id, product_id)
VALUES ($1, $2)
ON CONFLICT (user_id, product_id) DO NOTHING
RETURNING *
`;
const { rows } = await pool.query(insertQuery, [userId, product_id]);
if (rows.length === 0) {
return res.status(409).json({ message: 'Product already in wishlist' });
}
res.status(201).json({ message: 'Product added to wishlist', wishlistItem: rows[0] });
} catch (error) {
console.error('Error adding to wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
/**
* Remove a product from the authenticated user's wishlist
*/
export const removeFromWishlist = async (req: Request, res: Response) => {
const userId = req.user.id;
const { product_id } = req.body;
if (!product_id) {
return res.status(400).json({ message: 'Product ID is required' });
}
try {
const deleteQuery = `
DELETE FROM wishlist
WHERE user_id = $1 AND product_id = $2
RETURNING *
`;
const { rows } = await pool.query(deleteQuery, [userId, product_id]);
if (rows.length === 0) {
return res.status(404).json({ message: 'Wishlist item not found' });
}
res.status(200).json({ message: 'Product removed from wishlist', wishlistItem: rows[0] });
} catch (error) {
console.error('Error removing from wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
Explanation:
- Error Handling: Each controller function handles potential errors by using try-catch blocks and responding with appropriate HTTP status codes and messages.
getWishlist:
- Retrieves all wishlist items for the authenticated user.
- Joins the
wishlist and products tables to fetch detailed product information.
addToWishlist:
- Inserts a new wishlist entry.
- Uses
ON CONFLICT to prevent duplicate entries (UNIQUE constraint in the table).
- Responds with a
409 Conflict if the product is already in the wishlist.
removeFromWishlist:
- Deletes a specific product from the user's wishlist.
- Returns a
404 Not Found if the wishlist item doesn't exist.
3. Connecting Controllers with Routes
You've already set up the wishlist routes. Ensure they correctly use the controller functions.
wishlistRoutes.js
// routes/wishlistRoutes.js
import express from 'express';
import { isAuthenticated } from '../middleware/isAuthenticated';
import {
getWishlist,
addToWishlist,
removeFromWishlist
} from '../controllers/wishlistController';
const router = express.Router();
// GET /wishlist - Retrieve user's wishlist
router.get('/', isAuthenticated, getWishlist);
// POST /wishlist - Add a product to wishlist
router.post('/', isAuthenticated, addToWishlist);
// DELETE /wishlist - Remove a product from wishlist
router.delete('/', isAuthenticated, removeFromWishlist);
export default router;
Usage Example:
- Get Wishlist:
GET /wishlist
- Add to Wishlist:
POST /wishlist with JSON body { "product_id": 123 }
- Remove from Wishlist:
DELETE /wishlist with JSON body { "product_id": 123 }
4. Handling Product Deletion Cascades
As defined in the database schema, the ON DELETE CASCADE constraint ensures that when a product is deleted from the products table, all corresponding entries in the wishlist table are automatically removed. This maintains referential integrity without additional application logic.
No Additional Code Needed:
The ON DELETE CASCADE in the foreign key constraint handles the deletion automatically. However, ensure that your application logic accounts for cases where products might no longer exist when retrieving wishlists.
5. Database Connection Setup
Ensure that your application can connect to the PostgreSQL database. Here's a basic setup using environment variables for configuration.
.env File
Create a .env file in the root of your project (ensure it's added to .gitignore to prevent sensitive information from being committed).
DATABASE_URL=postgresql://username:password@localhost:5432/your_database
JWT_SECRET=your_jwt_secret_key
PORT=3000
Security Tip: Never commit your .env file or expose it in any public repositories.
Initializing Environment Variables
Use the dotenv package to load environment variables.
npm install dotenv
app.js or server.js
// app.js or server.js
import express from 'express';
import dotenv from 'dotenv';
import wishlistRoutes from './routes/wishlistRoutes';
// Import other routes as needed
dotenv.config();
const app = express();
// Middleware
app.use(express.json()); // For parsing application/json
// Routes
app.use('/wishlist', wishlistRoutes);
// Use other routes as needed
// Error Handling Middleware (Optional)
app.use((err, req, res, next) => {
console.error('Unhandled Error:', err);
res.status(500).json({ message: 'Internal server error' });
});
// Start the Server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
6. Enhancements and Best Practices
a. Validate product_id
Ensure that the product_id provided exists in the products table before adding it to the wishlist. You can modify addToWishlist to include this validation.
// Inside addToWishlist controller
const productCheckQuery = 'SELECT id FROM products WHERE id = $1';
const productResult = await pool.query(productCheckQuery, [product_id]);
if (productResult.rows.length === 0) {
return res.status(404).json({ message: 'Product not found' });
}
b. Pagination for getWishlist
If users can have large wishlists, consider implementing pagination to limit the number of items returned per request.
// Modify getWishlist to accept query parameters for pagination
export const getWishlist = async (req: Request, res: Response) => {
const userId = req.user.id;
const { page = 1, limit = 20 } = req.query;
const offset = (Number(page) - 1) * Number(limit);
try {
const query = `
SELECT p.id, p.name, p.description, p.price, p.image_url
FROM wishlist w
JOIN products p ON w.product_id = p.id
WHERE w.user_id = $1
ORDER BY w.created_at DESC
LIMIT $2 OFFSET $3
`;
const { rows } = await pool.query(query, [userId, limit, offset]);
res.status(200).json({ wishlist: rows, page: Number(page), limit: Number(limit) });
} catch (error) {
console.error('Error fetching wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
c. Use Transaction Management
For operations that involve multiple database queries, consider using transactions to maintain data integrity.
d. Logging and Monitoring
Implement proper logging (e.g., using winston or morgan) to monitor access and errors effectively.
7. Testing the Wishlist API
It's essential to test your API endpoints to ensure they work as expected.
a. Using Postman or Insomnia
-
Add to Wishlist:
- Method: POST
- URL:
http://localhost:3000/wishlist
- Headers:
Authorization: Bearer <your_jwt_token>
Content-Type: application/json
- Body:
{
"product_id": 1
}
-
Get Wishlist:
- Method: GET
- URL:
http://localhost:3000/wishlist
- Headers:
Authorization: Bearer <your_jwt_token>
-
Remove from Wishlist:
- Method: DELETE
- URL:
http://localhost:3000/wishlist
- Headers:
Authorization: Bearer <your_jwt_token>
Content-Type: application/json
- Body:
{
"product_id": 1
}
b. Automated Testing
Consider writing automated tests using frameworks like Jest and Supertest to ensure your endpoints behave correctly.
Conclusion
By following the above steps, you've successfully implemented a robust Wishlist feature in your Express application with PostgreSQL. This setup ensures data integrity, handles product deletions gracefully, and provides clear and maintainable controller logic. Remember to follow best practices for security, validation, and error handling to create a reliable and user-friendly API.
If you have any further questions or need additional features, feel free to ask!