Skip to content

Commit

Permalink
formatted recursively with prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
roopeshsn committed Apr 23, 2022
1 parent bcfe164 commit 074ecaf
Show file tree
Hide file tree
Showing 68 changed files with 1,086 additions and 789 deletions.
2 changes: 1 addition & 1 deletion backend/config/db.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const mongoose = require("mongoose")
const mongoose = require('mongoose')

const connectDB = async () => {
try {
Expand Down
7 changes: 6 additions & 1 deletion backend/controllers/carouselControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,9 @@ const updateCarousel = asyncHandler(async (req, res) => {
}
})

module.exports = { getCarousels, getCarouselById, createCarousel, updateCarousel }
module.exports = {
getCarousels,
getCarouselById,
createCarousel,
updateCarousel,
}
17 changes: 13 additions & 4 deletions backend/controllers/orderControllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,21 @@ const Product = require('../models/productModel')
// @route POST /api/orders
// @access Private
const addOrderItems = asyncHandler(async (req, res) => {
const { orderItems, shippingAddress, paymentMethod, itemsPrice, shippingPrice, totalPrice } =
req.body
const {
orderItems,
shippingAddress,
paymentMethod,
itemsPrice,
shippingPrice,
totalPrice,
} = req.body
// Product price validation
orderItems.forEach(async (item) => {
let lookupItem = await Product.findById(item.product)
if (item.price !== lookupItem.price) {
res.status(400)
throw new Error(
'There is a discrepancy between the prices of the items, and whats in the Database, please try again!'
'There is a discrepancy between the prices of the items, and whats in the Database, please try again!',
)
}
})
Expand Down Expand Up @@ -43,7 +49,10 @@ const addOrderItems = asyncHandler(async (req, res) => {
// @route GET /api/orders/:id
// @access Private
const getOrderById = asyncHandler(async (req, res) => {
const order = await Order.findById(req.params.id).populate('user', 'name email')
const order = await Order.findById(req.params.id).populate(
'user',
'name email',
)

if (order && (req.user.isAdmin || order.user._id.equals(req.user._id))) {
res.json(order)
Expand Down
30 changes: 27 additions & 3 deletions backend/controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,16 @@ const deleteProduct = asyncHandler(async (req, res) => {
// @route POST /api/products
// @access Private/Admin
const createProduct = asyncHandler(async (req, res) => {
const { name, price, mrp, description, imageSrc, imageAlt, category, countInStock } = req.body
const {
name,
price,
mrp,
description,
imageSrc,
imageAlt,
category,
countInStock,
} = req.body
console.log(req.user)
const product = new Product({
name,
Expand All @@ -77,7 +86,16 @@ const createProduct = asyncHandler(async (req, res) => {
// @route PUT /api/products/:id
// @access Private/Admin
const updateProduct = asyncHandler(async (req, res) => {
const { name, price, mrp, description, imageSrc, imageAlt, category, countInStock } = req.body
const {
name,
price,
mrp,
description,
imageSrc,
imageAlt,
category,
countInStock,
} = req.body

const product = await Product.findById(req.params.id)

Expand All @@ -99,4 +117,10 @@ const updateProduct = asyncHandler(async (req, res) => {
}
})

module.exports = { getProducts, getProductById, deleteProduct, createProduct, updateProduct }
module.exports = {
getProducts,
getProductById,
deleteProduct,
createProduct,
updateProduct,
}
9 changes: 7 additions & 2 deletions backend/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ const forgotPassword = asyncHandler(async (req, res) => {
const resetToken = user.createPasswordResetToken()
await user.save()

const resetURL = `${req.protocol}://${req.get('host')}/resetpassword/${resetToken}`
const resetURL = `${req.protocol}://${req.get(
'host',
)}/resetpassword/${resetToken}`

const message = `Forgot your password? Create a new password for you account by visiting this URL: ${resetURL}.\nIf you didn't forget your password, please ignore this email!`

Expand All @@ -145,7 +147,10 @@ const forgotPassword = asyncHandler(async (req, res) => {

const resetPassword = asyncHandler(async (req, res) => {
// decrypt token
const hashedToken = crypto.createHash('sha256').update(req.params.token).digest('hex')
const hashedToken = crypto
.createHash('sha256')
.update(req.params.token)
.digest('hex')
const user = await User.findOne({
passwordResetToken: hashedToken,
passwordResetExpires: { $gt: Date.now() },
Expand Down
12 changes: 6 additions & 6 deletions backend/data/users.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
const bcrypt = require("bcryptjs");
const bcrypt = require('bcryptjs')

const users = [
{
name: "Roopesh",
email: "[email protected]",
password: bcrypt.hashSync("123456", 10),
name: 'Roopesh',
email: '[email protected]',
password: bcrypt.hashSync('123456', 10),
isAdmin: true,
},
];
]

module.exports = users;
module.exports = users
5 changes: 4 additions & 1 deletion backend/middleware/authMiddleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ const User = require('../models/userModel')
const protect = asyncHandler(async (req, res, next) => {
let token

if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
try {
token = req.headers.authorization.split(' ')[1]
const decoded = jwt.verify(token, process.env.JWT_SECRET)
Expand Down
2 changes: 1 addition & 1 deletion backend/models/carouselModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const carouselSchema = mongoose.Schema(
},
{
timestamps: true,
}
},
)

const Carousel = mongoose.model('Carousel', carouselSchema)
Expand Down
2 changes: 1 addition & 1 deletion backend/models/categoryModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const categorySchema = mongoose.Schema(
},
{
timestamps: true,
}
},
)

const Category = mongoose.model('Category', categorySchema)
Expand Down
8 changes: 6 additions & 2 deletions backend/models/orderModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ const orderSchema = mongoose.Schema(
qty: { type: String, required: true },
imageSrc: { type: String, required: true },
price: { type: String, required: true },
product: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Product' },
product: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Product',
},
},
],
shippingAddress: {
Expand Down Expand Up @@ -67,7 +71,7 @@ const orderSchema = mongoose.Schema(
},
{
timestamps: true,
}
},
)

const Order = mongoose.model('Order', orderSchema)
Expand Down
2 changes: 1 addition & 1 deletion backend/models/productModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const productSchema = mongoose.Schema(
},
{
timestamps: true,
}
},
)

const Product = mongoose.model('Product', productSchema)
Expand Down
7 changes: 5 additions & 2 deletions backend/models/userModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const userSchema = mongoose.Schema(
},
{
timestamps: true,
}
},
)

userSchema.methods.matchPassword = async function (enteredPassword) {
Expand All @@ -40,7 +40,10 @@ userSchema.methods.matchPassword = async function (enteredPassword) {

userSchema.methods.createPasswordResetToken = function () {
const resetToken = crypto.randomBytes(32).toString('hex')
this.passwordResetToken = crypto.createHash('sha256').update(resetToken).digest('hex')
this.passwordResetToken = crypto
.createHash('sha256')
.update(resetToken)
.digest('hex')
this.passwordResetExpires = Date.now() + 10 * 60 * 1000
return resetToken
}
Expand Down
8 changes: 5 additions & 3 deletions backend/routes/categoryRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ router.get(
asyncHandler(async (req, res) => {
const categories = await Category.find({})
res.json(categories)
})
}),
)

// @desc Fetch products based on category
Expand All @@ -23,15 +23,17 @@ router.get(
router.get(
'/:category',
asyncHandler(async (req, res) => {
const categorywiseProducts = await Product.find({ category: req.params.category })
const categorywiseProducts = await Product.find({
category: req.params.category,
})
// const categorywiseProducts = products.filter((p) => p.category === req.params.category)
if (categorywiseProducts) {
res.json(categorywiseProducts)
} else {
res.status(404)
throw new Error('Products not found')
}
})
}),
)

module.exports = router
5 changes: 4 additions & 1 deletion backend/routes/uploadRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ const storage = multer.diskStorage({
cb(null, 'uploads/')
},
filename(req, file, cb) {
cb(null, `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`)
cb(
null,
`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`,
)
},
})

Expand Down
5 changes: 4 additions & 1 deletion backend/routes/userRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ const router = express.Router()

router.route('/').post(registerUser).get(protect, admin, getUsers)
router.post('/login', authUser)
router.route('/profile').get(protect, getUserProfile).put(protect, updateUserProfile)
router
.route('/profile')
.get(protect, getUserProfile)
.put(protect, updateUserProfile)
router.post('/forgotpassword', forgotPassword)
router.patch('/resetpassword/:token', resetPassword)
router
Expand Down
28 changes: 14 additions & 14 deletions backend/seeder.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const dotenv = require("dotenv")
const users = require("./data/users")
const products = require("./data/products")
const categories = require("./data/categories")
const carousels = require("./data/carousels")
const User = require("./models/userModel")
const Carousel = require("./models/carouselModel")
const Category = require("./models/categoryModel")
const Product = require("./models/productModel")
const Order = require("./models/orderModel")
const connectDB = require("./config/db")
const dotenv = require('dotenv')
const users = require('./data/users')
const products = require('./data/products')
const categories = require('./data/categories')
const carousels = require('./data/carousels')
const User = require('./models/userModel')
const Carousel = require('./models/carouselModel')
const Category = require('./models/categoryModel')
const Product = require('./models/productModel')
const Order = require('./models/orderModel')
const connectDB = require('./config/db')

dotenv.config()

Expand All @@ -35,7 +35,7 @@ const importData = async () => {
await Carousel.insertMany(sampleCarousels)
await Category.insertMany(sampleCategories)
await Product.insertMany(sampleProducts)
console.log("Data Imported!")
console.log('Data Imported!')
process.exit()
} catch (error) {
console.error(error)
Expand All @@ -50,15 +50,15 @@ const destroyData = async () => {
await Category.deleteMany()
await Carousel.deleteMany()
await User.deleteMany()
console.log("Data Destroyed!")
console.log('Data Destroyed!')
process.exit()
} catch (error) {
console.error(error)
process.exit(1)
}
}

if (process.argv[2] === "-d") {
if (process.argv[2] === '-d') {
destroyData()
} else {
importData()
Expand Down
11 changes: 8 additions & 3 deletions backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../frontend/build')))

app.get('*', (req, res) =>
res.sendFile(path.resolve(__dirname, '..', 'frontend', 'build', 'index.html'))
res.sendFile(
path.resolve(__dirname, '..', 'frontend', 'build', 'index.html'),
),
)
} else {
app.get('/', (req, res) => {
Expand All @@ -49,5 +51,8 @@ app.use(errorHandler)

const PORT = process.env.PORT || 5000

app.listen(PORT, console.log(`Server is running in ${process.env.NODE_ENV} on port ${PORT}`))
module.exports=app
app.listen(
PORT,
console.log(`Server is running in ${process.env.NODE_ENV} on port ${PORT}`),
)
module.exports = app
Loading

0 comments on commit 074ecaf

Please sign in to comment.