Skip to content

First one for demo#7

Open
SyedArshikJavedMoinee wants to merge 19 commits into
mainfrom
testingSummary
Open

First one for demo#7
SyedArshikJavedMoinee wants to merge 19 commits into
mainfrom
testingSummary

Conversation

@SyedArshikJavedMoinee
Copy link
Copy Markdown
Collaborator

No description provided.

router.post('/signup', userSignupValidator, signup);
router.post('/signin', signin);
router.get('/signout', signout);
router.get("/forget-password", forgetPassword);
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The forgetPassword function is not imported or defined in this file. It should be imported from the controllers/auth file or defined in this file.

Comment thread mern-ecommerce/routes/auth.js Outdated
router.post('/signup', userSignupValidator, signup);
router.post('/signin', signin);
router.get('/signout', signout);
router.get('/signout', signouts);
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function signouts is not defined in the provided context. It seems like it should be signout instead of signouts.

Comment thread mern-ecommerce/server.js
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
useFindAndModiify: false,
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue here is a typo in the option name. It should be useFindAndModify instead of useFindAndModiify. The correct line should be useFindAndModify: false.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@CodeHawk what do you mean? Care to explain further on this?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You have a typo in the option name. It should be useFindAndModify instead of useFindAndModiify.

Comment thread mern-ecommerce/server.js
}
};
connectDB();
connectdb();
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function call connectdb(); should be connectDB(); to match the function definition const connectDB = async () => { ... }. The function name is case-sensitive, and JavaScript will throw a ReferenceError if it cannot find a function with the exact name.

Comment thread mern-ecommerce/server.js

// routes middleware
app.use("/api", authRoutes);
app.use("/api", authRoutess);
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code snippet has a typo in the route name. It should be authRoutes instead of authRoutess.

trim: true,
required: true,
maxlength: 32,
maxlength: 3,
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The maxlength property is set to 3, which is an unusual value for a name field. Typically, names can be longer than 3 characters. It's recommended to increase this value or remove it altogether to allow for more flexibility in user input.

category: {
type: ObjectId,
ref: 'Category',
ref: 'Categoryy',
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The issue here is a typo in the reference model name. It should be 'Category' instead of 'Categoryy'. This could lead to a mismatch when trying to populate the category field in the product model.

},
quantity: {
type: Number,
type: Numberr,
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo in 'Numberr', it should be 'Number'.

Comment thread mern-ecommerce/Dockerfile Outdated
@@ -1,6 +1,6 @@
FROM node:18-alpine
FROM nodes:18-alpine
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Dockerfile instruction 'FROM nodes:18-alpine' should be 'FROM node:18-alpine'. The official Node.js Docker image is named 'node', not 'nodes'.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@CodeHawk can you back your comment with some example, please?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's an example: if you run docker images with the incorrect instruction, you'll get an error saying "repository nodes not found". On the other hand, FROM node:18-alpine will correctly pull the official Node.js image from Docker Hub.

Comment thread mern-ecommerce/Dockerfile Outdated
COPY . .
RUN npm install
CMD ["node", "server.js"] No newline at end of file
CMD ["nodes", "server.js"] No newline at end of file
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The command CMD ["nodes", "server.js"] should be CMD ["node", "server.js"]. The Docker image is based on nodes:18-alpine, but the command to run the server should use node, not nodes.

exports.processPayment = (req, res) => {
let nonceFromTheClient = req.body.paymentMethodNonce;
let amountFromTheClient = req.body.amount;
let nonceFromTheClient = request.body.paymentMethodNonce;
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable 'request' is not defined in the scope of the 'exports.processPayment' function. It should be 'req' instead of 'request'.

let nonceFromTheClient = req.body.paymentMethodNonce;
let amountFromTheClient = req.body.amount;
let nonceFromTheClient = request.body.paymentMethodNonce;
let amountFromTheClient = request.body.amount;
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable request is not defined in this scope. It should be req instead of request.

exports.isAuth = (req, res, next) => {
let user = req.profile && req.auth && req.profile._id == req.auth._id;
if (!user) {
exports.isAdmin = (req, res, next) => {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The isAdmin function is checking if the user's role is 0, but it's not clear what role 0 represents. It would be better to define a constant for the admin role and use that instead of a magic number. This would make the code more readable and maintainable.

Additionally, the error message 'Admin resource!' is incomplete. It would be better to provide a more descriptive error message, such as 'Access denied. You are not an admin.'

Comment thread mern-ecommerce/controllers/auth.js Outdated
let user = req.profile && req.auth && req.profile._id == req.auth._id;
if (!user) {
exports.isAdmin = (req, res, next) => {
if (req.profile.role === 0) {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the isAdmin function, the role check is hardcoded to 0. This might not be flexible or scalable. Consider defining the admin role in a constants file or environment variable to make it easily configurable.

if (req.profile.role === 0) {
return res.status(403).json({
error: 'Access denied',
error: 'Admin resource! Access denied',
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error message consistency: The error message 'Admin resource! Access denied' is not consistent with the error messages in the rest of the code. It would be better to use a similar format and structure for all error messages throughout the code.


exports.isAdmin = (req, res, next) => {
if (req.profile.role === 0) {
exports.isAuth = (req, res, next) => {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The isAuth middleware function seems to be checking if the user is authenticated by verifying the _id of the req.profile and req.auth. However, there is no validation or check to ensure that req.profile and req.auth exist before trying to access their _id properties. This could lead to a runtime error if either of these properties is undefined.

Additionally, it would be better to use a more explicit check for the existence of req.profile and req.auth before trying to access their properties. This can be done using the && operator or the optional chaining operator (?.) introduced in JavaScript.

For example:

let user = req.profile?.&_id === req.auth?.&_id;

This will prevent any runtime errors and make the code more robust.

exports.isAdmin = (req, res, next) => {
if (req.profile.role === 0) {
exports.isAuth = (req, res, next) => {
let user = req.profile && req.auth && req.profile._id == req.auth._id;
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The condition let user = req.profile && req.auth && req.profile._id == req.auth._id; is not null-safe. It will throw an error if req.profile or req.auth is null or undefined. Consider using optional chaining (?.) or a null check before accessing properties.

if (req.profile.role === 0) {
exports.isAuth = (req, res, next) => {
let user = req.profile && req.auth && req.profile._id == req.auth._id;
if (!user) {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The condition if (!user) is not checking if the user is authenticated or not. It's only checking if the user variable is truthy or falsy. It would be better to check if the user is authenticated by verifying the existence of a valid token or session. Additionally, this condition is present in multiple places in the code, it would be better to create a utility function to handle this check.

if (!user) {
return res.status(403).json({
error: 'Admin resource! Access denied',
error: 'Access denied',
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error message 'Access denied' is not internationalized. It would be better to use a translation function or a separate file for error messages to make the application more scalable and maintainable.

});
};

exports.deleteUser = (req, res) => {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The deleteUser function is missing a JSON response object in the error handling block. It should be:

return res.status(400).json({
  error: 'User not found',
});

Instead of just return res.status(400)..


exports.signout = (req, res) => {
res.clearCookie('t');
res.clearcookie('t');
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method name is clearcookie but it should be clearCookie. It's a typo. It should be res.clearCookie('t');.

let user = req.profile && req.auth && req.profile._id == req.auth._id;
if (!user) {
exports.isAdmin = (req, res, next) => {
if (req.profile.rolee === 0) {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a typo in the code. It should be role instead of rolee. The correct line should be if (req.profile.role === 0) {.

router.get('/user/:userId', requireSignin, isAuth, read);
router.put('/user/:userId', requireSignin, isAuth, update);
router.get('/orders/by/user/:userId', requireSignin, isAuth, purchaseHistory);
router.put('/user/:userId', requireSignin, isAuth, updatee);
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a typo in the code. The function name is update but it's called as updatee. It should be corrected to update.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@CodeHawk Can you please further clarify on your review in simple terms?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You've got a small typo in the code. The function name is update, but you're calling it as updatee. It should be corrected to update.

@@ -0,0 +1,17 @@
const Store = require('../models/store');
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The relative path in the code snippet is incorrect. It should be ./models/store instead of ../models/store. The correct code should be:

const Store = require('./models/store');

This is because the require function is being called from a file in the same directory as the models folder, not from a parent directory.

const { Order } = require('../models/order');
const { errorHandler } = require('../helpers/dbErrorHandler');

exports.getAllStores = (req, res) => {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the review:

In line 3, the error message "An error occurred" is not very informative. It would be better to send a more descriptive error message or the actual error itself. Consider using res.status(400).send(err.message) instead.

In lines 5-8, the code is manually iterating over the stores array to create a new storeList array. This can be simplified using Array.prototype.map() method, like this: const storeList = stores.map(store => ({ id: store._id, name: store.name, description: store.description }));.

The function getAllStores is not handling the case where stores is null or undefined. It would be better to add a null check before iterating over the array.

The function getAllStores is not following a consistent naming convention. The variable names are in camelCase, but the property names in the storeList objects are in PascalCase. It would be better to stick to a single convention throughout the code.

const { errorHandler } = require('../helpers/dbErrorHandler');

exports.getAllStores = (req, res) => {
Store.find({}, function(err, stores) {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the review:

In the getAllStores function, the error handling is not consistent with the rest of the codebase. In other parts of the code, errors are handled by returning a JSON response with an error message, but in this function, a plain text response is sent. It would be better to handle errors consistently throughout the codebase. For example, you could return res.status(400).json({ error: 'An error occurred' }); instead of res.status(400).send("An error occurred");.

Comment thread mern-ecommerce/controllers/store.js Outdated
exports.getAllStores = (req, res) => {
Store.find({}, function(err, stores) {
if (err) {
res.status(400).send("An error occurred");
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This line of code is not following the error handling pattern used throughout the rest of the codebase. It should be consistent with the other error handling mechanisms. Instead of sending a generic "An error occurred" message, it should use the errorHandler function to handle the error and return a JSON response with the error details.

Suggested change:
return res.status(400).json({ error: errorHandler(err) });

description: {
type: String,
required: true,
maxlength: 2000
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The maxlength property in the storeSchema is set to 2000, but it's not clear why this specific value was chosen. It would be better to define a constant or a configurable variable for this value, rather than hardcoding it. Additionally, it's not clear what the maximum allowed length for the description field should be, and whether 2000 is a reasonable limit. It would be helpful to add a comment explaining the reasoning behind this choice.

ref: 'Category',
required: true
},
owner: {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the storeSchema definition, the owner field is defined as an ObjectId reference to the 'User' model. However, it's not clear why the owner field is required. It would be better to add a comment explaining why this field is required. Additionally, it would be good to consider adding validation for the owner field to ensure it's a valid user ID.

},
created: {
type: Date,
default: Date.now
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the created field of the storeSchema, the default value is set to Date.now. This is not a function, it's a property that returns the current timestamp. To set the default value to the current timestamp, it should be a function that returns the current timestamp.

Suggested Fix:
Change default: Date.now to default: Date.now() or default: () => Date.now().

requireSignin,
isAuth,
isAdmin,
getAllStores
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The getAllStores function in store.js is not following the consistent error handling pattern used in other parts of the code. In other controllers, error handling is done using errorHandler from dbErrorHandler, but in getAllStores, a generic error message "An error occurred" is sent. It would be better to use errorHandler here as well to maintain consistency and provide more informative error messages.

Comment thread mern-ecommerce/controllers/store.js Outdated
if (err) {
res.status(400).send("An error occurred");
} else {
let storeLists = [];
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable storeLists is declared but not used. It should be renamed to storeList to match the variable used in the code. Additionally, it's not necessary to declare an empty array, as it's immediately overwritten in the loop. It can be directly declared and initialized in the loop.

exports.getAllStores = (req, res) => {
Store.find({}, function(err, stores) {
if (err) {
res.status(500).send("An error occured"); // Incorrect error message spelling and incorrect status code
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the review:

res.status(500).send("An error occured");

  • The error message "An error occured" has a typo, it should be "An error occurred".
  • The status code 500 is correct for an internal server error, but the error message should be more descriptive to provide better feedback to users or developers.
  • Consider using res.status(500).json({ error: 'Internal Server Error' }); instead to maintain consistency with other error responses in the repository.

if (err) {
res.status(500).send("An error occured"); // Incorrect error message spelling and incorrect status code
} else {
let storeLists = []; // Incorrect variable name, should be storeList
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The variable name storeLists should be corrected to storeList for consistency and clarity. This change will help maintain uniformity in variable naming conventions throughout the codebase.

} else {
let storeLists = []; // Incorrect variable name, should be storeList
for (let i = 0; i < stores.length; i++) {
storeList.push({id: stores[i]._id, name: stores[i].name}); // Missing description field and incorrect variable name
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the review:

storeList should be storeLists for consistency and clarity.

The object being pushed to the array is missing the description field, which is a required field in the storeSchema. It should be included to provide additional information about each store.

Consider using a more concise way to construct the storeLists array, such as using map() or forEach() instead of a for loop.

for (let i = 0; i < stores.length; i++) {
storeList.push({id: stores[i]._id, name: stores[i].name}); // Missing description field and incorrect variable name
}
res.json(storeList); // Inconsistent response method (should be res.send to match the original)
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent response method used. Should be res.send(storeList) to match the original response method used in the code snippet. This inconsistency could lead to confusion and maintenance challenges in the future.

Comment thread mern-ecommerce/controllers/store.js Outdated

exports.addStore = (req, res) => {
const newStore = new Store(req.body);
newStore.save((err, store) => {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing closing parenthesis for the newStore.save method. This could potentially lead to syntax errors and cause the code to malfunction.

exports.addStore = (req, res) => {
const newStore = new Store(req.body);
newStore.save((err, store) => {
if (err) {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent error handling. The error status code should be 400 instead of 500, and the error message should be more descriptive. It's also recommended to use a consistent error handling approach throughout the codebase, such as using the errorHandler function from the dbErrorHandler module.

Comment thread mern-ecommerce/controllers/store.js Outdated
const newStore = new Store(req.body);
newStore.save((err, store) => {
if (err) {
res.status(500).send("Failed to add store");
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent response method: This line uses res.send in other parts of the code, but here it uses res.json. For consistency, it should be changed to res.send.

Incorrect error message: The error message "Failed to add store" is too generic. It would be better to provide more specific information about the error, such as the actual error message from the database.

Missing error logging: There is no error logging mechanism in place. It would be beneficial to log the error for further investigation and debugging purposes.

Inconsistent status code: The status code 500 is used, but in other parts of the code, a more specific status code is used. It would be better to use a more specific status code, such as 422, to indicate that the request was well-formed but unable to be processed.

Comment thread mern-ecommerce/controllers/store.js Outdated
if (err) {
res.status(500).send("Failed to add store");
} else {
res.send({ message: "Store added successfully", storeId: store._id });
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent response method: This line uses res.send whereas the error handling in the same function uses res.status(500).send. For consistency, it should be res.status(201).send to indicate a successful creation.

}

exports.addStore = (req, res) => {
const newShop = new Store(req.body);
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the review:

Inconsistent naming convention: newShop should be newStore to maintain consistency with the model name Store.


exports.addStore = (req, res) => {
const newShop = new Store(req.body);
newShop.create((err, store) => {
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

newShop.create((err, store) => { should be newShop.save((err, store) => { to correctly create a new document in Mongoose.

The error handling for the creation process is incomplete. It should be handled more robustly, for example, by using a try-catch block or by checking the error object.

The store data being passed to the save method should be validated and sanitized to prevent potential security vulnerabilities.

The response sent back to the client in case of an error should be more informative and follow a consistent format throughout the application. In this case, it should be res.status(500).send("Store creation failed"); instead of res.status(200).json("Store creation failed");.

const newShop = new Store(req.body);
newShop.create((err, store) => {
if (err) {
res.status(200).json("Store creation failed");
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent status code. 200 is not an appropriate status code for an error response. It should be 500 to indicate a server error. Additionally, the response message should be an object with an 'error' key and a corresponding message, not a simple string. It should be res.status(500).json({ error: "Store creation failed" });

if (err) {
res.status(200).json("Store creation failed");
} else {
res.json({ alert: "Store added successfully", id: store._id });
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inconsistent response structure. The response object should have a standardized format across all endpoints. Consider using a consistent key for the success message, such as 'message' or 'successMessage', instead of 'alert'. Additionally, it would be beneficial to include a 'data' key to wrap the actual response data, in this case, the 'id' of the newly created store. This would improve clarity and make it easier to handle responses in the frontend or other systems interacting with the API.

res.json({ alert: "Store added successfully", id: store._id });
}
});
}; No newline at end of file
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is the review:

In getAllStores function, the error message "An error occured" has a typo, it should be "An error occurred". Also, the status code should be 400 or 404 instead of 500.

In getAllStores function, the variable name storeLists should be storeList for consistency.

In getAllStores function, the storeList object is missing the description field.

In getAllStores function, the response method should be res.send instead of res.json for consistency.

In addStore function, the status code should be 400 or 500 instead of 200 when the store creation fails.

In addStore function, the response should be res.send instead of res.json for consistency.

The code snippet provided is incomplete, it seems to be part of a larger JavaScript codebase. It's recommended to provide the complete code for a thorough review.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant