Create wishlist table in postgresql that contain two columns user_id and product_id user_id references to users table user_id column and product_id references to products table id column
handle the case when the product is deleted... it should be deleted in the wishlist as well...
Then in express create a controller to get all product ids from the wishlist for the user, edit and delete product from wishlist...
btw I'm using Bearer JWT.
import {NextFunction, Request, Response} from 'express';
import jwt from 'jsonwebtoken';
interface DecodedToken {
id: number;
userId: number;
name: string;
active: boolean;
email: string;
role: string;
phone_number: string;
dob?: string; // Optional, as it might not be present for all users
}
Sure! I'll guide you through creating the PostgreSQL wishlist table and implementing the corresponding Express controllers to manage the wishlist functionality. We'll cover:
PostgreSQL Table Creation
Express Controllers Implementation
Additional Setup and Considerations
1. PostgreSQL Table Creation
First, let's create the wishlist table in PostgreSQL with the required constraints:
Columns:
user_id: References the user_id column in the users table.
product_id: References the id column in the products table.
Constraints:
Foreign Key Constraints with ON DELETE CASCADE to ensure that if a user or product is deleted, the corresponding wishlist entries are automatically removed.
Primary Key on the combination of user_id and product_id to prevent duplicate entries.
SQL Script
sql
CREATE TABLE wishlist (
user_id INTEGER NOT NULL,
product_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, product_id),
FOREIGN KEY (user_id) REFERENCES users(user_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(id) ON DELETE CASCADE
);
Explanation:
user_id INTEGER NOT NULL: Stores the ID of the user.
product_id INTEGER NOT NULL: Stores the ID of the product.
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP: (Optional) Tracks when the wishlist entry was created.
PRIMARY KEY (user_id, product_id): Ensures that each user-product pair is unique.
FOREIGN KEY Constraints: Ensures referential integrity and handles deletions:
ON DELETE CASCADE: Automatically removes wishlist entries if the referenced user or product is deleted.
2. Express Controllers Implementation
Next, we'll implement the Express controllers to handle wishlist operations: fetching, adding, and removing products from the wishlist.
Prerequisites
Database Connection: We'll use the pg library to interact with PostgreSQL. Ensure you have it installed:
bash
npm install pg
Environment Variables: Ensure you have the following environment variables set for database connection and JWT secret:
DATABASE_URL: PostgreSQL connection string.
JWT_SECRET: Secret key for JWT verification.
TypeScript Declarations: Extend the Express Request interface to include the user property set by the isAuthenticated middleware.
Extending Express Request Interface
Create a types.d.ts file (if not already present) to extend the Request interface:
Ensure this file is included in your tsconfig.json under the include array.
Database Configuration
Create a db.ts file to set up the PostgreSQL client:
typescript
// db.ts
import { Pool } from 'pg';
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
export default pool;
Wishlist Controller
Create a wishlistController.ts file with the following content:
typescript
// controllers/wishlistController.ts
import { Request, Response } from 'express';
import pool from '../db'; // Adjust the path as necessary
// Fetch all product IDs from the user's wishlist
export const getWishlist = async (req: Request, res: Response) => {
const userId = req.user?.userId;
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
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
`;
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 user's wishlist
export const addToWishlist = async (req: Request, res: Response) => {
const userId = req.user?.userId;
const { product_id } = req.body;
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
if (!product_id) {
return res.status(400).json({ message: 'Product ID is required' });
}
try {
const query = `
INSERT INTO wishlist (user_id, product_id)
VALUES ($1, $2)
ON CONFLICT (user_id, product_id) DO NOTHING
`;
await pool.query(query, [userId, product_id]);
res.status(201).json({ message: 'Product added to wishlist' });
} catch (error) {
console.error('Error adding to wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
// Remove a product from the user's wishlist
export const removeFromWishlist = async (req: Request, res: Response) => {
const userId = req.user?.userId;
const { product_id } = req.body;
if (!userId) {
return res.status(400).json({ message: 'User ID not found in token' });
}
if (!product_id) {
return res.status(400).json({ message: 'Product ID is required' });
}
try {
const query = `
DELETE FROM wishlist
WHERE user_id = $1 AND product_id = $2
`;
const result = await pool.query(query, [userId, product_id]);
if (result.rowCount === 0) {
return res.status(404).json({ message: 'Product not found in wishlist' });
}
res.status(200).json({ message: 'Product removed from wishlist' });
} catch (error) {
console.error('Error removing from wishlist:', error);
res.status(500).json({ message: 'Internal server error' });
}
};
Explanation:
getWishlist:
Retrieves all products in the authenticated user's wishlist.
Joins the wishlist and products tables to fetch detailed product information.
Returns the wishlist as an array of product objects.
addToWishlist:
Adds a new product to the user's wishlist.
Uses ON CONFLICT DO NOTHING to prevent duplicate entries based on the primary key (user_id, product_id).
Returns a success message upon addition.
removeFromWishlist:
Removes a specific product from the user's wishlist.
Checks if the deletion was successful; if not, returns a 404 error indicating that the product wasn't found in the wishlist.
Returns a success message upon removal.
Handling JWT and User Authentication
Ensure your isAuthenticated middleware correctly sets the req.user object. As you've provided, the middleware should decode the JWT and attach the user information to the request.
Wishlist Routes
Ensure your wishlistRoutes.ts is correctly set up to use these controllers. Based on your snippet, it should look like this:
In your main server file (e.g., app.ts or server.ts), make sure to use the wishlist routes:
typescript
// app.ts
import express from 'express';
import wishlistRoutes from './routes/wishlistRoutes'; // Adjust the path as necessary
const app = express();
// Middleware
app.use(express.json()); // For parsing application/json
// Routes
app.use('/api/wishlist', wishlistRoutes);
// Error Handling Middleware (Optional)
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// Start the Server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
3. Additional Setup and Considerations
Input Validation
It's a good practice to validate incoming data to ensure that product_id is a valid integer and that the product exists before adding it to the wishlist. You can enhance the controllers with additional checks as needed.
Security Considerations
Authorization: Ensure that users can only modify their own wishlist. Since we're using the userId from the JWT, this should inherently be enforced.
Rate Limiting: Implement rate limiting to prevent abuse of the wishlist endpoints.
Testing the Endpoints
You can use tools like Postman or Insomnia to test the wishlist endpoints. Ensure you include the Authorization header with a valid Bearer JWT.
Example Requests:
Get Wishlist:
Method: GET
URL: /api/wishlist/
Headers: Authorization: Bearer <your_jwt_token>
Add to Wishlist:
Method: POST
URL: /api/wishlist/
Headers: Authorization: Bearer <your_jwt_token>
Body (JSON):
json
{
"product_id": 123
}
Remove from Wishlist:
Method: DELETE
URL: /api/wishlist/
Headers: Authorization: Bearer <your_jwt_token>
Body (JSON):
json
{
"product_id": 123
}
Error Handling Enhancements
For a more robust application, consider implementing centralized error handling and possibly using a validation library like Joi or express-validator to handle request validations.
By following the above steps, you should have a fully functional wishlist feature integrated into your PostgreSQL and Express application, complete with JWT-based authentication and proper handling of related deletions.