Skip to content

Commit

Permalink
UPDATE: indentation
Browse files Browse the repository at this point in the history
  • Loading branch information
OfficialSiddharthBisht committed Dec 1, 2022
1 parent b36a9fd commit b957ada
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 65 deletions.
4 changes: 2 additions & 2 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ app.use(cookieParser());
const product = require("./routes/productRoute");
const user = require("./routes/userRoute");

app.use("/api/v1",product);
app.use("/api/v1",user);
app.use("/api/v1", product);
app.use("/api/v1", user);

// Middleware for Errors
app.use(errorMiddleware);
Expand Down
4 changes: 2 additions & 2 deletions controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ exports.createProduct = catchAsyncErrors(async (req, res, next) => {

// Get all products
exports.getAllProducts = catchAsyncErrors(async (req, res) => {

const resultPerPage = 2;
const productCount = await Product.countDocuments();
const apiFeature = new ApiFeatures(Product.find(),req.query).search().filter().pagination(resultPerPage);
const apiFeature = new ApiFeatures(Product.find(), req.query).search().filter().pagination(resultPerPage);
// const products = await Product.find();
const products = await apiFeature.query;

Expand Down
2 changes: 1 addition & 1 deletion middlewares/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ exports.authorizeRoles = (...roles) => {
return next(
new ErrorHandler(
`Role ${req.user.role} is not allowed to access this resource`,
403
403
)
);
}
Expand Down
6 changes: 3 additions & 3 deletions middlewares/catchAsyncErrors.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module.exports = catchAsyncErrors => (req , res ,next) =>{
module.exports = catchAsyncErrors => (req, res, next) => {
Promise
.resolve(catchAsyncErrors(req, res,next))
.catch(next);
.resolve(catchAsyncErrors(req, res, next))
.catch(next);
}
42 changes: 21 additions & 21 deletions models/productModels.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,44 +31,44 @@ const productSchema = new mongoose.Schema({
}
}
],
categories : {
type : String,
required : [true, "Please enter product category"],
categories: {
type: String,
required: [true, "Please enter product category"],
},
stock : {
type : Number,
required : [true, "Please enter product stock"],
stock: {
type: Number,
required: [true, "Please enter product stock"],
maxLength: [5, "Product stock cannot exceed ten thousand"],
default : 0,
default: 0,
},
numOfReviews : {
type : Number,
default : 0,
numOfReviews: {
type: Number,
default: 0,
},
reviews : [
reviews: [
{
name : {
type : String,
name: {
type: String,
required: true,
},
rating :{
type : Number,
required :true,
rating: {
type: Number,
required: true,
},
comment: {
type: String,
}
}
],
user:{
user: {
type: mongoose.Schema.ObjectId,
ref: "User",
required: true,
},
createdAt : {
type :Date,
default : Date.now,
createdAt: {
type: Date,
default: Date.now,
}
});

module.exports = mongoose.model("Product",productSchema);
module.exports = mongoose.model("Product", productSchema);
14 changes: 7 additions & 7 deletions models/userModels.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,27 +50,27 @@ userSchema.pre("save", async function (next) {
})

// Jwt Token
userSchema.methods.getJWTToken =async function () {
userSchema.methods.getJWTToken = async function () {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRE
})
}

// Compare Password
userSchema.methods.comparePassword = async function(enteredPassword){
return await bcrypt.compare(enteredPassword,this.password);
userSchema.methods.comparePassword = async function (enteredPassword) {
return await bcrypt.compare(enteredPassword, this.password);
}

// Password reset token generate
userSchema.methods.getResetPasswordToken = function(){
userSchema.methods.getResetPasswordToken = function () {
// Generating Token
const resetToken = crypto.randomBytes(25).toString("hex");

// Hashing and adding to userSchema
this.resetPasswordToken = crypto
.createHash("sha256")
.update(resetToken)
.digest("hex");
.createHash("sha256")
.update(resetToken)
.digest("hex");

this.resetPasswordExpire = Date.now() + 15 * 60 * 1000;

Expand Down
11 changes: 6 additions & 5 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,32 @@ const dotenv = require("dotenv");
const connectDatabase = require("./config/database");

// Handling Uncaught Exception (using a variable which is not defined)
process.on("uncaughtException",(err)=>{
process.on("uncaughtException", (err) => {
console.log(`Error ${err.message}`);
console.log(`Shutting down the server due to uncaught exception`);
process.exit(1);
})

// config
dotenv.config({path : "./config/config.env"});
dotenv.config({ path: "./config/config.env" });

// Connect Database
connectDatabase();


const server = app.listen(process.env.PORT,()=>{
const server = app.listen(process.env.PORT, () => {
console.log(`Server is running on port ${process.env.port}`);
})


// Unhandled promise rejection (eg :- mongo instead of mongodb)
// in these cases we have to crash our own server asap

process.on("unhandledRejection",err=>{
process.on("unhandledRejection", err => {
console.log(`Error : ${err.message}`);
console.log(`Shutting down the server due to unhandled promise rejection`);

server.close(()=>{
server.close(() => {
process.exit(1);
})
})
30 changes: 15 additions & 15 deletions utils/apiFeatures.js
Original file line number Diff line number Diff line change
@@ -1,42 +1,42 @@
class ApiFeatures{
constructor(query, queryStr){
class ApiFeatures {
constructor(query, queryStr) {
this.query = query;
this.queryStr = queryStr;
}

// Search Feature
search(){
search() {
const keyword = this.queryStr.keyword ? {
name : {
$regex:this.queryStr.keyword,
$options : "i", //Case insensitive M and m are same
name: {
$regex: this.queryStr.keyword,
$options: "i", //Case insensitive M and m are same
}
} : {};
this.query = this.query.find({...keyword});

this.query = this.query.find({ ...keyword });
return this;
}

// filter feature
filter(){
filter() {
// const queryCopy = this.queryStr
// this will take the exact reference , changing one will change the other too, so we will use spread operator
const queryCopy = {...this.queryStr};
const queryCopy = { ...this.queryStr };
// Removing some fields for category
const removeFields = ["keyword","page","limit"];
removeFields.forEach(key=> delete queryCopy[key]);
const removeFields = ["keyword", "page", "limit"];
removeFields.forEach(key => delete queryCopy[key]);

// Filter for price and rating
let queryStr = JSON.stringify(queryCopy);
queryStr = queryStr.replace(/\b(gt|gte|lt|lte)\b/g,key => `$${key}`);
queryStr = queryStr.replace(/\b(gt|gte|lt|lte)\b/g, key => `$${key}`);

this.query = this.query.find(JSON.parse(queryStr));
return this;
}
// categories can be case sensitive cauz user will not search for the category he/she will choose from the given ones

// Pagination
pagination(resultPerPage){
pagination(resultPerPage) {
const currentPage = Number(this.queryStr.page) || 1;
const skip = resultPerPage * (currentPage - 1);

Expand Down
4 changes: 2 additions & 2 deletions utils/errorHandler.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
class ErrorHandler extends Error{
constructor(message,statusCode){
class ErrorHandler extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;

Expand Down
4 changes: 2 additions & 2 deletions utils/jwtToken.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//Creating Token and saving in cookie

const sendToken = async(user, statusCode, res) =>{
const sendToken = async (user, statusCode, res) => {
const token = await user.getJWTToken();

// options for cookie
Expand All @@ -10,7 +10,7 @@ const sendToken = async(user, statusCode, res) =>{
),
httpOnly: true,
};
res.status(statusCode).cookie('token',token,options).json({
res.status(statusCode).cookie('token', token, options).json({
success: true,
user,
token,
Expand Down
10 changes: 5 additions & 5 deletions utils/sendEmail.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
const nodemailer = require("nodemailer");

const sendEmail = async(options) =>{
const sendEmail = async (options) => {
const transporter = nodemailer.createTransport({
host : "smtp.gmail.com",
host: "smtp.gmail.com",
port: 465,
service: process.env.SMTP_SERVICE,
secure: true,
auth: {
user :process.env.SMTP_MAIL,
user: process.env.SMTP_MAIL,
pass: process.env.SMTP_PASSWORD,
}
})
const mailOptions = {
from : process.env.SMTP_MAIL,
from: process.env.SMTP_MAIL,
to: options.email,
subject : options.subject,
subject: options.subject,
text: options.message,
};
await transporter.sendMail(mailOptions);
Expand Down

0 comments on commit b957ada

Please sign in to comment.