Skip to content

Commit

Permalink
Merge pull request #98 from atlp-rwanda/187967401-fix-get-products-by…
Browse files Browse the repository at this point in the history
…-seller

fix-get-products-by-seller
  • Loading branch information
niyontwali authored Jul 17, 2024
2 parents 4cf7555 + 72f7b68 commit 7b48f89
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 9 deletions.
39 changes: 34 additions & 5 deletions src/controllers/productsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import OrderItems from '../database/models/orderItems';
export const createProduct = async (req: Request, res: Response) => {
const transaction = await sequelize.transaction();
try {
const { categoryId, name, description, colors, sizes } = req.body as ProductAttributes & {
const { categoryName, name, description, colors, sizes } = req.body as ProductAttributes & {
sizes: SizeAttributes[];
};
const seller = (await req.user) as User;
Expand Down Expand Up @@ -56,13 +56,13 @@ export const createProduct = async (req: Request, res: Response) => {

// Create product
const product = await Product.create(
{ sellerId, name, description, categoryId, colors, images: productImages },
{ sellerId, name, description, categoryName, colors, images: productImages },
{ transaction }
);

// Create sizes
if (sizes || sizes.length > 0) {
for (const sizeData of sizes) {
for (const sizeData of JSON.parse(sizes)) {
await Size.create({ ...sizeData, productId: product.id }, { transaction });
}
}
Expand Down Expand Up @@ -278,12 +278,42 @@ export const getAllProduct = async (req: Request, res: Response) => {
}
};

// Function to get all products by a particular seller
export const getAllProductsBySeller = async (req: Request, res: Response): Promise<void> => {
try {
const { sellerId } = req.params;

if (!sellerId) {
res.status(400).json({ error: 'Invalid sellerId' });
return;
}

const products = await Product.findAll({
where: {
sellerId,
},
attributes: ['id', 'name', 'description', 'images', 'categoryName'], // Select only necessary fields
order: [['createdAt', 'DESC']],
});

res.status(200).json({
ok: true,
data: products,
});
} catch (error) {
sendInternalErrorResponse(res, error);
}
};

// a function to get a certain product by ID
export const getProductById = async (req: Request, res: Response) => {
try {
const { productId } = req.params;
const product = await Product.findByPk(productId, {
include: [{ model: Size, as: 'sizes' },{ model: Review, as: 'reviews', include: [{ model: User, as: 'user', attributes: ['photoUrl', 'firstName'] }] },],
include: [
{ model: Size, as: 'sizes' },
{ model: Review, as: 'reviews', include: [{ model: User, as: 'user', attributes: ['photoUrl', 'firstName'] }] },
],
});

if (!product) {
Expand Down Expand Up @@ -514,4 +544,3 @@ export const calculateAverageRating = async (req: Request, res: Response) => {
sendInternalErrorResponse(res, error);
}
};

28 changes: 28 additions & 0 deletions src/database/migrations/20240717004630-update-product-attribute.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
// Rename the column
await queryInterface.renameColumn(
'products',
'categoryId',
'categoryName',
{
type: Sequelize.STRING,
}
);
},

async down(queryInterface, Sequelize) {
// Revert the change in case of rollback
await queryInterface.renameColumn(
'products',
'categoryName',
'categoryId',
{
type: Sequelize.STRING,
}
);
},
};
8 changes: 4 additions & 4 deletions src/database/models/Product.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export interface ProductAttributes {
description: string;
images: string[];
colors?: string[];
categoryId: string;
categoryName: string;
sizes?: any;
createdAt?: Date;
updatedAt?: Date;
Expand All @@ -23,7 +23,7 @@ export class Product extends Model<ProductAttributes> implements ProductAttribut
public sellerId!: string;
public name!: string;
public description!: string;
public categoryId!: string;
public categoryName!: string;
public images!: string[];
public colors!: string[];
public sizes!: any;
Expand Down Expand Up @@ -65,7 +65,7 @@ Product.init(
onUpdate: 'CASCADE',
allowNull: false,
},
categoryId: {
categoryName: {
type: DataTypes.UUID,
references: {
model: 'Category',
Expand All @@ -76,6 +76,6 @@ Product.init(
{ sequelize: sequelize, timestamps: true, modelName: 'Product', tableName: 'products' }
);

Product.belongsTo(Category, { foreignKey: 'categoryId' });
Product.belongsTo(Category, { foreignKey: 'categoryName' });
Product.belongsTo(User, { foreignKey: 'sellerId', as: 'user' });
Product.hasMany(Size, { foreignKey: 'productId', as: 'sizes' });
2 changes: 2 additions & 0 deletions src/routes/productRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
provideReviewToProduct,
calculateAverageRating,
deleteReview,
getAllProductsBySeller,
} from '../controllers/productsController';
import multerUpload from '../helpers/multer';
import { checkUserRoles, isAuthenticated } from '../middlewares/authMiddlewares';
Expand Down Expand Up @@ -43,5 +44,6 @@ router.put('/:sizeId/unavailable', isAuthenticated, checkUserRoles('seller'), ma
router.post('/:productId/review/', isAuthenticated, multerUpload.single('feedbackImage'), provideReviewToProduct);
router.delete('/:productId/review/:reviewId', isAuthenticated, deleteReview);
router.get('/:productId/review/statistics', calculateAverageRating);
router.get('/seller-products/:sellerId', isAuthenticated, checkUserRoles('seller'), getAllProductsBySeller);

export default router;

0 comments on commit 7b48f89

Please sign in to comment.