Skip to content

product endpoints now working #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 29, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/controllers/attributes.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ class AttributeController {
},
});
if (productAttribute) {
productAttributes.push(productAttribute)
productAttributes.push(productAttribute);
}
}
return res.status(200).json(productAttributes);
Expand Down
242 changes: 216 additions & 26 deletions src/controllers/product.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,13 @@
*/
import {
Product,
ProductCategory,
Review,
Department,
AttributeValue,
Attribute,
Category,
Customer,
Sequelize,
} from '../database/models';

Expand All @@ -46,15 +49,35 @@ class ProductController {
*/
static async getAllProducts(req, res, next) {
const { query } = req;
const { page, limit, offset } = query
// eslint-disable-next-line camelcase
let { page, limit, description_length } = query;
if (!page) {
page = 1;
} else if (page < 1) {
page = 1;
};
if (!limit) {
limit = 20;
}
// eslint-disable-next-line camelcase
if (!description_length) {
// eslint-disable-next-line camelcase
description_length = 200;
}
const offset = Number(page) * Number(limit) - Number(limit);
const maximum = offset + Number(limit);
const sqlQueryMap = {
limit,
offset,
limit: Number(limit),
};
const paginationMeta = {
currentPage: offset,
currentPageSize: limit,
};
try {
const products = await Product.findAndCountAll(sqlQueryMap);
return res.status(200).json({
status: true,
paginationMeta,
products,
});
} catch (error) {
Expand Down Expand Up @@ -92,21 +115,44 @@ class ProductController {
static async getProductsByCategory(req, res, next) {

try {
const { category_id } = req.params; // eslint-disable-line
const products = await Product.findAndCountAll({
const { query, params } = req;
const { category_id } = params; // eslint-disable-line
let { page, limit, description_length } = query;
const offset = Number(page) * Number(limit) - Number(limit);
if (!page) {
page = 1;
} else if (page < 1) {
page = 1;
}
if (!limit) {
limit = 20;
}
const products = await ProductCategory.findAll({
where: {
category_id,
},
include: [
{
model: Department,
where: {
category_id,
},
attributes: [],
model: Product,
as: 'product',
attributes: [
'product_id',
'name',
'description',
'price',
'discounted_price',
'thumbnail',
],
},
],
limit,
raw: true,
attributes: [],
limit: Number(limit),
offset,
});
return next(products);
return res.status(200).json({
rows: products,
});
} catch (error) {
return next(error);
}
Expand All @@ -124,6 +170,65 @@ class ProductController {
*/
static async getProductsByDepartment(req, res, next) {
// implement the method to get products by department
try {
const { query, params } = req;
const { department_id } = params; // eslint-disable-line
let { page, limit, description_length } = query;
const offset = Number(page) * Number(limit) - Number(limit);
if (!page) {
page = 1;
} else if (page < 1) {
page = 1;
}
if (!limit) {
limit = 20;
}
const categoryIDs = await Category.findAll({
where: {
department_id,
},
attributes: ['category_id'],
limit: Number(limit),
offset,
});
const departmentalProducts = [];
const categoriesIDArray = [];
categoryIDs.map(id => categoriesIDArray.push(id.category_id));

// eslint-disable-next-line no-plusplus
for (let i = 0; i < categoriesIDArray.length; i++) {
// eslint-disable-next-line no-await-in-loop
const products = await ProductCategory.findAll({
where: {
category_id: categoriesIDArray[i],
},
include: [
{
model: Product,
as: 'product',
attributes: [
'product_id',
'name',
'description',
'price',
'discounted_price',
'thumbnail',
],
},
],
attributes: [],
});
if (products) {
departmentalProducts.push(products);
}
}

return res.status(200).json({
rows: departmentalProducts,
});
} catch (error) {
return next(error);
}
}

/**
Expand All @@ -137,28 +242,113 @@ class ProductController {
* @memberof ProductController
*/
static async getProduct(req, res, next) {
const { query, params } = req;
// eslint-disable-next-line camelcase
let { description_length } = query;
const { product_id } = params; // eslint-disable-line
try {
const product = await Product.findByPk(product_id);
if (product) {
return res.status(200).json(product);
}
return res.status(404).json({
error: {
status: 404,
message: `Product with id ${product_id} does not exist`, // eslint-disable-line
}
});
} catch (error) {
return next(error);
}
}

/**
* get all reviews for a product
*
* @static
* @param {object} req express request object
* @param {object} res express response object
* @param {object} next next middleware
* @returns {json} json object with status and product data
* @memberof ProductController
*/
static async getProductReviews(req, res, next) {
const { product_id } = req.params; // eslint-disable-line
try {
const product = await Product.findByPk(product_id, {
const reviews = await Review.findAll({
where: {
product_id,
},
include: [
{
model: AttributeValue,
as: 'attributes',
attributes: ['value'],
through: {
attributes: [],
},
include: [
{
model: Attribute,
as: 'attribute_type',
},
],
model: Customer,
as: 'customer',
attributes: ['name'],
},
],
raw: true,
attributes: [],
});
if (reviews) {
return res.status(200).json(reviews);
}
return res.status(404).json({
error: {
status: 404,
message: `Product with id ${product_id} does not exist`, // eslint-disable-line
},
});
} catch (error) {
return next(error);
}
}

/**
* post a product review
*
* @static
* @param {object} req express request object
* @param {object} res express response object
* @param {object} next next middleware
* @returns {json} json object with status and product data
* @memberof ProductController
*/
static async postProductReview(req, res, next) {
const { product_id, review, rating } = req.params; // eslint-disable-line
try {
const product = await Product.findOne({
where: {
product_id,
},
});
if (product) {
// check if the customer had reviewed the product before
const customerReview = await Review.findOne({
where: {
product_id,
customer_id: 1,
},
attributes: ['review_id'],
});

if (!customerReview) {
const productReview = await Review.upsert({
customer_id: 1,
review,
rating,
created_on: Date.now(),
product_id: parseInt(product_id, 10),
});
return res.status(201).send(productReview);
}
return res.status(409).json('You have already reviewed this product.');
}
return res.status(404).json({
error: {
status: 404,
message: `Product with id ${product_id} does not exist`, // eslint-disable-line
},
});
return res.status(500).json({ message: 'This works!!1' });
} catch (error) {
return next(error);
}
Expand Down
1 change: 1 addition & 0 deletions src/database/models/productCategory.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ module.exports = (sequelize, DataTypes) => {
foreignKey: 'product_id',
});
ProductCategory.belongsTo(Category, {
as: 'category',
foreignKey: 'category_id',
});
};
Expand Down
44 changes: 44 additions & 0 deletions src/database/models/review.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
module.exports = (sequelize, DataTypes) => {
const Review = sequelize.define (
'Review',
{
review_id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
customer_id: DataTypes.INTEGER,
product_id: DataTypes.INTEGER,
review: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: '',
},
rating: {
type: DataTypes.SMALLINT,
allowNull: false,
defaultValue: 0,
},
created_on: DataTypes.DATE,
},
{
timestamps: false,
tableName: 'review',
}
);
Review.associate = ({ Product, Customer }) => {
Review.belongsTo(Product, {
foreignKey: 'product_id',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
as: 'product',
});
Review.belongsTo(Customer, {
foreignKey: 'customer_id',
onDelete: 'CASCADE',
onUpdate: 'CASCADE',
as: 'customer',
});
};
return Review;
};
4 changes: 3 additions & 1 deletion src/routes/api/product.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import ProductController from '../../controllers/product.controller';
// These are valid routes but they may contain a bug, please try to define and fix them

const router = Router();
router.get('/products', ProductController.toString);
router.get('/products', ProductController.getAllProducts);
router.get('/products/:product_id', ProductController.getProduct);
router.get('/products/:product_id/reviews', ProductController.getProductReviews);
router.post('/products/:product_id/reviews', ProductController.postProductReview);
router.get('/products/search', ProductController.searchProduct);
router.get('/products/inCategory/:category_id', ProductController.getProductsByCategory);
router.get('/products/inDepartment/:department_id', ProductController.getProductsByDepartment);
Expand Down